code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
(() => { "use strict";
489Padovan sequence
10javascript
quwx8
const addMissingZeros = date => (/^\d$/.test(date) ? `0${date}` : date); const formatter = (date, readable) => { const year = date.getFullYear(); const month = addMissingZeros(date.getMonth() + 1); const day = addMissingZeros(date.getDate()); return readable ? `${year}-${month}-${day}` : `${year}${month}${day}`; }; function getPalindromeDates(start, palindromesToShow = 15) { let date = start || new Date(2020, 3, 2); for ( let i = 0; i < palindromesToShow; date = new Date(date.setDate(date.getDate() + 1)) ) { const formattedDate = formatter(date); if (formattedDate === formattedDate.split("").reverse().join("")) { i++; console.log(formatter(date, true)); } } } getPalindromeDates();
488Palindrome dates
10javascript
h6hjh
use Thread 'async'; use Thread::Queue; sub make_slices { my ($n, @avail) = (shift, @{ +shift }); my ($q, @part, $gen); $gen = sub { my $pos = shift; if (@part == $n) { $q->enqueue(\@part, \@avail); return; } return if (@part + @avail < $n); for my $i ($pos .. @avail - 1) { push @part, splice @avail, $i, 1; $gen->($i); splice @avail, $i, 0, pop @part; } }; $q = new Thread::Queue; (async{ &$gen; $q->enqueue(undef) })->detach; return $q; } my $qa = make_slices(4, [ 0 .. 9 ]); while (my $a = $qa->dequeue) { my $qb = make_slices(2, $qa->dequeue); while (my $b = $qb->dequeue) { my $rb = $qb->dequeue; print "@$a | @$b | @$rb\n"; } }
487Ordered partitions
2perl
p91b0
use Time::Piece; my $d = Time::Piece->strptime("2020-02-02", "%Y-%m-%d"); for (my $k = 1 ; $k <= 15 ; $d += Time::Piece::ONE_DAY) { my $s = $d->strftime("%Y%m%d"); if ($s eq reverse($s) and ++$k) { print $d->strftime("%Y-%m-%d\n"); } }
488Palindrome dates
2perl
q5qx6
use strict; use warnings; use feature <state say>; use List::Lazy 'lazy_list'; my $p = 1.32471795724474602596; my $s = 1.0453567932525329623; my %rules = (A => 'B', B => 'C', C => 'AB'); my $pad_recur = lazy_list { state @p = (1, 1, 1, 2); push @p, $p[1]+$p[2]; shift @p }; sub pad_floor { int 1/2 + $p**($_<3 ? 1 : $_-2) / $s } my($l, $m, $n) = (10, 20, 32); my(@pr, @pf); push @pr, $pad_recur->next() for 1 .. $n; say join ' ', @pr[0 .. $m-1]; push @pf, pad_floor($_) for 1 .. $n; say join ' ', @pf[0 .. $m-1]; my @L = 'A'; push @L, join '', @rules{split '', $L[-1]} for 1 .. $n; say join ' ', @L[0 .. $l-1]; $pr[$_] == $pf[$_] and $pr[$_] == length $L[$_] or die "Uh oh, n=$_: $pr[$_] vs $pf[$_] vs " . length $L[$_] for 0 .. $n-1; say '100% agreement among all 3 methods.';
489Padovan sequence
2perl
tbdfg
from itertools import combinations def partitions(*args): def p(s, *args): if not args: return [[]] res = [] for c in combinations(s, args[0]): s0 = [x for x in s if x not in c] for r in p(s0, *args[1:]): res.append([c] + r) return res s = range(sum(args)) return p(s, *args) print partitions(2, 0, 2)
487Ordered partitions
3python
1capc
pascalTriangle <- function(h) { for(i in 0:(h-1)) { s <- "" for(k in 0:(h-i)) s <- paste(s, " ", sep="") for(j in 0:i) { s <- paste(s, sprintf("%3d ", choose(i, j)), sep="") } print(s) } }
481Pascal's triangle
13r
mx5y4
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n: int) -> int: return floor(_p**(n-1) / _s + .5) def padovan_l(start: str='A', rules: Dict[str, str]=dict(A='B', B='C', C='AB') ) -> Generator[str, None, None]: axiom = start while True: yield axiom axiom = ''.join(rules[ch] for ch in axiom) if __name__ == : from itertools import islice print() print(str([padovan_f(n) for n in range(20)])[1:-1]) r_generator = padovan_r() if all(next(r_generator) == padovan_f(n) for n in range(64)): print() else: print() print() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) print('\n'.join(f for string in islice(l_generator, 10))) r_generator = padovan_r() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) for n in range(32)): print() else: print()
489Padovan sequence
3python
zpftt
'''Palindrome dates''' from datetime import datetime from itertools import chain def palinDay(y): '''A possibly empty list containing the palindromic date for the given year, if such a date exists. ''' s = str(y) r = s[::-1] iso = '-'.join([s, r[0:2], r[2:]]) try: datetime.strptime(iso, '%Y-%m-%d') return [iso] except ValueError: return [] def main(): '''Count and samples of palindromic dates [2021..9999] ''' palinDates = list(chain.from_iterable( map(palinDay, range(2021, 10000)) )) for x in [ 'Count of palindromic dates [2021..9999]:', len(palinDates), '\nFirst 15:', '\n'.join(palinDates[0:15]), '\nLast 15:', '\n'.join(palinDates[-15:]) ]: print(x) if __name__ == '__main__': main()
488Palindrome dates
3python
s4sq9
function ispalindrome(s) return s == string.reverse(s) end
483Palindrome detection
1lua
nh3i8
int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf(, ++count, s1, s2); int response; scanf(, &response); return response; } void printOrder(const char *items[], int len) { printf(); for (int i = 0; i < len; ++i) printf(, items[i]); printf(); } int main(void) { const char *items[] = { , , , , , , }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
490Order by pair comparisons
5c
v8c2o
def partition(mask) return [[]] if mask.empty? [*1..mask.inject(:+)].permutation.map {|perm| mask.map {|num_elts| perm.shift(num_elts).sort } }.uniq end
487Ordered partitions
14ruby
e2wax
use itertools::Itertools; type NArray = Vec<Vec<Vec<usize>>>; fn generate_partitions(args: &[usize]) -> NArray {
487Ordered partitions
15rust
wvxe4
padovan = Enumerator.new do |y| ar = [1, 1, 1] loop do ar << ar.first(2).sum y << ar.shift end end P, S = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n) = (P**(n-1) / S + 0.5).floor puts puts n = 63 bool = (0...n).map{|n| padovan_f(n)} == padovan.take(n) puts puts def l_system(axiom = , rules = { => , => , => } ) return enum_for(__method__, axiom, rules) unless block_given? loop do yield axiom axiom = axiom.chars.map{|c| rules[c] }.join end end puts , n = 32 bool = l_system.take(n).map(&:size) == padovan.take(n) puts
489Padovan sequence
14ruby
6az3t
require 'date' palindate = Enumerator.new do |yielder| (..).each do |y| m, d = y.reverse.scan(/../) strings = [y, m, d] yielder << strings.join() if Date.valid_date?( *strings.map( &:to_i ) ) end end puts palindate.take(15)
488Palindrome dates
14ruby
8r801
null
488Palindrome dates
15rust
o7o83
fn padovan_recur() -> impl std::iter::Iterator<Item = usize> { let mut p = vec![1, 1, 1]; let mut n = 0; std::iter::from_fn(move || { let pn = if n < 3 { p[n] } else { p[0] + p[1] }; p[0] = p[1]; p[1] = p[2]; p[2] = pn; n += 1; Some(pn) }) } fn padovan_floor() -> impl std::iter::Iterator<Item = usize> { const P: f64 = 1.324717957244746025960908854; const S: f64 = 1.0453567932525329623; (0..).map(|x| (P.powf((x - 1) as f64) / S + 0.5).floor() as usize) } fn padovan_lsystem() -> impl std::iter::Iterator<Item = String> { let mut str = String::from("A"); std::iter::from_fn(move || { let result = str.clone(); let mut next = String::new(); for ch in str.chars() { match ch { 'A' => next.push('B'), 'B' => next.push('C'), _ => next.push_str("AB"), } } str = next; Some(result) }) } fn main() { println!("First 20 terms of the Padovan sequence:"); for p in padovan_recur().take(20) { print!("{} ", p); } println!(); println!( "\nRecurrence and floor functions agree for first 64 terms? {}", padovan_recur().take(64).eq(padovan_floor().take(64)) ); println!("\nFirst 10 strings produced from the L-system:"); for p in padovan_lsystem().take(10) { print!("{} ", p); } println!(); println!( "\nLength of first 32 strings produced from the L-system = Padovan sequence? {}", padovan_lsystem() .map(|x| x.len()) .take(32) .eq(padovan_recur().take(32)) ); }
489Padovan sequence
15rust
ye368
import Foundation class PadovanRecurrence: Sequence, IteratorProtocol { private var p = [1, 1, 1] private var n = 0 func next() -> Int? { let pn = n < 3? p[n]: p[0] + p[1] p[0] = p[1] p[1] = p[2] p[2] = pn n += 1 return pn } } class PadovanFloor: Sequence, IteratorProtocol { private let P = 1.324717957244746025960908854 private let S = 1.0453567932525329623 private var n = 0 func next() -> Int? { let p = Int(floor(pow(P, Double(n - 1)) / S + 0.5)) n += 1 return p } } class PadovanLSystem: Sequence, IteratorProtocol { private var str = "A" func next() -> String? { let result = str var next = "" for ch in str { switch (ch) { case "A": next.append("B") case "B": next.append("C") default: next.append("AB") } } str = next return result } } print("First 20 terms of the Padovan sequence:") for p in PadovanRecurrence().prefix(20) { print("\(p)", terminator: " ") } print() var b = PadovanRecurrence().prefix(64) .elementsEqual(PadovanFloor().prefix(64)) print("\nRecurrence and floor functions agree for first 64 terms? \(b)") print("\nFirst 10 strings produced from the L-system:"); for p in PadovanLSystem().prefix(10) { print(p, terminator: " ") } print() b = PadovanLSystem().prefix(32).map{$0.count} .elementsEqual(PadovanRecurrence().prefix(32)) print("\nLength of first 32 strings produced from the L-system = Padovan sequence? \(b)")
489Padovan sequence
17swift
31tz2
import Foundation func isPalindrome(_ string: String) -> Bool { let chars = string.lazy return chars.elementsEqual(chars.reversed()) } let format = DateFormatter() format.dateFormat = "yyyyMMdd" let outputFormat = DateFormatter() outputFormat.dateFormat = "yyyy-MM-dd" var count = 0 let limit = 15 let calendar = Calendar.current var date = Date() while count < limit { if isPalindrome(format.string(from: date)) { print(outputFormat.string(from: date)) count += 1 } date = calendar.date(byAdding: .day, value: 1, to: date)! }
488Palindrome dates
17swift
0g0s6
package main import ( "fmt" "sort" "strings" ) var count int = 0 func interactiveCompare(s1, s2 string) bool { count++ fmt.Printf("(%d) Is%s <%s? ", count, s1, s2) var response string _, err := fmt.Scanln(&response) return err == nil && strings.HasPrefix(response, "y") } func main() { items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"} var sortedItems []string
490Order by pair comparisons
0go
s5wqa
def pascal(n) raise ArgumentError, if n < 1 yield ar = [1] (n-1).times do ar.unshift(0).push(0) yield ar = ar.each_cons(2).map(&:sum) end end pascal(8){|row| puts row.join().center(20)}
481Pascal's triangle
14ruby
uihvz
import Control.Monad import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM) import Data.Bool (bool) import Data.Monoid import Data.List isortM, msortM, tsortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a] msortM = sortByM isortM cmp = foldM (flip (insertByM cmp)) [] tsortM cmp = go where go [] = pure [] go (h:t) = do (l, g) <- partitionM (fmap (LT /=) . cmp h) t go l <+> pure [h] <+> go g (<+>) = liftM2 (++)
490Order by pair comparisons
8haskell
9x6mo
import java.util.*; public class SortComp1 { public static void main(String[] args) { List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange"); List<String> sortedItems = new ArrayList<>(); Comparator<String> interactiveCompare = new Comparator<String>() { int count = 0; Scanner s = new Scanner(System.in); public int compare(String s1, String s2) { System.out.printf("(%d) Is%s <, =, or >%s. Answer -1, 0, or 1: ", ++count, s1, s2); return s.nextInt(); } }; for (String item : items) { System.out.printf("Inserting '%s' into%s\n", item, sortedItems); int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
490Order by pair comparisons
9java
tbnf9
typedef char TWord[MAXLEN]; typedef struct Node { TWord word; struct Node *next; } Node; int is_ordered_word(const TWord word) { assert(word != NULL); int i; for (i = 0; word[i] != '\0'; i++) if (word[i] > word[i + 1] && word[i + 1] != '\0') return 0; return 1; } Node* list_prepend(Node* words_list, const TWord new_word) { assert(new_word != NULL); Node *new_node = malloc(sizeof(Node)); if (new_node == NULL) exit(EXIT_FAILURE); strcpy(new_node->word, new_word); new_node->next = words_list; return new_node; } Node* list_destroy(Node *words_list) { while (words_list != NULL) { Node *temp = words_list; words_list = words_list->next; free(temp); } return words_list; } void list_print(Node *words_list) { while (words_list != NULL) { printf(, words_list->word); words_list = words_list->next; } } int main() { FILE *fp = fopen(, ); if (fp == NULL) return EXIT_FAILURE; Node *words = NULL; TWord line; unsigned int max_len = 0; while (fscanf(fp, , line) != EOF) { if (strlen(line) > max_len && is_ordered_word(line)) { max_len = strlen(line); words = list_destroy(words); words = list_prepend(words, line); } else if (strlen(line) == max_len && is_ordered_word(line)) { words = list_prepend(words, line); } } fclose(fp); list_print(words); return EXIT_SUCCESS; }
491Ordered words
5c
9x3m1
unsigned int * seq_len(const unsigned int START, const unsigned int END) { unsigned start = (unsigned)START; unsigned end = (unsigned)END; if (START == END) { unsigned int *restrict sequence = malloc( (end+1) * sizeof(unsigned int)); if (sequence == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned i = 0; i < end; i++) { sequence[i] = i+1; } return sequence; } if (START > END) { end = (unsigned)START; start = (unsigned)END; } const unsigned LENGTH = end - start ; unsigned int *restrict sequence = malloc( (1+LENGTH) * sizeof(unsigned int)); if (sequence == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } if (START < END) { for (unsigned index = 0; index <= LENGTH; index++) { sequence[index] = start + index; } } else { for (unsigned index = 0; index <= LENGTH; index++) { sequence[index] = end - index; } } return sequence; } double *restrict base_arr = NULL; static int compar_increase (const void *restrict a, const void *restrict b) { int aa = *((int *restrict ) a), bb = *((int *restrict) b); if (base_arr[aa] < base_arr[bb]) { return 1; } else if (base_arr[aa] == base_arr[bb]) { return 0; } else { return -1; } } static int compar_decrease (const void *restrict a, const void *restrict b) { int aa = *((int *restrict ) a), bb = *((int *restrict) b); if (base_arr[aa] < base_arr[bb]) { return -1; } else if (base_arr[aa] == base_arr[bb]) { return 0; } else { return 1; } } unsigned int * order (const double *restrict ARRAY, const unsigned int SIZE, const bool DECREASING) { unsigned int *restrict idx = malloc(SIZE * sizeof(unsigned int)); if (idx == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } base_arr = malloc(sizeof(double) * SIZE); if (base_arr == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned int i = 0; i < SIZE; i++) { base_arr[i] = ARRAY[i]; idx[i] = i; } if (DECREASING == false) { qsort(idx, SIZE, sizeof(unsigned int), compar_decrease); } else if (DECREASING == true) { qsort(idx, SIZE, sizeof(unsigned int), compar_increase); } free(base_arr); base_arr = NULL; return idx; } double * cummin(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) { if (NO_OF_ARRAY_ELEMENTS < 1) { puts(); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } double *restrict output = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (output == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } double cumulative_min = ARRAY[0]; for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) { if (ARRAY[i] < cumulative_min) { cumulative_min = ARRAY[i]; } output[i] = cumulative_min; } return output; } double * cummax(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) { if (NO_OF_ARRAY_ELEMENTS < 1) { puts(); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } double *restrict output = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (output == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } double cumulative_max = ARRAY[0]; for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) { if (ARRAY[i] > cumulative_max) { cumulative_max = ARRAY[i]; } output[i] = cumulative_max; } return output; } double * pminx(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS, const double X) { if (NO_OF_ARRAY_ELEMENTS < 1) { puts(); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } double *restrict pmin_array = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (pmin_array == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { if (ARRAY[index] < X) { pmin_array[index] = ARRAY[index]; } else { pmin_array[index] = X; } } return pmin_array; } void double_say (const double *restrict ARRAY, const size_t NO_OF_ARRAY_ELEMENTS) { printf(, ARRAY[0]); for (unsigned int i = 1; i < NO_OF_ARRAY_ELEMENTS; i++) { printf(, ARRAY[i]); if (((i+1) % 5) == 0) { printf(, i+1); } } puts(); } double * uint2double (const unsigned int *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) { double *restrict doubleArray = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (doubleArray == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { doubleArray[index] = (double)ARRAY[index]; } return doubleArray; } double min2 (const double N1, const double N2) { if (N1 < N2) { return N1; } else { return N2; } } double * p_adjust (const double *restrict PVALUES, const unsigned int NO_OF_ARRAY_ELEMENTS, const char *restrict STRING) { if (NO_OF_ARRAY_ELEMENTS < 1) { puts(); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } short int TYPE = -1; if (STRING == NULL) { TYPE = 0; } else if (strcasecmp(STRING, ) == 0) { TYPE = 0; } else if (strcasecmp(STRING, ) == 0) { TYPE = 0; } else if (strcasecmp(STRING, ) == 0) { TYPE = 1; } else if (strcasecmp(STRING, ) == 0) { TYPE = 2; } else if (strcasecmp(STRING, ) == 0) { TYPE = 3; } else if (strcasecmp(STRING, ) == 0) { TYPE = 4; } else if (strcasecmp(STRING, ) == 0) { TYPE = 5; } else { printf(, STRING); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } if (TYPE == 2) { double *restrict bonferroni = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (bonferroni == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { const double BONFERRONI = PVALUES[index] * NO_OF_ARRAY_ELEMENTS; if (BONFERRONI >= 1.0) { bonferroni[index] = 1.0; } else if ((0.0 <= BONFERRONI) && (BONFERRONI < 1.0)) { bonferroni[index] = BONFERRONI; } else { printf(, BONFERRONI); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } } return bonferroni; } else if (TYPE == 4) { unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, false); double *restrict o2double = uint2double(o, NO_OF_ARRAY_ELEMENTS); double *restrict cummax_input = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); for (unsigned index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { cummax_input[index] = (NO_OF_ARRAY_ELEMENTS - index ) * (double)PVALUES[o[index]]; } free(o); o = NULL; unsigned int *restrict ro = order(o2double, NO_OF_ARRAY_ELEMENTS, false); free(o2double); o2double = NULL; double *restrict cummax_output = cummax(cummax_input, NO_OF_ARRAY_ELEMENTS); free(cummax_input); cummax_input = NULL; double *restrict pmin = pminx(cummax_output, NO_OF_ARRAY_ELEMENTS, 1); free(cummax_output); cummax_output = NULL; double *restrict qvalues = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { qvalues[index] = pmin[ro[index]]; } free(pmin); pmin = NULL; free(ro); ro = NULL; return qvalues; } else if (TYPE == 5) { unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, false); double *restrict p = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (p == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { p[index] = PVALUES[o[index]]; } double *restrict o2double = uint2double(o, NO_OF_ARRAY_ELEMENTS); free(o); o = NULL; unsigned int *restrict ro = order(o2double, NO_OF_ARRAY_ELEMENTS, false); free(o2double); o2double = NULL; double *restrict q = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (q == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } double *restrict pa = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (pa == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } double min = (double)NO_OF_ARRAY_ELEMENTS * p[0]; for (unsigned index = 1; index < NO_OF_ARRAY_ELEMENTS; index++) { const double TEMP = (double)NO_OF_ARRAY_ELEMENTS * p[index] / (double)(1+index); if (TEMP < min) { min = TEMP; } } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { pa[index] = min; q[index] = min; } for (unsigned j = (NO_OF_ARRAY_ELEMENTS-1); j >= 2; j--) { unsigned int *restrict ij = seq_len(0,NO_OF_ARRAY_ELEMENTS - j); const size_t I2_LENGTH = j - 1; unsigned int *restrict i2 = malloc(I2_LENGTH * sizeof(unsigned int)); for (unsigned i = 0; i < I2_LENGTH; i++) { i2[i] = NO_OF_ARRAY_ELEMENTS-j+2+i-1; } double q1 = (double)j * p[i2[0]] / 2.0; for (unsigned int i = 1; i < I2_LENGTH; i++) { const double TEMP_Q1 = (double)j * p[i2[i]] / (double)(2 + i); if (TEMP_Q1 < q1) { q1 = TEMP_Q1; } } for (unsigned int i = 0; i < (NO_OF_ARRAY_ELEMENTS - j + 1); i++) { q[ij[i]] = min2( (double)j*p[ij[i]], q1); } free(ij); ij = NULL; for (unsigned int i = 0; i < I2_LENGTH; i++) { q[i2[i]] = q[NO_OF_ARRAY_ELEMENTS - j]; } free(i2); i2 = NULL; for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) { if (pa[i] < q[i]) { pa[i] = q[i]; } } } free(p); p = NULL; for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { q[index] = pa[ro[index]]; } free(ro); ro = NULL; free(pa); pa = NULL; return q; } unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, true); if (o == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } double *restrict o_double = uint2double(o, NO_OF_ARRAY_ELEMENTS); for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { if ((PVALUES[index] < 0) || (PVALUES[index] > 1)) { printf(, index, PVALUES[index]); printf(, __FILE__, __LINE__); exit(EXIT_FAILURE); } } unsigned int *restrict ro = order(o_double, NO_OF_ARRAY_ELEMENTS, false); if (ro == NULL) { printf(, __FILE__, __LINE__); perror(); exit(EXIT_FAILURE); } free(o_double); o_double = NULL; double *restrict cummin_input = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS); if (TYPE == 0) { for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { const double NI = (double)NO_OF_ARRAY_ELEMENTS / (double)(NO_OF_ARRAY_ELEMENTS - index); cummin_input[index] = NI * PVALUES[o[index]]; } } else if (TYPE == 1) { double q = 1.0; for (unsigned int index = 2; index < (1+NO_OF_ARRAY_ELEMENTS); index++) { q += 1.0/(double)index; } for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { const double NI = (double)NO_OF_ARRAY_ELEMENTS / (double)(NO_OF_ARRAY_ELEMENTS - index); cummin_input[index] = q * NI * PVALUES[o[index]]; } } else if (TYPE == 3) { for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { cummin_input[index] = (double)(index + 1) * PVALUES[o[index]]; } } free(o); o = NULL; double *restrict cummin_array = NULL; cummin_array = cummin(cummin_input, NO_OF_ARRAY_ELEMENTS); free(cummin_input); cummin_input = NULL; double *restrict pmin = pminx(cummin_array, NO_OF_ARRAY_ELEMENTS, 1); free(cummin_array); cummin_array = NULL; double *restrict q_array = malloc(NO_OF_ARRAY_ELEMENTS*sizeof(double)); for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) { q_array[index] = pmin[ro[index]]; } free(ro); ro = NULL; free(pmin); pmin = NULL; return q_array; } int main(void) { const double PVALUES[] = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}; const double CORRECT_ANSWERS[6][50] = { {6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02}, {1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02}, {1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01}, {9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01}, {1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01}, { 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01} }; const char *restrict TYPES[] = {, , , , , }; for (unsigned short int type = 0; type <= 5; type++) { double *restrict q = p_adjust(PVALUES, sizeof(PVALUES) / sizeof(*PVALUES), TYPES[type]); double error = fabs(q[0] - CORRECT_ANSWERS[type][0]); for (unsigned int i = 1; i < sizeof(PVALUES) / sizeof(*PVALUES); i++) { const double this_error = fabs(q[i] - CORRECT_ANSWERS[type][i]); error += this_error; } double_say(q, sizeof(PVALUES) / sizeof(*PVALUES)); free(q); q = NULL; printf(, type, TYPES[type], error); } return 0; }
492P-value correction
5c
mwtys
fn pascal_triangle(n: u64) { for i in 0..n { let mut c = 1; for _j in 1..2*(n-1-i)+1 { print!(" "); } for k in 0..i+1 { print!("{:2} ", c); c = c * (i-k)/(k+1); } println!(); } }
481Pascal's triangle
15rust
5nkuq
def tri(row: Int): List[Int] = row match { case 1 => List(1) case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1 }
481Pascal's triangle
16scala
rt1gn
use strict; use warnings; sub ask { while( 1 ) { print "Compare $a to $b [<,=,>]: "; <STDIN> =~ /[<=>]/ and return +{qw( < -1 = 0 > 1 )}->{$&}; } } my @sorted = sort ask qw( violet red green indigo blue yellow orange ); print "sorted: @sorted\n";
490Order by pair comparisons
2perl
gdu4e
(defn is-sorted? [coll] (not-any? pos? (map compare coll (next coll)))) (defn take-while-eqcount [coll] (let [n (count (first coll))] (take-while #(== n (count %)) coll))) (with-open [rdr (clojure.java.io/reader "unixdict.txt")] (->> rdr line-seq (filter is-sorted?) (sort-by count >) take-while-eqcount (clojure.string/join ", ") println))
491Ordered words
6clojure
uocvi
def _insort_right(a, x, q): lo, hi = 0, len(a) while lo < hi: mid = (lo+hi) q += 1 less = input(f).strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q def order(items): ordered, q = [], 0 for item in items: q = _insort_right(ordered, item, q) return ordered, q if __name__ == '__main__': items = 'violet red green indigo blue yellow orange'.split() ans, questions = order(items) print('\n' + ' '.join(ans))
490Order by pair comparisons
3python
rf5gq
SAMPLES>write 18 / 2 * 3 + 7 34 SAMPLES>write 18 / (2 * 3) + 7 10
493Operator precedence
5c
4nc5t
package main import ( "fmt" "log" "math" "os" "sort" "strconv" "strings" ) type pvalues = []float64 type iv1 struct { index int value float64 } type iv2 struct{ index, value int } type direction int const ( up direction = iota down )
492P-value correction
0go
ach1f
items = [, , , , , , ] count = 0 sortedItems = [] items.each {|item| puts spotToInsert = sortedItems.bsearch_index{|x| count += 1 print gets.start_with?('y') } || sortedItems.length sortedItems.insert(spotToInsert, item) } p sortedItems
490Order by pair comparisons
14ruby
jzg7x
: \? = ~ /! # $% & * + - < > @ ^ ` | , '
493Operator precedence
6clojure
h35jr
import java.util.Arrays; import java.util.Comparator; public class PValueCorrection { private static int[] seqLen(int start, int end) { int[] result; if (start == end) { result = new int[end + 1]; for (int i = 0; i < result.length; ++i) { result[i] = i + 1; } } else if (start < end) { result = new int[end - start + 1]; for (int i = 0; i < result.length; ++i) { result[i] = start + i; } } else { result = new int[start - end + 1]; for (int i = 0; i < result.length; ++i) { result[i] = start - i; } } return result; } private static int[] order(double[] array, boolean decreasing) { int size = array.length; int[] idx = new int[size]; double[] baseArr = new double[size]; for (int i = 0; i < size; ++i) { baseArr[i] = array[i]; idx[i] = i; } Comparator<Integer> cmp; if (!decreasing) { cmp = Comparator.comparingDouble(a -> baseArr[a]); } else { cmp = (a, b) -> Double.compare(baseArr[b], baseArr[a]); } return Arrays.stream(idx) .boxed() .sorted(cmp) .mapToInt(a -> a) .toArray(); } private static double[] cummin(double[] array) { if (array.length < 1) throw new IllegalArgumentException("cummin requires at least one element"); double[] output = new double[array.length]; double cumulativeMin = array[0]; for (int i = 0; i < array.length; ++i) { if (array[i] < cumulativeMin) cumulativeMin = array[i]; output[i] = cumulativeMin; } return output; } private static double[] cummax(double[] array) { if (array.length < 1) throw new IllegalArgumentException("cummax requires at least one element"); double[] output = new double[array.length]; double cumulativeMax = array[0]; for (int i = 0; i < array.length; ++i) { if (array[i] > cumulativeMax) cumulativeMax = array[i]; output[i] = cumulativeMax; } return output; } private static double[] pminx(double[] array, double x) { if (array.length < 1) throw new IllegalArgumentException("pmin requires at least one element"); double[] result = new double[array.length]; for (int i = 0; i < array.length; ++i) { if (array[i] < x) { result[i] = array[i]; } else { result[i] = x; } } return result; } private static void doubleSay(double[] array) { System.out.printf("[ 1]%e", array[0]); for (int i = 1; i < array.length; ++i) { System.out.printf("%.10f", array[i]); if ((i + 1) % 5 == 0) System.out.printf("\n[%2d]", i + 1); } System.out.println(); } private static double[] intToDouble(int[] array) { double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i]; } return result; } private static double doubleArrayMin(double[] array) { if (array.length < 1) throw new IllegalArgumentException("pAdjust requires at least one element"); return Arrays.stream(array).min().orElse(Double.NaN); } private static double[] pAdjust(double[] pvalues, String str) { int size = pvalues.length; if (size < 1) throw new IllegalArgumentException("pAdjust requires at least one element"); int type; switch (str.toLowerCase()) { case "bh": case "fdr": type = 0; break; case "by": type = 1; break; case "bonferroni": type = 2; break; case "hochberg": type = 3; break; case "holm": type = 4; break; case "hommel": type = 5; break; default: throw new IllegalArgumentException(str + " doesn't match any accepted FDR types"); } if (type == 2) {
492P-value correction
9java
orx8d
typedef const char * String; typedef struct sTable { String * *rows; int n_rows,n_cols; } *Table; typedef int (*CompareFctn)(String a, String b); struct { CompareFctn compare; int column; int reversed; } sortSpec; int CmprRows( const void *aa, const void *bb) { String *rA = *(String *const *)aa; String *rB = *(String *const *)bb; int sortCol = sortSpec.column; String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol]; return sortSpec.compare( left, right ); } int sortTable(Table tbl, const char* argSpec,... ) { va_list vl; const char *p; int c; sortSpec.compare = &strcmp; sortSpec.column = 0; sortSpec.reversed = 0; va_start(vl, argSpec); if (argSpec) for (p=argSpec; *p; p++) { switch (*p) { case 'o': sortSpec.compare = va_arg(vl,CompareFctn); break; case 'c': c = va_arg(vl,int); if ( 0<=c && c<tbl->n_cols) sortSpec.column = c; break; case 'r': sortSpec.reversed = (0!=va_arg(vl,int)); break; } } va_end(vl); qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; } void printTable( Table tbl, FILE *fout, const char *colFmts[]) { int row, col; for (row=0; row<tbl->n_rows; row++) { fprintf(fout, ); for(col=0; col<tbl->n_cols; col++) { fprintf(fout, colFmts[col], tbl->rows[row][col]); } fprintf(fout, ); } fprintf(fout, ); } int ord(char v) { return v-'0'; } int cmprStrgs(String s1, String s2) { const char *p1 = s1; const char *p2 = s2; const char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++; } if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); } int main() { const char *colFmts[] = {,,}; String r1[] = { , , }; String r2[] = { , , }; String r3[] = { , , }; String r4[] = { , , }; String r5[] = { , , }; String r6[] = { , , }; String r7[] = { , , }; String r8[] = { , , }; String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 }; struct sTable table; table.rows = rows; table.n_rows = 8; table.n_cols = 3; sortTable(&table, ); printf(); printTable(&table, stdout, colFmts); sortTable(&table, , 1, &cmprStrgs); printf(); printTable(&table, stdout, colFmts); sortTable(&table, , 1); printf(); printTable(&table, stdout, colFmts); sortTable(&table, , 2, 1); printf(); printTable(&table, stdout, colFmts); return 0; }
494Optional parameters
5c
5imuk
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s %-10d %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
495OpenWebNet password
0go
20zl7
package main import ( "time" ole "github.com/go-ole/go-ole" "github.com/go-ole/go-ole/oleutil" ) func main() { ole.CoInitialize(0) unknown, _ := oleutil.CreateObject("Word.Application") word, _ := unknown.QueryInterface(ole.IID_IDispatch) oleutil.PutProperty(word, "Visible", true) documents := oleutil.MustGetProperty(word, "Documents").ToIDispatch() document := oleutil.MustCallMethod(documents, "Add").ToIDispatch() content := oleutil.MustGetProperty(document, "Content").ToIDispatch() paragraphs := oleutil.MustGetProperty(content, "Paragraphs").ToIDispatch() paragraph := oleutil.MustCallMethod(paragraphs, "Add").ToIDispatch() rnge := oleutil.MustGetProperty(paragraph, "Range").ToIDispatch() oleutil.PutProperty(rnge, "Text", "This is a Rosetta Code test document.") time.Sleep(10 * time.Second) oleutil.PutProperty(document, "Saved", true) oleutil.CallMethod(document, "Close", false) oleutil.CallMethod(word, "Quit") word.Release() ole.CoUninitialize() }
496OLE automation
0go
byukh
func pascal(n:Int)->[Int]{ if n==1{ let a=[1] print(a) return a } else{ var a=pascal(n:n-1) var temp=a for i in 0..<a.count{ if i+1==a.count{ temp.append(1) break } temp[i+1] = a[i]+a[i+1] } a=temp print(a) return a } } let waste = pascal(n:10)
481Pascal's triangle
17swift
voj2r
package main import ( "bufio" "crypto/rand" "fmt" "io/ioutil" "log" "math/big" "os" "strconv" "strings" "unicode" ) const ( charsPerLine = 48 chunkSize = 6 cols = 8 demo = true
497One-time pad
0go
njai1
function calcPass (pass, nonce) { var flag = true; var num1 = 0x0; var num2 = 0x0; var password = parseInt(pass, 10); for (var c in nonce) { c = nonce[c]; if (c!='0') { if (flag) num2 = password; flag = false; } switch (c) { case '1': num1 = num2 & 0xFFFFFF80; num1 = num1 >>> 7; num2 = num2 << 25; num1 = num1 + num2; break; case '2': num1 = num2 & 0xFFFFFFF0; num1 = num1 >>> 4; num2 = num2 << 28; num1 = num1 + num2; break; case '3': num1 = num2 & 0xFFFFFFF8; num1 = num1 >>> 3; num2 = num2 << 29; num1 = num1 + num2; break; case '4': num1 = num2 << 1; num2 = num2 >>> 31; num1 = num1 + num2; break; case '5': num1 = num2 << 5; num2 = num2 >>> 27; num1 = num1 + num2; break; case '6': num1 = num2 << 12; num2 = num2 >>> 20; num1 = num1 + num2; break; case '7': num1 = num2 & 0x0000FF00; num1 = num1 + (( num2 & 0x000000FF ) << 24 ); num1 = num1 + (( num2 & 0x00FF0000 ) >>> 16 ); num2 = ( num2 & 0xFF000000 ) >>> 8; num1 = num1 + num2; break; case '8': num1 = num2 & 0x0000FFFF; num1 = num1 << 16; num1 = num1 + ( num2 >>> 24 ); num2 = num2 & 0x00FF0000; num2 = num2 >>> 8; num1 = num1 + num2; break; case '9': num1 = ~num2; break; case '0': num1 = num2; break; } num2 = num1; } return (num1 >>> 0).toString(); } exports.calcPass = calcPass; console.log ('openpass initialization'); function testCalcPass (pass, nonce, expected) { var res = calcPass (pass, nonce); var m = pass + ' ' + nonce + ' ' + res + ' ' + expected; if (res == parseInt(expected, 10)) console.log ('PASS '+m); else console.log ('FAIL '+m); } testCalcPass ('12345', '603356072', '25280520'); testCalcPass ('12345', '410501656', '119537670'); testCalcPass ('12345', '630292165', '4269684735'); testCalcPass ('12345', '523781130', '537331200');
495OpenWebNet password
10javascript
19gp7
import win32com.client from win32com.server.util import wrap, unwrap from win32com.server.dispatcher import DefaultDebugDispatcher from ctypes import * import commands import pythoncom import winerror from win32com.server.exception import Exception clsid = iid = pythoncom.MakeIID(clsid) appid = class VeryPermissive: def __init__(self): self.data = [] self.handle = 0 self.dobjects = {} def __del__(self): pythoncom.RevokeActiveObject(self.handle) def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: return getattr(self,name)(*args) if wFlags & pythoncom.DISPATCH_PROPERTYGET: try: ret = self.__dict__[name] if type(ret)==type(()): ret = list(ret) return ret except KeyError: raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF): setattr(self, name, args[0]) return raise Exception(scode=winerror.E_INVALIDARG, desc=) def write(self, x): print x return 0 import win32com.server.util, win32com.server.policy child = VeryPermissive() ob = win32com.server.util.wrap(child, usePolicy=win32com.server.policy.DynamicPolicy) try: handle = pythoncom.RegisterActiveObject(ob, iid, 0) except pythoncom.com_error, details: print , details handle = None child.handle = handle ahk = win32com.client.Dispatch() ahk.aRegisterIDs(clsid, appid)
496OLE automation
3python
cqd9q
null
492P-value correction
11kotlin
xvpws
(defn sort [table & {:keys [ordering column reverse?] :or {ordering:lex, column 1}}] (println table ordering column reverse?)) (sort [1 8 3]:reverse? true) [1 8 3]:lex 1 true
494Optional parameters
6clojure
jzv7m
module OneTimePad (main) where import Control.Monad import Data.Char import Data.Function (on) import qualified Data.Text as T import qualified Data.Text.IO as TI import Data.Time import System.Console.GetOpt import System.Environment import System.Exit import System.IO data Options = Options { optCommand :: String , optInput :: IO T.Text , optOutput :: T.Text -> IO () , optPad :: (IO T.Text, T.Text -> IO ()) , optLines :: Int } startOptions :: Options startOptions = Options { optCommand = "decrypt" , optInput = TI.getContents , optOutput = TI.putStr , optPad = (TI.getContents, TI.putStr) , optLines = 0 } options :: [ OptDescr (Options -> IO Options) ] options = [ Option "e" ["encrypt"] (NoArg (\opt -> return opt { optCommand = "encrypt" })) "Encrypt file" , Option "d" ["decrypt"] (NoArg (\opt -> return opt { optCommand = "decrypt" })) "Decrypt file (default)" , Option "g" ["generate"] (NoArg (\opt -> return opt { optCommand = "generate" })) "Generate a one-time pad" , Option "i" ["input"] (ReqArg (\arg opt -> return opt { optInput = TI.readFile arg }) "FILE") "Input file (for decryption and encryption)" , Option "o" ["output"] (ReqArg (\arg opt -> return opt { optOutput = TI.writeFile arg }) "FILE") "Output file (for generation, decryption, and encryption)" , Option "p" ["pad"] (ReqArg (\arg opt -> return opt { optPad = (TI.readFile arg, TI.writeFile arg) }) "FILE") "One-time pad to use (for decryption and encryption)" , Option "l" ["lines"] (ReqArg (\arg opt -> return opt { optLines = read arg :: Int }) "LINES") "New one-time pad's length (in lines of 48 characters) (for generation)" , Option "V" ["version"] (NoArg (\_ -> do hPutStrLn stderr "Version 0.01" exitWith ExitSuccess)) "Print version" , Option "h" ["help"] (NoArg (\_ -> do prg <- getProgName putStrLn "usage: OneTimePad [-h] [-V] [ hPutStrLn stderr (usageInfo prg options) exitWith ExitSuccess)) "Show this help message and exit" ] main :: IO () main = do args <- getArgs let (actions, nonOptions, errors) = getOpt RequireOrder options args opts <- Prelude.foldl (>>=) (return startOptions) actions let Options { optCommand = command , optInput = input , optOutput = output , optPad = (inPad, outPad) , optLines = linecnt } = opts case command of "generate" -> generate linecnt output "encrypt" -> do inputContents <- clean <$> input padContents <- inPad output $ format $ encrypt inputContents $ unformat $ T.concat $ dropWhile (\t -> T.head t == '-' || T.head t == '#') $ T.lines padContents "decrypt" -> do inputContents <- unformat <$> input padContents <- inPad output $ decrypt inputContents $ unformat $ T.concat $ dropWhile (\t -> T.head t == '-' || T.head t == '#') $ T.lines padContents let discardLines = ceiling $ ((/) `on` fromIntegral) (T.length inputContents) 48 outPad $ discard discardLines $ T.lines padContents discard :: Int -> [T.Text] -> T.Text discard 0 ts = T.unlines ts discard x (t:ts) = if (T.head t == '-' || T.head t == '#') then T.unlines [t, (discard x ts)] else T.unlines [(T.append (T.pack "- ") t), (discard (x-1) ts)] clean :: T.Text -> T.Text clean = T.map toUpper . T.filter (\c -> let oc = ord c in oc >= 65 && oc <= 122 && (not $ oc >=91 && oc <= 96)) format :: T.Text -> T.Text format = T.unlines . map (T.intercalate (T.pack " ") . T.chunksOf 6) . T.chunksOf 48 unformat :: T.Text -> T.Text unformat = T.filter (\c -> c/='\n' && c/=' ') generate :: Int -> (T.Text -> IO ()) -> IO () generate lines output = do withBinaryFile "/dev/random" ReadMode (\handle -> do contents <- replicateM (48 * lines) $ hGetChar handle time <- getCurrentTime output $ T.unlines [ T.pack $ "# OTP pad, generated by https://github.com/kssytsrk/one-time-pad on " ++ show time , format $ T.pack $ map (chr . (65 +) . flip mod 26 . ord) contents ]) crypt :: (Int -> Int -> Int) -> T.Text -> T.Text -> T.Text crypt f = T.zipWith ((chr .) . f `on` ord) encrypt :: T.Text -> T.Text -> T.Text encrypt = crypt ((((+65) . flip mod 26 . subtract 130) .) . (+)) decrypt :: T.Text -> T.Text -> T.Text decrypt = crypt ((((+65) . flip mod 26) .) . (-))
497One-time pad
8haskell
uozv2
null
495OpenWebNet password
11kotlin
5iyua
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], s.ind[j] = s.ind[j], s.ind[i] } func disjointSliceSort(m, n []string) []string { s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))} used := make(map[int]bool) for _, nw := range n { for i, mw := range m { if used[i] || mw != nw { continue } used[i] = true s.ind = append(s.ind, i) break } } sort.Sort(s) return s.val.(sort.StringSlice) } func disjointStringSort(m, n string) string { return strings.Join( disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ") } func main() { for _, data := range []struct{ m, n string }{ {"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, } { mp := disjointStringSort(data.m, data.n) fmt.Printf("%s %s%s\n", data.m, data.n, mp) } }
498Order disjoint list items
0go
5izul
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OneTimePad { public static void main(String[] args) { String controlName = "AtomicBlonde"; generatePad(controlName, 5, 60, 65, 90); String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES"; String encrypted = parse(true, controlName, text.replaceAll(" ", "")); String decrypted = parse(false, controlName, encrypted); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); controlName = "AtomicBlondeCaseSensitive"; generatePad(controlName, 5, 60, 32, 126); text = "It was the best of times, it was the worst of times."; encrypted = parse(true, controlName, text); decrypted = parse(false, controlName, encrypted); System.out.println(); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); } private static String parse(boolean encryptText, String controlName, String text) { StringBuilder sb = new StringBuilder(); int minCh = 0; int maxCh = 0; Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$"); Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$"); boolean validated = false; try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) { String inLine = null; while ( (inLine = in.readLine()) != null ) { Matcher minMatcher = minChPattern.matcher(inLine); if ( minMatcher.matches() ) { minCh = Integer.parseInt(minMatcher.group(1)); continue; } Matcher maxMatcher = maxChPattern.matcher(inLine); if ( maxMatcher.matches() ) { maxCh = Integer.parseInt(maxMatcher.group(1)); continue; } if ( ! validated && minCh > 0 && maxCh > 0 ) { validateText(text, minCh, maxCh); validated = true; }
497One-time pad
9java
mwoym
use strict; use warnings; use feature 'say'; use integer; sub own_password { my($password, $nonce) = @_; my $n1 = 0; my $n2 = $password; for my $d (split //, $nonce) { if ($d == 1) { $n1 = ($n2 & 0xFFFFFF80) >> 7; $n2 <<= 25; } elsif ($d == 2) { $n1 = ($n2 & 0xFFFFFFF0) >> 4; $n2 <<= 28; } elsif ($d == 3) { $n1 = ($n2 & 0xFFFFFFF8) >> 3; $n2 <<= 29; } elsif ($d == 4) { $n1 = $n2 << 1; $n2 >>= 31; } elsif ($d == 5) { $n1 = $n2 << 5; $n2 >>= 27; } elsif ($d == 6) { $n1 = $n2 << 12; $n2 >>= 20; } elsif ($d == 7) { $n1 = ($n2 & 0x0000FF00) | (($n2 & 0x000000FF) << 24) | (($n2 & 0x00FF0000) >> 16); $n2 = ($n2 & 0xFF000000) >> 8; } elsif ($d == 8) { $n1 = ($n2 & 0x0000FFFF) << 16 | $n2 >> 24; $n2 = ($n2 & 0x00FF0000) >> 8; } elsif ($d == 9) { $n1 = ~$n2; } else { $n1 = $n2 } $n1 = ($n1 | $n2) & 0xFFFFFFFF if $d != 0 and $d != 9; $n2 = $n1; } $n1 } say own_password( 12345, 603356072 ); say own_password( 12345, 410501656 ); say own_password( 12345, 630292165 );
495OpenWebNet password
2perl
ora8x
void paint(void) { glClearColor(0.3,0.3,0.3,0.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glShadeModel(GL_SMOOTH); glLoadIdentity(); glTranslatef(-15.0, -15.0, 0.0); glBegin(GL_TRIANGLES); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0, 0.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(30.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.0, 30.0); glEnd(); glFlush(); } void reshape(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0); glMatrixMode(GL_MODELVIEW); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitWindowSize(640, 480); glutCreateWindow(); glutDisplayFunc(paint); glutReshapeFunc(reshape); glutMainLoop(); return EXIT_SUCCESS; }
499OpenGL
5c
s57q5
use strict; use warnings FATAL => 'all'; use autodie ':all'; use List::Util 'min'; use feature 'say'; sub pmin { my $array = shift; my $x = 1; my @pmin_array; my $n = scalar @$array; for (my $index = 0; $index < $n; $index++) { $pmin_array[$index] = min(@$array[$index], $x); } @pmin_array } sub cummin { my $array_ref = shift; my @cummin; my $cumulative_min = @$array_ref[0]; foreach my $p (@$array_ref) { if ($p < $cumulative_min) { $cumulative_min = $p; } push @cummin, $cumulative_min; } @cummin } sub cummax { my $array_ref = shift; my @cummax; my $cumulative_max = @$array_ref[0]; foreach my $p (@$array_ref) { if ($p > $cumulative_max) { $cumulative_max = $p; } push @cummax, $cumulative_max; } @cummax } sub order { my $array_ref = shift; my $decreasing = 'false'; if (defined $_[0]) { my $option = shift; if ($option =~ m/true/i) { $decreasing = 'true'; } elsif ($option =~ m/false/i) { } else { print "2nd option should only be case-insensitive 'true' or 'false'"; die; } } my @array; my $max_index = scalar @$array_ref-1; if ($decreasing eq 'false') { @array = sort { @$array_ref[$a] <=> @$array_ref[$b] } 0..$max_index; } elsif ($decreasing eq 'true') { @array = sort { @$array_ref[$b] <=> @$array_ref[$a] } 0..$max_index; } @array } sub p_adjust { my $pvalues_ref = shift; my $method; if (defined $_[0]) { $method = shift } else { $method = 'Holm' } my %methods = ( 'bh' => 1, 'fdr' => 1, 'by' => 1, 'holm' => 1, 'hommel' => 1, 'bonferroni' => 1, 'hochberg' => 1 ); my $method_found = 'no'; foreach my $key (keys %methods) { if ((uc $method) eq (uc $key)) { $method = $key; $method_found = 'yes'; last } } if ($method_found eq 'no') { if ($method =~ m/benjamini-?\s*hochberg/i) { $method = 'bh'; $method_found = 'yes'; } elsif ($method =~ m/benjamini-?\s*yekutieli/i) { $method = 'by'; $method_found = 'yes'; } } if ($method_found eq 'no') { print "No method could be determined from $method.\n"; die } my $lp = scalar @$pvalues_ref; my $n = $lp; my @qvalues; if ($method eq 'hochberg') { my @o = order($pvalues_ref, 'TRUE'); my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = ($index+1)* @$pvalues_ref[$o[$index]]; } my @cummin = cummin(\@cummin_input); my @pmin = pmin(\@cummin); my @ro = order(\@o); @qvalues = @pmin[@ro]; } elsif ($method eq 'bh') { my @o = order($pvalues_ref, 'TRUE'); my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = ($n/($n-$index))* @$pvalues_ref[$o[$index]]; } my @ro = order(\@o); my @cummin = cummin(\@cummin_input); my @pmin = pmin(\@cummin); @qvalues = @pmin[@ro]; } elsif ($method eq 'by') { my $q = 0.0; my @o = order($pvalues_ref, 'TRUE'); my @ro = order(\@o); for (my $index = 1; $index < ($n+1); $index++) { $q += 1.0 / $index; } my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = $q * ($n/($n-$index)) * @$pvalues_ref[$o[$index]]; } my @cummin = cummin(\@cummin_input); undef @cummin_input; my @pmin = pmin(\@cummin); @qvalues = @pmin[@ro]; } elsif ($method eq 'bonferroni') { for (my $index = 0; $index < $n; $index++) { my $q = @$pvalues_ref[$index]*$n; if ((0 <= $q) && ($q < 1)) { $qvalues[$index] = $q; } elsif ($q >= 1) { $qvalues[$index] = 1.0; } else { say 'Failed to get Bonferroni adjusted p.'; die; } } } elsif ($method eq 'holm') { my @o = order($pvalues_ref); my @cummax_input; for (my $index = 0; $index < $n; $index++) { $cummax_input[$index] = ($n - $index) * @$pvalues_ref[$o[$index]]; } my @ro = order(\@o); undef @o; my @cummax = cummax(\@cummax_input); undef @cummax_input; my @pmin = pmin(\@cummax); undef @cummax; @qvalues = @pmin[@ro]; } elsif ($method eq 'hommel') { my @o = order($pvalues_ref); my @p = @$pvalues_ref[@o]; my @ro = order(\@o); undef @o; my (@q, @pa); my $min = $n*$p[0]; for (my $index = 0; $index < $n; $index++) { my $temp = $n*$p[$index] / ($index + 1); $min = min($min, $temp); } for (my $index = 0; $index < $n; $index++) { $pa[$index] = $min; $q[$index] = $min; } for (my $j = ($n-1); $j >= 2; $j--) { my @ij = 0..($n - $j); my $I2_LENGTH = $j - 1; my @i2; for (my $i = 0; $i < $I2_LENGTH; $i++) { $i2[$i] = $n-$j+2+$i-1; } my $q1 = $j * $p[$i2[0]] / 2.0; for (my $i = 1; $i < $I2_LENGTH; $i++) { my $TEMP_Q1 = $j * $p[$i2[$i]] / (2 + $i); $q1 = min($TEMP_Q1, $q1); } for (my $i = 0; $i < ($n - $j + 1); $i++) { $q[$ij[$i]] = min( $j*$p[$ij[$i]], $q1); } for (my $i = 0; $i < $I2_LENGTH; $i++) { $q[$i2[$i]] = $q[$n - $j]; } for (my $i = 0; $i < $n; $i++) { if ($pa[$i] < $q[$i]) { $pa[$i] = $q[$i]; } } } @qvalues = @pa[@ro]; } else { print "$method doesn't fit my types.\n"; die } @qvalues } my @pvalues = (4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03); my %correct_answers = ( 'Benjamini-Hochberg' => [6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02], 'Benjamini-Yekutieli' => [1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02], 'Bonferroni' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01], 'Hochberg' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01], 'Holm' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01], 'Hommel' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01]); foreach my $method ('Hochberg','Benjamini-Hochberg','Benjamini-Yekutieli', 'Bonferroni', 'Holm', 'Hommel') { print "$method\n"; my @qvalues = p_adjust(\@pvalues, $method); my $error = 0.0; foreach my $q (0..$ $error += abs($qvalues[$q] - $correct_answers{$method}[$q]); } printf("type $method has cumulative error of%g.\n", $error); }
492P-value correction
2perl
20ylf
import Data.List (mapAccumL, sort) order :: Ord a => [[a]] -> [a] order [ms, ns] = snd . mapAccumL yu ls $ ks where ks = zip ms [(0 :: Int) ..] ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks yu ((u, v):us) (_, y) | v == y = (us, u) yu ys (x, _) = (ys, x) go (u:us, ys) (x, y) | u == x = (us, y: ys) go ts _ = ts task :: [String] -> IO () task ls@[ms, ns] = putStrLn $ "M: " ++ ms ++ " | N: " ++ ns ++ " |> " ++ (unwords . order . map words $ ls) main :: IO () main = mapM_ task [ ["the cat sat on the mat", "mat cat"] , ["the cat sat on the mat", "cat mat"] , ["A B C A B C A B C", "C A C A"] , ["A B C A B D A B E", "E A D A"] , ["A B", "B"] , ["A B", "B A"] , ["A B B A", "B A"] ]
498Order disjoint list items
8haskell
xvrw4
int list_cmp(int *a, int la, int *b, int lb) { int i, l = la; if (l > lb) l = lb; for (i = 0; i < l; i++) { if (a[i] == b[i]) continue; return (a[i] > b[i]) ? 1 : -1; } if (la == lb) return 0; return la > lb ? 1 : -1; }
500Order two numerical lists
5c
orh80
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1% expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1:= expr2 # assignment expr1 <- expr2 # reversible assignment expr1:=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
493Operator precedence
0go
orw8q
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1% expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1:= expr2 # assignment expr1 <- expr2 # reversible assignment expr1:=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
493Operator precedence
8haskell
206ll
null
481Pascal's triangle
20typescript
e2oaq
Julia Operators in Order of Preference -------------------------------------------- Syntax .followed by:: Exponentiation ^ Fractions
493Operator precedence
9java
6an3z
Julia Operators in Order of Preference -------------------------------------------- Syntax .followed by:: Exponentiation ^ Fractions
493Operator precedence
10javascript
ls3cf
null
497One-time pad
11kotlin
tbxf0
function ownCalcPass($password, $nonce) { $msr = 0x7FFFFFFF; $m_1 = (int)0xFFFFFFFF; $m_8 = (int)0xFFFFFFF8; $m_16 = (int)0xFFFFFFF0; $m_128 = (int)0xFFFFFF80; $m_16777216 = (int)0xFF000000; $flag = True; $num1 = 0; $num2 = 0; foreach (str_split($nonce) as $c) { $num1 = $num1 & $m_1; $num2 = $num2 & $m_1; if ($c == '1') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_128; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 6; $num2 = $num2 << 25; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '2') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_16; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 3; $num2 = $num2 << 28; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '3') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_8; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 2; $num2 = $num2 << 29; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '4') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 1; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 30; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '5') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 5; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 26; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '6') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 12; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 19; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '7') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFF00; $num1 = $num1 + (( $num2 & 0xFF ) << 24 ); $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 ); $num2 = $num2 & $m_16777216; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '8') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFFFF; $num1 = $num1 << 16; $numx = $num2 >> 1; $numx = $numx & $msr; $numx = $numx >> 23; $num1 = $num1 + $numx; $num2 = $num2 & 0xFF0000; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '9') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = ~(int)$num2; $flag = False; } else { $num1 = $num2; } $num2 = $num1; } return sprintf('%u', $num1 & $m_1); }
495OpenWebNet password
12php
gd942
(use 'penumbra.opengl) (require '[penumbra.app :as app]) (defn init [state] (app/title! "Triangle") (clear-color 0.3 0.3 0.3 0) (shade-model :smooth) state) (defn reshape [[x y w h] state] (ortho-view -30 30 -30 30 -30 30) (load-identity) (translate -15 -15) state) (defn display [[dt time] state] (draw-triangles (color 1 0 0) (vertex 0 0) (color 0 1 0) (vertex 30 0) (color 0 0 1) (vertex 0 30))) (app/start {:display display, :reshape reshape, :init init} {})
499OpenGL
6clojure
njpik
from __future__ import division import sys def pminf(array): x = 1 pmin_list = [] N = len(array) for index in range(N): if array[index] < x: pmin_list.insert(index, array[index]) else: pmin_list.insert(index, x) return pmin_list def cumminf(array): cummin = [] cumulative_min = array[0] for p in array: if p < cumulative_min: cumulative_min = p cummin.append(cumulative_min) return cummin def cummaxf(array): cummax = [] cumulative_max = array[0] for e in array: if e > cumulative_max: cumulative_max = e cummax.append(cumulative_max) return cummax def order(*args): if len(args) > 1: if args[1].lower() == 'false': return sorted(range(len(args[0])), key = lambda k: args[0][k]) elif list(args[1].lower()) == list('true'): return sorted(range(len(args[0])), key = lambda k: args[0][k], reverse = True) else: print % args[1] sys.exit() elif len(args) == 1: return sorted(range(len(args[0])), key = lambda k: args[0][k]) def p_adjust(*args): method = pvalues = args[0] if len(args) > 1: methods = {, , , , , , } metharg = arg[1].lower() if metharg in methods: method = metharg lp = len(pvalues) n = lp qvalues = [] if method == 'hochberg': o = order(pvalues, 'TRUE') cummin_input = [] for index in range(n): cummin_input.insert(index, (index+1)*pvalues[o[index]]) cummin = cumminf(cummin_input) pmin = pminf(cummin) ro = order(o) qvalues = [pmin[i] for i in ro] elif method == 'bh': o = order(pvalues, 'TRUE') cummin_input = [] for index in range(n): cummin_input.insert(index, (n/(n-index))* pvalues[o[index]]) ro = order(o) cummin = cumminf(cummin_input) pmin = pminf(cummin) qvalues = [pmin[i] for i in ro] elif method == 'by': q = 0.0 o = order(pvalues, 'TRUE') ro = order(o) for index in range(1, n+1): q += 1.0 / index; cummin_input = [] for index in range(n): cummin_input.insert(index, q * (n/(n-index)) * pvalues[o[index]]) cummin = cumminf(cummin_input) pmin = pminf(cummin) qvalues = [pmin[i] for i in ro] elif method == 'bonferroni': for index in range(n): q = pvalues[index] * n if (0 <= q) and (q < 1): qvalues.insert(index, q) elif q >= 1: qvalues.insert(index, 1) else: print '%g won\'t give a Bonferroni adjusted p'% q sys.exit() elif method == 'holm': o = order(pvalues) cummax_input = [] for index in range(n): cummax_input.insert(index, (n - index) * pvalues[o[index]]) ro = order(o) cummax = cummaxf(cummax_input) pmin = pminf(cummax) qvalues = [pmin[i] for i in ro] elif method == 'hommel': i = range(1,n+1) o = order(pvalues) p = [pvalues[index] for index in o] ro = order(o) pa = [] q = [] smin = n*p[0] for index in range(n): temp = n*p[index] / (index + 1) if temp < smin: smin = temp for index in range(n): pa.insert(index, smin) q.insert(index, smin) for j in range(n-1,1,-1): ij = range(1,n-j+2) for x in range(len(ij)): ij[x] -= 1 I2_LENGTH = j - 1 i2 = [] for index in range(I2_LENGTH+1): i2.insert(index, n - j + 2 + index - 1) q1 = j * p[i2[0]] / 2.0 for index in range(1,I2_LENGTH): TEMP_Q1 = j * p[i2[index]] / (2.0 + index) if TEMP_Q1 < q1: q1 = TEMP_Q1 for index in range(n - j + 1): q[ij[index]] = min(j * p[ij[index]], q1) for index in range(I2_LENGTH): q[i2[index]] = q[n-j] for index in range(n): if pa[index] < q[index]: pa[index] = q[index] qvalues = [pa[index] for index in ro] else: print % method sys.exit() return qvalues pvalues = [4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03] correct_answers = {} correct_answers['bh'] = [6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02] correct_answers['by'] = [1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02] correct_answers['bonferroni'] = [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01] correct_answers['hochberg'] = [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01] correct_answers['holm'] = [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01] correct_answers['hommel'] = [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01] for key in correct_answers.keys(): error = 0.0 q = p_adjust(pvalues, key) for i in range(len(q)): error += abs(q[i] - correct_answers[key][i]) print '%s error =%g'% (key.upper(), error)
492P-value correction
3python
v8m29
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}}; for (String[] a : MNs) { String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" ")); System.out.printf("%s |%s ->%s%n", a[0], a[1], Arrays.toString(r)); } }
498Order disjoint list items
9java
by2k3
As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence. Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}
493Operator precedence
11kotlin
dhsnz
use strict; use warnings; use Crypt::OTP; use Bytes::Random::Secure qw( random_bytes ); print "Message : ", my $message = "show me the monKey", "\n"; my $otp = random_bytes(length $message); print "Ord(OTP) : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n"; my $cipher = OTP( $otp, $message, 1 ); print "Ord(Cipher): ", ( map { ord($_).' ' } (split //, $cipher) ) , "\n"; print "Decoded : ", OTP( $otp, $cipher, 1 ), "\n";
497One-time pad
2perl
k62hc
def ownCalcPass (password, nonce, test=False): start = True num1 = 0 num2 = 0 password = int(password) if test: print(% (password)) for c in nonce: if c != : if start: num2 = password start = False if test: print(% (c, num1, num2)) if c == '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 elif c == '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 elif c == '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 elif c == '4': num1 = num2 << 1 num2 = num2 >> 31 elif c == '5': num1 = num2 << 5 num2 = num2 >> 27 elif c == '6': num1 = num2 << 12 num2 = num2 >> 20 elif c == '7': num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 ) num2 = ( num2 & 0xFF000000 ) >> 8 elif c == '8': num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 ) num2 = (num2 & 0x00FF0000) >> 8 elif c == '9': num1 = ~num2 else: num1 = num2 num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if (c not in ): num1 |= num2 if test: print(% (num1, num2)) num2 = num1 return num1 def test_passwd_calc(passwd, nonce, expected): res = ownCalcPass(passwd, nonce, False) m = passwd+' '+nonce+' '+str(res)+' '+str(expected) if res == int(expected): print('PASS '+m) else: print('FAIL '+m) if __name__ == '__main__': test_passwd_calc('12345','603356072','25280520') test_passwd_calc('12345','410501656','119537670') test_passwd_calc('12345','630292165','4269684735')
495OpenWebNet password
3python
i7eof
p <- c(4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03) p.adjust(p, method = 'BH') print("Benjamini-Hochberg") writeLines("\n") p.adjust(p, method = 'BY') print("Benjamini & Yekutieli") writeLines("\n") p.adjust(p, method = 'bonferroni') print("Bonferroni") writeLines("\n") p.adjust(p, method = 'hochberg') print("Hochberg") writeLines("\n"); p.adjust(p, method = 'hommel') writeLines("Hommel\n")
492P-value correction
13r
9xzmg
(() => { "use strict";
498Order disjoint list items
10javascript
w2ge2
(defn lex? [a b] (compare a b))
500Order two numerical lists
6clojure
tbafv
42:my-var 42 "my-var" define
493Operator precedence
1lua
fk0dp
null
498Order disjoint list items
11kotlin
rfygo
import argparse import itertools import pathlib import re import secrets import sys MAGIC = def make_keys(n, size): return (secrets.token_hex(size) for _ in range(n)) def make_pad(name, pad_size, key_size): pad = [ MAGIC, f, f, *make_keys(pad_size, key_size), ] return .join(pad) def xor(message, key): return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key))) def use_key(pad): match = re.search(r, pad, re.MULTILINE) if not match: error() key = match.group() pos = match.start() return (f, key) def log(msg): sys.stderr.write(msg) sys.stderr.write() def error(msg): sys.stderr.write(msg) sys.stderr.write() sys.exit(1) def write_pad(path, pad_size, key_size): if path.exists(): error(f) with path.open() as fd: fd.write(make_pad(path.name, pad_size, key_size)) log(f) def main(pad, message, outfile): if not pad.exists(): error(f) with pad.open() as fd: if fd.readline().strip() != MAGIC: error(f) with pad.open() as fd: updated, key = use_key(fd.read()) fd.seek(0) fd.write(updated) outfile.write(xor(message, bytes.fromhex(key))) if __name__ == : parser = argparse.ArgumentParser(description=) parser.add_argument( , help=( ), ) parser.add_argument( , type=int, default=10, help=, ) parser.add_argument( , type=int, default=64, help=, ) parser.add_argument( , , type=argparse.FileType(), default=sys.stdout.buffer, help=( ), ) group = parser.add_mutually_exclusive_group() group.add_argument( , metavar=, type=argparse.FileType(), help=, ) group.add_argument( , metavar=, type=argparse.FileType(), help=, ) args = parser.parse_args() if args.encrypt: message = args.encrypt.read() elif args.decrypt: message = args.decrypt.read() else: message = None if isinstance(message, str): message = message.encode() pad = pathlib.Path(args.pad).with_suffix() if message: main(pad, message, args.outfile) else: write_pad(pad, args.length, args.key_size)
497One-time pad
3python
byvkr
func openAuthenticationResponse(_password: String, operations: String) -> String? { var num1 = UInt32(0) var num2 = UInt32(0) var start = true let password = UInt32(_password)! for c in operations { if (c!= "0") { if start { num2 = password } start = false } switch c { case "1": num1 = (num2 & 0xffffff80) >> 7 num2 = num2 << 25 case "2": num1 = (num2 & 0xfffffff0) >> 4 num2 = num2 << 28 case "3": num1 = (num2 & 0xfffffff8) >> 3 num2 = num2 << 29 case "4": num1 = num2 << 1 num2 = num2 >> 31 case "5": num1 = num1 << 5 num2 = num2 >> 27 case "6": num1 = num2 << 12 num2 = num2 >> 20 case "7": num1 = (num2 & 0x0000ff00) | ((num2 & 0x000000ff) << 24) | ((num2 & 0x00ff0000) >> 16) num2 = (num2 & 0xff000000) >> 8 case "8": num1 = ((num2 & 0x0000ffff) << 16) | (num2 >> 24) num2 = (num2 & 0x00ff0000) >> 8 case "9": num1 = ~num2 case "0": num1 = num2 default: print("unexpected char \(c)") return nil } if (c!= "9") && (c!= "0") { num1 |= num2 } num2 = num1 } return String(num1) }
495OpenWebNet password
17swift
njwil
int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {,,,,,,,,,,,,}; double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6}; if(argC!=3) printf(); else{ for(i=0;argV[2][i]!=00;i++) argV[2][i] = tolower(argV[2][i]); for(i=0;i<UNITS_LENGTH;i++){ if(strstr(argV[2],units[i])!=NULL){ reference = i; factor = atof(argV[1])*values[i]; break; } } printf(,argV[1],argV[2]); for(i=0;i<UNITS_LENGTH;i++){ if(i!=reference) printf(,factor/values[i],units[i]); } } return 0; }
501Old Russian measure of length
5c
19lpj
def pmin(array) x = 1 pmin_array = [] array.each_index do |i| pmin_array[i] = [array[i], x].min abort if pmin_array[i] > 1 end pmin_array end def cummin(array) cumulative_min = array[0] arr_cummin = [] array.each do |p| cumulative_min = [p, cumulative_min].min arr_cummin.push(cumulative_min) end arr_cummin end def cummax(array) cumulative_max = array[0] arr_cummax = [] array.each do |p| cumulative_max = [p, cumulative_max].max arr_cummax.push(cumulative_max) end arr_cummax end def order(array, decreasing = false) if decreasing == false array.sort.map { |n| array.index(n) } else array.sort.map { |n| array.index(n) }.reverse end end def p_adjust(arr_pvalues, method = 'Holm') lp = arr_pvalues.size n = lp if method.casecmp('hochberg').zero? arr_o = order(arr_pvalues, true) arr_cummin_input = [] (0..n).each do |index| arr_cummin_input[index] = (index + 1) * arr_pvalues[arr_o[index].to_i] end arr_cummin = cummin(arr_cummin_input) arr_pmin = pmin(arr_cummin) arr_ro = order(arr_o) return arr_pmin.values_at(*arr_ro) elsif method.casecmp('bh').zero? || method.casecmp('benjamini-hochberg').zero? arr_o = order(arr_pvalues, true) arr_cummin_input = [] (0..(n - 1)).each do |i| arr_cummin_input[i] = (n / (n - i).to_f) * arr_pvalues[arr_o[i]] end arr_ro = order(arr_o) arr_cummin = cummin(arr_cummin_input) arr_pmin = pmin(arr_cummin) return arr_pmin.values_at(*arr_ro) elsif method.casecmp('by').zero? || method.casecmp('benjamini-yekutieli').zero? q = 0.0 arr_o = order(arr_pvalues, true) arr_ro = order(arr_o) (1..n).each do |index| q += 1.0 / index end arr_cummin_input = [] (0..(n - 1)).each do |i| arr_cummin_input[i] = q * (n / (n - i).to_f) * arr_pvalues[arr_o[i]] end arr_cummin = cummin(arr_cummin_input) arr_pmin = pmin(arr_cummin) return arr_pmin.values_at(*arr_ro) elsif method.casecmp('bonferroni').zero? arr_qvalues = [] (0..(n - 1)).each do |i| q = arr_pvalues[i] * n if (q >= 0) && (q < 1) arr_qvalues[i] = q elsif q >= 1 arr_qvalues[i] = 1.0 else puts end end return arr_qvalues elsif method.casecmp('holm').zero? o = order(arr_pvalues) cummax_input = [] (0..(n - 1)).each do |index| cummax_input[index] = (n - index) * arr_pvalues[o[index]] end ro = order(o) arr_cummax = cummax(cummax_input) arr_pmin = pmin(arr_cummax) return arr_pmin.values_at(*ro) elsif method.casecmp('hommel').zero? o = order(arr_pvalues) arr_p = arr_pvalues.values_at(*o) ro = order(o) q = [] pa = [] min = n * arr_p[0] (0..(n - 1)).each do |index| temp = n * arr_p[index] / (index + 1) min = [min, temp].min end (0..(n - 1)).each do |index| pa[index] = min q[index] = min end j = n - 1 while j >= 2 ij = Array 0..(n - j) i2_length = j - 1 i2 = [] (0..(i2_length - 1)).each do |i| i2[i] = n - j + 2 + i - 1 end q1 = j * arr_p[i2[0]] / 2.0 (1..(i2_length - 1)).each do |i| temp_q1 = j * arr_p[i2[i]] / (2 + i) q1 = [temp_q1, q1].min end (0..(n - j)).each do |i| tmp = j * arr_p[ij[i]] q[ij[i]] = [tmp, q1].min end (0..(i2_length - 1)).each do |i| q[i2[i]] = q[n - j] end (0..(n - 1)).each do |i| pa[i] = q[i] if pa[i] < q[i] end j -= 1 end return pa.values_at(*ro) else puts abort end end pvalues = [4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03] correct_answers = { 'Benjamini-Hochberg' => [6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02], 'Benjamini-Yekutieli' => [1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02], 'Bonferroni' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01], 'Hochberg' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01], 'Holm' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01], 'Hommel' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01] } methods = ['Benjamini-Yekutieli', 'Benjamini-Hochberg', 'Hochberg', 'Bonferroni', 'Holm', 'Hommel'] methods.each do |method| puts method error = 0.0 arr_q = p_adjust(pvalues, method) arr_q.each_index do |p| error += (correct_answers[method][p] - arr_q[p]) end puts end
492P-value correction
14ruby
5icuj
null
498Order disjoint list items
1lua
7tmru
inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf(, r[i], i == 9 ? '\n':' '); return 0; }
502One of n lines in a file
5c
tbpf4
use std::iter; #[rustfmt::skip] const PVALUES:[f64;50] = [ 4.533_744e-01, 7.296_024e-01, 9.936_026e-02, 9.079_658e-02, 1.801_962e-01, 8.752_257e-01, 2.922_222e-01, 9.115_421e-01, 4.355_806e-01, 5.324_867e-01, 4.926_798e-01, 5.802_978e-01, 3.485_442e-01, 7.883_130e-01, 2.729_308e-01, 8.502_518e-01, 4.268_138e-01, 6.442_008e-01, 3.030_266e-01, 5.001_555e-02, 3.194_810e-01, 7.892_933e-01, 9.991_834e-01, 1.745_691e-01, 9.037_516e-01, 1.198_578e-01, 3.966_083e-01, 1.403_837e-02, 7.328_671e-01, 6.793_476e-02, 4.040_730e-03, 3.033_349e-04, 1.125_147e-02, 2.375_072e-02, 5.818_542e-04, 3.075_482e-04, 8.251_272e-03, 1.356_534e-03, 1.360_696e-02, 3.764_588e-04, 1.801_145e-05, 2.504_456e-07, 3.310_253e-02, 9.427_839e-03, 8.791_153e-04, 2.177_831e-04, 9.693_054e-04, 6.610_250e-05, 2.900_813e-02, 5.735_490e-03 ]; #[derive(Debug)] enum CorrectionType { BenjaminiHochberg, BenjaminiYekutieli, Bonferroni, Hochberg, Holm, Hommel, Sidak, } enum SortDirection { Increasing, Decreasing, }
492P-value correction
15rust
4nl5u
type cell string type spec struct { less func(cell, cell) bool column int reverse bool } func newSpec() (s spec) {
494Optional parameters
0go
8ga0g
def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) { table.sort(false) { x, y -> (reverse ? -1: 1) * ordering.compare(x[column], y[column])} }
494Optional parameters
7groovy
w2hel
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500)
503Numerical and alphabetical suffixes
0go
quuxz
sub dsort { my ($m, $n) = @_; my %h; $h{$_}++ for @$n; map $h{$_}-- > 0 ? shift @$n : $_, @$m; } for (split "\n", <<"IN") the cat sat on the mat | mat cat the cat sat on the mat | cat mat A B C A B C A B C | C A C A A B C A B D A B E | E A D A A B | B A B | B A A B B A | B A IN { my ($a, $b) = map([split], split '\|'); print "@$a | @$b -> @{[dsort($a, $b)]}\n"; }
498Order disjoint list items
2perl
dhanw
data SorterArgs = SorterArgs { cmp :: String, col :: Int, rev :: Bool } deriving Show defSortArgs = SorterArgs "lex" 0 False sorter :: SorterArgs -> [[String]] -> [[String]] sorter (SorterArgs{..}) = case cmp of _ -> undefined main = do sorter defSortArgs{cmp = "foo", col=1, rev=True} [[]] sorter defSortArgs{cmp = "foo"} [[]] sorter defSortArgs [[]] return ()
494Optional parameters
8haskell
lszch
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
493Operator precedence
2perl
jzu7f
use strict; use warnings; my %suffix = qw( k 1e3 m 1e6 g 1e9 t 1e12 p 1e15 e 1e18 z 1e21 y 1e24 x 1e27 w 1e30 v 1e33 u 1e36 ki 2**10 mi 2**20 gi 2**30 ti 2**40 pi 2**50 ei 2**60 zi 2**70 yi 2**80 xi 2**90 wi 2**100 vi 2**110 ui 2**120 ); local $" = ' '; print "numbers = ${_}results = @{[ map suffix($_), split ]}\n\n" while <DATA>; sub suffix { my ($value, $mods) = shift =~ tr/,//dr =~ /([+-]?[\d.]+(?:e[+-]\d+)?)(.*)/i; $value *= $^R while $mods =~ / PAIRs? (?{ 2 }) | SCO(re?)? (?{ 20 }) | DOZ(e(ns?)?)? (?{ 12 }) | GREATGR(o(ss?)?)? (?{ 1728 }) | GR(o(ss?)?)? (?{ 144 }) | GOOGOLs? (?{ 10**100 }) | [kmgtpezyxwvu]i? (?{ eval $suffix{ lc $& } }) | !+ (?{ my $factor = $value; $value *= $factor while ($factor -= length $&) > 1; 1 }) /gix; return $value =~ s/(\..*)|\B(?=(\d\d\d)+(?!\d))/$1 || ','/ger; } __DATA__ 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre 1,567 +1.567k 0.1567e-2m 25.123kK 25.123m 2.5123e-00002G 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei -.25123e-34Vikki 2e-77gooGols 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
503Numerical and alphabetical suffixes
2perl
4nn5d
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
493Operator precedence
12php
tb8f1
(defn rand-seq-elem [sequence] (let [f (fn [[k old] new] [(inc k) (if (zero? (rand-int k)) new old)])] (->> sequence (reduce f [1 nil]) second))) (defn one-of-n [n] (rand-seq-elem (range 1 (inc n)))) (let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))] (doseq [[n cnt] (sort countmap)] (println n cnt)))
502One of n lines in a file
6clojure
mwxyq
import java.util.*; public class OptionalParams {
494Optional parameters
9java
31ozg
#!/usr/bin/env node import { writeFileSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
497One-time pad
20typescript
fkwds
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols', 6, 10, 100), ('ki', 2, 2, 10), ('mi', 2, 2, 20), ('gi', 2, 2, 30), ('ti', 2, 2, 40), ('pi', 2, 2, 50), ('ei', 2, 2, 60), ('zi', 2, 2, 70), ('yi', 2, 2, 80), ('xi', 2, 2, 90), ('wi', 2, 2, 100), ('vi', 2, 2, 110), ('ui', 2, 2, 120), ('k', 1, 10, 3), ('m', 1, 10, 6), ('g', 1, 10, 9), ('t', 1, 10, 12), ('p', 1, 10, 15), ('e', 1, 10, 18), ('z', 1, 10, 21), ('y', 1, 10, 24), ('x', 1, 10, 27), ('w', 1, 10, 30) ] num = num.replace(',', '').strip().lower() if num[-1].isdigit(): return float(num) for i, char in enumerate(reversed(num)): if char.isdigit(): input_suffix = num[-i:] num = Decimal(num[:-i]) break if input_suffix[0] == '!': return reduce(mul, range(int(num), 0, -len(input_suffix))) while len(input_suffix) > 0: for suffix, min_abbrev, base, power in suffixes: if input_suffix[:min_abbrev] == suffix[:min_abbrev]: for i in range(min_abbrev, len(input_suffix) + 1): if input_suffix[:i+1] != suffix[:i+1]: num *= base ** power input_suffix = input_suffix[i:] break break return num test = for test_line in test.split(): test_cases = test_line.split() print(, ' '.join(test_cases)) print(, ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
503Numerical and alphabetical suffixes
3python
gdd4h
package main import ( gl "github.com/chsc/gogl/gl21" "github.com/go-gl/glfw/v3.2/glfw" "log" "runtime" )
499OpenGL
0go
v8d2m
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) itemindices += lastindex[1:] itemindices.sort() for index, item in zip(itemindices, items): data[index] = item if __name__ == '__main__': tostring = ' '.join for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')), (str.split('the cat sat on the mat'), str.split('cat mat')), (list('ABCABCABC'), list('CACA')), (list('ABCABDABE'), list('EADA')), (list('AB'), list('B')), (list('AB'), list('BA')), (list('ABBA'), list('BA')), (list(''), list('')), (list('A'), list('A')), (list('AB'), list('')), (list('ABBA'), list('AB')), (list('ABAB'), list('AB')), (list('ABAB'), list('BABA')), (list('ABCCBA'), list('ACAC')), (list('ABCCBA'), list('CACA')), ]: print('Data M:%-24r Order N:%-9r'% (tostring(data), tostring(items)), end=' ') order_disjoint_list_items(data, items) print(% tostring(data))
498Order disjoint list items
3python
fkede
function sorter(table, options) { opts = {} opts.ordering = options.ordering || 'lexicographic'; opts.column = options.column || 0; opts.reverse = options.reverse || false;
494Optional parameters
10javascript
cqt9j
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
493Operator precedence
3python
h35jw
package Palindrome; use strict; use warnings; use Exporter 'import'; our @EXPORT = qw(palindrome palindrome_c palindrome_r palindrome_e); sub palindrome { my $s = (@_ ? shift : $_); return $s eq reverse $s; } sub palindrome_c { my $s = (@_ ? shift : $_); for my $i (0 .. length($s) >> 1) { return 0 unless substr($s, $i, 1) eq substr($s, -1 - $i, 1); } return 1; } sub palindrome_r { my $s = (@_ ? shift : $_); if (length $s <= 1) { return 1; } elsif (substr($s, 0, 1) ne substr($s, -1, 1)) { return 0; } else { return palindrome_r(substr($s, 1, -1)); } } sub palindrome_e { (@_ ? shift : $_) =~ /^(.?|(.)(?1)\2)$/ + 0 }
483Palindrome detection
2perl
rtbgd
static int owp(int odd) { int ch, ret; ch = getc(stdin); if (!odd) { putc(ch, stdout); if (ch == EOF || ch == '.') return EOF; if (ispunct(ch)) return 0; owp(odd); return 0; } else { if (ispunct(ch)) return ch; ret = owp(odd); putc(ch, stdout); return ret; } } int main(int argc, char **argv) { int ch = 1; while ((ch = owp(!ch)) != EOF) { if (ch) putc(ch, stdout); if (ch == '.') break; } return 0; }
504Odd word problem
5c
pmyby
double Pi; double lroots[N]; double weight[N]; double lcoef[N + 1][N + 1] = {{0}}; void lege_coef() { int n, i; lcoef[0][0] = lcoef[1][1] = 1; for (n = 2; n <= N; n++) { lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; for (i = 1; i <= n; i++) lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1] - (n - 1) * lcoef[n - 2][i] ) / n; } } double lege_eval(int n, double x) { int i; double s = lcoef[n][n]; for (i = n; i; i--) s = s * x + lcoef[n][i - 1]; return s; } double lege_diff(int n, double x) { return n * (x * lege_eval(n, x) - lege_eval(n - 1, x)) / (x * x - 1); } void lege_roots() { int i; double x, x1; for (i = 1; i <= N; i++) { x = cos(Pi * (i - .25) / (N + .5)); do { x1 = x; x -= lege_eval(N, x) / lege_diff(N, x); } while ( fdim( x, x1) > 2e-16 ); lroots[i - 1] = x; x1 = lege_diff(N, x); weight[i - 1] = 2 / ((1 - x * x) * x1 * x1); } } double lege_inte(double (*f)(double), double a, double b) { double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0; int i; for (i = 0; i < N; i++) sum += weight[i] * f(c1 * lroots[i] + c2); return c1 * sum; } int main() { int i; Pi = atan2(1, 1) * 4; lege_coef(); lege_roots(); printf(); for (i = 0; i < N; i++) printf(, lroots[i]); printf(); for (i = 0; i < N; i++) printf(, weight[i]); printf( , lege_inte(exp, -3, 3), exp(3) - exp(-3)); return 0; }
505Numerical integration/Gauss-Legendre Quadrature
5c
w2cec
import Graphics.Rendering.OpenGL import Graphics.UI.GLUT main = do getArgsAndInitialize createWindow "Triangle" displayCallback $= display matrixMode $= Projection loadIdentity ortho2D 0 30 0 30 matrixMode $= Modelview 0 mainLoop display = do clear [ColorBuffer] renderPrimitive Triangles $ do corner 1 0 0 5 5 corner 0 1 0 25 5 corner 0 0 1 5 25 swapBuffers corner r g b x y = do color (Color3 r g b :: Color3 GLfloat) vertex (Vertex2 x y :: Vertex2 GLfloat)
499OpenGL
8haskell
el5ai
package main import "fmt"
500Order two numerical lists
0go
4nt52
package main import ( "bytes" "fmt" "io/ioutil" ) func main() {
491Ordered words
0go
elba6