As you can tell, I didn't try to golf this at all. I'm a music geek, and a pet peeve of mine is when people write things using the wrong enharmonics (e.g. saying that a C diminished chord is C D# F# instead of C Eb Gb), so I wrote this program that gets the enharmonics right. It does so by representing each note as the number of perfect fifths above F.

For what it's worth, if you want to distinguish enharmonics, any musical interval can be represented nicely in a computer program as a number of perfect fifths and a number of octaves. An augmented fourth, for example, is 6 perfect fifths and -3 octaves, and a diminished fifth is -6 perfect fifths and 4 octaves.

Haskell, 441 characters

import Data.List

notes = "FCGDAEB"

fromNum x = [notes !! (mod x 7)] ++ if x < 0 then replicate (-(div x 7)) 'b' else replicate (div x 7) '#'

toNum (x:xs) = y + 7 * if isPrefixOf "b" xs then -length xs else length xs
    where Just y = elemIndex x notes

chord xs = unwords . map (fromNum . \x -> toNum (init xs) + x) $ case last xs of 'A' -> [0,4,8]; 'M' -> [0,4,1]; 'm' -> [0,-3,1]; 'd' -> [0,-3,-6]

main = getLine >>= putStrLn . chord

Some example invocations:

jaspers:junk tswett$ ./chord
AM
A C# E
jaspers:junk tswett$ ./chord
C#m
C# E G#
jaspers:junk tswett$ ./chord
DbA
Db F A
jaspers:junk tswett$ ./chord
Cd
C Eb Gb
jaspers:junk tswett$ ./chord
A#M
A# C## E#
jaspers:junk tswett$ ./chord
Dbm
Db Fb Ab


Jelly, 41 37 29 bytes

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷

Try it online!

How it works

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷  Main link. Argument: n (integer)

R                              Range; yield [1, ..., n].
 D                             Decimal; yield A =: [[1], ..., [1, 0], ...].
  µ                            Begin a new, monadic chain. Argument: A
   Ḍ                           Undecimal; convert back to falt range.
    ’                          Decrement to yield [0, ..., n-1].
     ½Ċ                        Take the square root and round up (ceil).
       -*                      Elevate -1 to each rounded square root.
         _\                    Cumulatively reduce by subtraction.
                               This yields [1, 2, 1, 0, -1, 0, ...], i.e., the
                               vertical positions of the digits in A.
             L€                Compute the length of each list in A.
           x                   Repeat the nth position l times, where l is the
                               nth length.
            ©                  Copy the result to the register.
               Ṣ               Sort.
                .ị             At-index 0.5; yield the last and first element,
                               which correspond to the highest and lowest position.
                  ạ€®          Take the absolute difference of each position in the
                               register and the extrema.
                               This yields the number of spaces above and below
                               the integers in r as a list of pairs.
                     ⁶ẋ        Replace each difference with that many spaces.
                         F     Flatten the list A.
                       j"      Join the nth pair of strings of spacing, separating
                               by the nth digit in flat A.
                          Z    Zip/transpose the result.
                           j⁷  Join, separating by linefeeds.


Check if a string is entirely made of the same substring

JavaScript (ES6), 22 bytes

Returns a Boolean value.

s=>/^(.*)\1+$/.test(s)

Try it online!

Without a regular expression,  33  29 bytes

Returns either null (falsy) or an object (truthy).

s=>(s+s).slice(1,-1).match(s)

Try it online!

NB: Technically, \$s\$ is converted to a regular expression for match(), so the above title is a lie.


Shortest self-modifying code to wish a happy New Year!

Bash / shell script (35 chars - 10% = 31.5)
I think this shell script counts as self-modifying:

$ eval "y()(echo Happy `date +%Y`)";y
Happy 2013
$

At least, it does modify its own function y:

$ set | grep -A3 '^y ()'
y ()
{
    ( echo Happy 2015 )
}
$

@manatwork suggested eval "y()(date +Happy\ %Y)";y, which produces the desired output, but I'm not sure if this counts as self-modifying, to the extent that it self-modifies with the current year.  The generated function is as follows, which won't be a different function on a yearly basis:

y ()
{
    ( date +Happy\ %Y )
}

If it does count, then the score is:
Bash / shell script (29 chars - 10% = 26.1)

A lot of entries don't seem to make any attempt to self-modify.  If we lift this restriction for shell-script, then we can do this which weighs in at:
15 chars - 10% = 13
date +Happy\ %Y


Jelly, 3 bytes

ṭFẠ

F flattens the input list.

ṭ tacks on the original input list as an element, which is falsy if and only if it is empty.

Ạ then checks if any element in the flattened list, or the original list itself, is falsy.

(Original answer)

FẠ^Ṇ

Thanks to Dennis for encouraging finding a solution matching his.

FẠ gives 0 if the input contains a falsy value at any depth, else 1. This is what Ȧ does, except for empty lists.

Ṇ gives 1 if the input is a falsy value, else 0. The only falsy list is the empty list.

XOR-ing the two gives the answer.

F;WẠ

This is much in the same spirit as Dennis's F;LẠ, but instead of using L to put a zero in the list when the list is empty, it uses W to put the empty list into itself (producing [[]]), making it contain a falsy element.


Python, 3 bytes ÷ 1 op = score 3

min

Try it online!
Implements AND, with inputs like ["1", "AND", "0", "AND", "0"]. Simply takes the smallest string value, which is "0" if present and "1" otherwise. Since "AND" is later alphabetically, it can be ignored.
Another solution is all, using inputs like [1, "AND", 0, "AND", 0] since only 0 is Falsey. Python 2 could also do min with such inputs, since it has numbers as smaller than strings, whereas Python 3 refuses to compare them.


Rust, score 1412 1411

src/main.rs

extern crate gmp;

use std::collections::BinaryHeap;
use std::collections::hash_map::{HashMap, Entry};
use gmp::mpz::Mpz;

fn visit(
    queue: &mut BinaryHeap<(i32, i32, i32, Mpz, Mpz)>,
    visited: &mut HashMap<(i32, Mpz), i32>,
    score: i32,
    h: i32,
    k: i32,
    d: Mpz,
    c: Mpz,
) {
    match visited.entry((k, d.clone())) {
        Entry::Occupied(mut e) => {
            if *e.get() < score {
                e.insert(score);
                queue.push((score, h, k, d, c));
            }
        }
        Entry::Vacant(e) => {
            e.insert(score);
            queue.push((score, h, k, d, c));
        }
    }
}

fn main() {
    let mut total = 0;
    for n in 1..21 {
        let a_range = n / 2 - n + 1..n / 2 + 1;
        let min_ab = a_range.start * (a_range.end - 1);
        let mut ab = Mpz::zero();
        for a in a_range.clone() {
            for b in a_range.clone() {
                ab.setbit((a * b - min_ab) as usize);
            }
        }

        let heuristic = |k: i32, d: &Mpz| if k == n {
            0
        } else {
            k + 1 - n -
                (0..d.bit_length())
                    .map(|i| (&ab & !(d >> i)).popcount())
                    .min()
                    .unwrap() as i32
        };

        let mut queue = BinaryHeap::new();
        let mut visited = HashMap::new();

        let (k1, d1) = (0, Mpz::zero());
        let h1 = heuristic(k1, &d1);
        visit(&mut queue, &mut visited, h1, h1, k1, d1, Mpz::zero());
        while let Some((score, h, k, d, c)) = queue.pop() {
            if k == n {
                println!("n={} |S|={}", n, -score);
                println!("  A={:?}", a_range.clone().collect::<Vec<_>>());
                println!("  B={:?}", a_range.clone().collect::<Vec<_>>());
                println!(
                    "  C={:?}",
                    (0..c.bit_length())
                        .filter(|&i| c.tstbit(c.bit_length() - 1 - i))
                        .collect::<Vec<_>>()
                );
                total += -score;
                break;
            }

            let kd = (k, d);
            if score < visited[&kd] {
                continue;
            }
            let (k, d) = kd;

            let (k1, d1) = (k, &d >> 1);
            let h1 = heuristic(k1, &d1);
            visit(
                &mut queue,
                &mut visited,
                score - h + h1,
                h1,
                k1,
                d1,
                &c << 1,
            );

            let (k1, d1) = (k + 1, (&d | &ab) >> 1);
            let h1 = heuristic(k1, &d1);
            visit(
                &mut queue,
                &mut visited,
                score - h - (&ab & !&d).popcount() as i32 + h1,
                h1,
                k1,
                d1,
                &c << 1 | Mpz::one(),
            );
        }
    }

    println!("total={}", total);
}

Cargo.toml

[package]
name = "small"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]

[dependencies]
rust-gmp = "0.5.0"

Compile and run with cargo run --release.

Output

n=1 |S|=1
  A=[0]
  B=[0]
  C=[0]
n=2 |S|=3
  A=[0, 1]
  B=[0, 1]
  C=[0, 1]
n=3 |S|=5
  A=[-1, 0, 1]
  B=[-1, 0, 1]
  C=[0, 1, 2]
n=4 |S|=10
  A=[-1, 0, 1, 2]
  B=[-1, 0, 1, 2]
  C=[0, 1, 2, 3]
n=5 |S|=13
  A=[-2, -1, 0, 1, 2]
  B=[-2, -1, 0, 1, 2]
  C=[0, 1, 2, 3, 4]
n=6 |S|=21
  A=[-2, -1, 0, 1, 2, 3]
  B=[-2, -1, 0, 1, 2, 3]
  C=[0, 2, 3, 4, 5, 6]
n=7 |S|=25
  A=[-3, -2, -1, 0, 1, 2, 3]
  B=[-3, -2, -1, 0, 1, 2, 3]
  C=[0, 2, 3, 5, 6, 7, 8]
n=8 |S|=35
  A=[-3, -2, -1, 0, 1, 2, 3, 4]
  B=[-3, -2, -1, 0, 1, 2, 3, 4]
  C=[0, 3, 4, 6, 7, 8, 10, 11]
n=9 |S|=39
  A=[-4, -3, -2, -1, 0, 1, 2, 3, 4]
  B=[-4, -3, -2, -1, 0, 1, 2, 3, 4]
  C=[0, 3, 4, 6, 7, 8, 10, 11, 14]
n=10 |S|=53
  A=[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  B=[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  C=[0, 1, 4, 5, 6, 9, 10, 11, 14, 15]
n=11 |S|=58
  A=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  B=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  C=[0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 19]
n=12 |S|=74
  A=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  B=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  C=[0, 4, 5, 6, 9, 10, 11, 12, 15, 16, 17, 21]
n=13 |S|=80
  A=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  B=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  C=[0, 4, 5, 6, 9, 10, 11, 12, 15, 16, 17, 21, 22]
n=14 |S|=100
  A=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
  B=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
  C=[0, 1, 6, 7, 8, 12, 13, 14, 15, 19, 20, 21, 26, 27]
n=15 |S|=106
  A=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
  B=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
  C=[0, 5, 6, 7, 11, 12, 13, 14, 18, 19, 20, 21, 25, 26, 27]
n=16 |S|=128
  A=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
  B=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
  C=[0, 6, 7, 8, 13, 14, 15, 16, 20, 21, 22, 23, 28, 29, 30, 36]
n=17 |S|=135
  A=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
  B=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
  C=[0, 6, 7, 8, 13, 14, 15, 16, 20, 21, 22, 23, 28, 29, 30, 36, 44]
n=18 |S|=161
  A=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  B=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  C=[0, 7, 8, 9, 15, 16, 17, 18, 23, 24, 25, 26, 27, 32, 33, 34, 35, 41]
n=19 |S|=167
  A=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  B=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  C=[0, 7, 8, 9, 15, 16, 17, 18, 23, 24, 25, 26, 27, 32, 33, 34, 35, 41, 42]
n=20 |S|=197
  A=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  B=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  C=[0, 1, 8, 9, 10, 11, 17, 18, 19, 20, 21, 26, 27, 28, 29, 30, 36, 37, 38, 46]
total=1411

On my laptop, this used about 8 minutes and about 1.5 GiB of memory.

How it works

We assume (without any particular justification) that A and B are the obvious range of consecutive integers centered at 0 or ½, then do an A* search for an optimal C given A and B.


Forth

Please find, below, a sphere outside the box.

The "sphere" is the volume-computing function f. The reference test cases compose the "box".

                     ( x y z d -- v )
                 : f { F: z F: d } d f2/
              { F: r } fmin { F: m } m f2/ {
             F: b } d m f<= d z f<= and if 0e
             else r r r f* b b f* f- fsqrt f-
              { F: t } d m f<= t z f> or if d
               z f- else d t f- then r 3e f*
                  fover f- pi f* fover f*
                      f* 3e f/ then ;

                     1e                 1e
                     1e                 1e
                     f                  f.
            cr       1e        1e       0e
            1e       f         f.       cr
            1e       1e 0.5e 1e f f. cr 1e
            0.999e 1e          1e     f
            f.  cr            0.1e 1e
            1.000e 0.500e f f. cr

Output:

0.
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212


Randomly select a character, plinko-style

Lean Mean Bean Machine, 55 43 42 bytes
-13 bytes thanks to Alex Varga
  O
  i
  ^
 ^ ^
\ ^ ^
 i / U
 ii
 ^
i U
U

Hope you guys don't mind me answering my own question after only 2 hours, but I highly doubt anybody else was planning on posting an answer in LMBM.
This literally just reflects the Plinko layout shown in the OP, flipped horizontally to cut down on unnecessary whitespace.


Haskell, 15 bytes

a#b=b++b#(a++b)

Try it online!
Takes strings a and b as input, returns the whole infinite Fibonacci word, as is usually allowed in sequence challenges.
How?
Not much to say. This answer relies on the identity
$$
F(a,b)=b+F(b,a+b),
$$
where \$F(a,b)\$ is the infinite Fibonacci word with starting words \$a\$ and \$b\$.


Program that encodes a message into its own text

Perl

This is a one-liner in Perl just because it's possible.

if($ARGV[0]){open(F,__FILE__);while(<F>){print;print"$ARGV[0]\n"if/^_/;}}else{print<DATA>;}
__DATA__

The messages are written after __DATA__, most recent first.


JavaScript (ES6), 219 bytes
Takes input as a list of lists of characters.
a=>((g=(X,Y,D,n=o=0)=>!(a+0)[n++]|a.some((r,y)=>r.some((c,x)=>D=='975'[i='-| #+$'.indexOf(c),x-X+1]-'450'[y-Y+1]?i-3?i-2?i>3?[3,0,7,4].some(d=>D^d^4&&g(x,y,d,n)):~i&&i^D&1?0:g(x,y,D,n):0:o=-n:X+1|i<5?0:g(x,y,2))))(),~o)

Try it online!
How?
Because they need to be tried in a specific order, the way the directions are handled in this code is a bit unusual.
Given a direction \$D\$ and the source coordinates \$(X,Y)\$, we want to figure out which target coordinates \$(x,y)\$ correspond to a move by one square along \$D\$.
We use the following test for each candidate pair \$(x,y)\$:
D == '975'[x - X + 1] - '450'[y - Y + 1]

This test always fails if \$|x-X|>1\$ or \$|y-Y|>1\$ because we get an undefined value from at least one of the 2 lookup strings.
Otherwise, we have the following table:
$$\begin{array}{r|c|ccc}
&x-X&-1&0&+1\\
\hline
y-Y&&9&7&5\\
\hline
-1&-4&5&3&1\\
0&-5&4&2&0\\
+1&-0&9&7&5
\end{array}$$
Because diagonal moves are not used, our final compass looks as follows:
$$\begin{array}{cccc}
&&3\\
&&↑\\
4&←&2&→&0\\
&&↓\\
&&7
\end{array}$$
The lookup values were chosen in such a way that we end up with some handy properties:

Opposite directions can be detected by testing if \$d\operatorname{xor}d'=4\$. Hence the code to try all directions in clockwise order except the one that would make us going back the way we came:
    [3, 0, 7, 4].some(d => D ^ d ^ 4 && g(x, y, d, n))

Vertical moves are connected to odd values.

Horizontal moves are connected to even values (except direction \$2\$, for no move at all, which is only used at the beginning of the process when the starting point has been identified).


JavaScript (ES6), 238

c=s=>{X={M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}
n=eval('W='+s.replace(/[\w]+/g,n=>(o=0,n.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,d=>o+=X[d]),
o+';W=W')));o='';for(i in X)while(n>=X[i])o+=i,n-=X[i];return o}

Usage:

c("XIX + LXXX")
> "XCIX"
c('XCIX + I / L * D + IV')
> "MIV"

Annotated version:

/**
 * Process basic calculation for roman numerals.
 *
 * @param {String} s The calculation to perform
 * @return {String} The result in roman numerals
 */
c = s => {
  // Create a lookup table.
  X = {
    M: 1e3, CM: 900, D: 500, CD: 400, C: 100, XC: 90,
    L: 50,  XL: 40,  X: 10,  IX: 9,   V: 5,   IV: 4, I: 1
  };
  // Do the calculation.
  //
  // The evaluated string is instrumented to as below:
  //   99+1/50*500+4 -> W=99;W=W+1;W=W/50;W=W*500;W=W+4;W=W
  //                 -> 1004
  n = eval('W=' + s.replace(
    // Match all roman numerals.
    /[\w]+/g,
    // Convert the roman number into an integer.
    n => (
      o = 0,
      n.replace(
        /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        d => o += X[d]
      ),
      // Instrument number to operate left-side operations.
      o + ';W=W'
    )
  ));

  // Convert the result into roman numerals.
  o = '';
  for (i in X)
    while (n >= X[i])
      o += i,
      n -= X[i];

  // Return calculation result.
  return o
}


Pyth, 23 bytes

M&tG.^HsgBu-G/GH{PGGhHG

Defines a function g, taking m and n in that order.

Try it online

How it works

M&tG.^HsgBu-G/GH{PGGhHG
M                         def g(G, H):
 &tG                        0 if G == 1, else …
                 PG         prime factors of G
                {           deduplicate that
          u-G/GH   G        reduce that on lambda G,H:G-G/H, starting at G
                              (this gives the Euler totient φ(G))
        gB          hH      bifurcate: two-element list [that, g(that, H + 1)]
       s                    sum
    .^H               G     H^that mod G

Python 2, 109 76 bytes

import sympy
def g(n,m):j=sympy.totient(m);return m-1and pow(n,j+g(n+1,j),m)

Try it online!

Why it works

We use the following generalization of Euler’s theorem.

Lemma. n2φ(m) ≡ nφ(m) (mod m) for all n (whether or not n is coprime to m).

Proof: For all prime powers pk dividing m,

If p divides n, then because φ(m) ≥ φ(pk) = pk − 1(p − 1) ≥ 2k − 1 ≥ k, we have n2φ(m) ≡ 0 ≡ nφ(m) (mod pk).
Otherwise, because φ(pk) divides φ(m), Euler’s theorem gives n2φ(m) ≡ 1 ≡ nφ(m) (mod pk).

Therefore, n2φ(m) ≡ nφ(m) (mod m).

Corollary. If k ≥ φ(m), then nk ≡ nφ(m) + (k mod φ(m)) (mod m).

Proof: If k ≥ 2φ(m), the lemma gives nk = n2φ(m)nk - 2φ(m) ≡ nφ(m)nk - 2φ(m) = nk - φ(m) (mod m) and we repeat until the exponent is less than 2φ(m).


Detect Rectangular Text with Rectangular Code

C (gcc), 127 125 124 118 bytes

Saved two bytes by golfing r*=!e&(!t|t==c); to r>>=e||t&&t-c;. (This golf was the inspiration for my recent C tips answer Inverse flag update.)
Saved a byte by golfing *(_-2) to _[~1].
Saved six bytes by golfing *_++-10||(...) to *_++<11?...:0 and utilizing the placeholder zero ...:0 (which is not used constructively) to golf the c++ increment. Those golfs allowed some further loop reshuffling.
When one can use multiple falsey values, 114 bytes could be possible.

r,e,c,t;_(char*_){for(r=1,t=c=0;*_;*_++<11?r*=(t||(t=c,!e))&*_>32&_[~1]>32&t==c,c=e=0:c++)*_-32||(e=1);r>>=e||t&&t-c;}

Try it online!

Source layout achieving a taller rectangle.

Explanation

The following explains the 124 bytes long version.

r,e,c,t;_(char*_){     // `r` is the boolean result flag, `e` a boolean flag if the current line contains
                       //  a space, `t` the first line's width, `c` the current line's current width
 for(r=1,t=c=0;*_;c++) // initialize, loop through entire string
  *_-32||              // if the current char is a space,
   (e=1),              //  the current line contains a space
  *_++-10||            // if the current char is a newline (char pointer `_` now incremented)
   (r*=(t||(t=c,!e))   // if t is not yet set, the current line is the first line; set it
                       //  to this line's length, check that no spaces where found
    &*_>32             // the next line's first char should not be a space
    &_[~1]>32          // this line's last char should not have been a space
    &t==c,c=~0,e=0);   // the line lengths should match, reset `c` and `e` to zero
                       //  (`~0 == -1`, countering the loop's increment of `c`)
 r>>=e||t&&t-c;}       // return boolean flag, check that the last line does not contain spaces,
                       //  there was either no newline or line lengths match
                       //  (here) equivalent to `r*=!e&(!t|t==c)`

Try it online!


If no animation is required, you can skip the void draw() and put everything into void setup().
Initialising the size of the canvas is sometimes not necessary - it will be initialised to (100, 100) by default.
If you need to use height and width in your code, it is usually shorter to use their numeric values instead. For example, with a canvas of size (100, 100), using 99 to replace height and width can save you 7 bytes.


Improvise a Hardware Random-Number Generator

Shell
Reads a single sample from the microphone stream and prints its least-significant bit, which should be dominated by noise.
EDIT: Changed to unmute the microphone ... and everything else too!
# Warning - unmutes EVERYTHING!
for DEV in `amixer | grep Simple | sed -e "s/.*'\(.*\)'.*/\\1/" -e "s/ /~/g"`
do
    amixer -q -- sset "`echo $DEV | sed 's/~/ /g'`" unmute 100% 2>/dev/null
done

echo $(( `od -N1 -d < /dev/dsp | head -n1 | sed 's/.* //'` & 1 ))


Implement range function without using numbers in code

Javascript (49)(45)
As feersum said, I do not know why anyone would have to use numbers here.
f=(a,b)=>{for(c=[];a<b;c.push(a++));return c}

Old:
f=(a,b)=>{c=[];for(;a<b;a++){c.push(a);}return c}

I am sure it can be golfed down further=)


Jelly, 28 bytes

“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ

A monadic link taking a list and returning a list of lists.

Try it online! (the footer separates the resulting list of lists with spaces)

How?

Uses all the percentages in the distribution rounded to their nearest integer (thus being within the 0.69% allowed thresholds).

“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ - Link: list (of characters), s
“¤Œæ×¿®¬©¥¤‘                 - code page indexes = [3,19,22,17,11,8,7,6,4,3]
               $             - last two links as a monad:
            J                -   range of length = [1, 2, 3, 4, 5,6,7,8,9,10]
              "              -   zip with:
             ẋ               -     repeat list = [[1,1,1],...,[9,9,9,9],[10,10,10]]
                F            - flatten (into one list of length 100)
                  L          - length of s
                 ẋ           - repeat list (one list of length 100*length(s) with the
                             -              correct distribution of integer lengths)
                   Ẋ         - shuffle
                      ¦      - sparse application of:
                    ‘        -   increment
                     1       -   to indexes: 1 (offset indexes for the partition below)
                        \    - cumulative reduce by:
                       +     -   addition (e.g. [4,4,7,1,...] -> [4,8,15,16,...])
                         Ṭ   - untruth (yield a list with 1s at those indexes (1 indexed)
                          œṗ - partition s at truthy indexes (note: excess ignored)


Write a function that tells you which of its lines has been removed

Ruby

Eschewing magic numbers since it's not code golf.

def f
  r=2^3^4^5
  defined?(r) ? r^=2 : r=1^3^4^5
  r^=3
  r^=4
  r^=5
end

Each line strips its own number out of 1^2^3^4^5. It's Ruby, so the last line defines the return value.


BBC Basic, 187 176 ASCII characters, tokenised filesize 155 140
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
Saved some characters: instead of using MOD to always generate random numbers that differ than the previous value, I simply generate any number and perform a check instead.
b=0f=0w=0REPEATc=b g=f x=w REPEATb=RND(6)f=RND(6)w=RND(6)UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x)VDU17,b+128,17,f:PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4):WAIT 99UNTIL0

I used the original BBC Basic 3-bit colour codings, which are based on 1's bit=Red, 2's bit=Green, 4's bit=Blue. I renamed Yellow as Gold, Magenta as Pink and Green as Lime (justifiable given the shade produced) in order to shorten colour names. I also renamed Cyan as Aqua just because. Therefore I use colours 1 to 6 from the 3-bit scheme. I exclude 0=black and 7=white (a very light grey, as the full white belongs to the extended 16-colour set in which the 8`s bit refers to brightness.)
b=0 f=0 w=0                                     :REM initialise "old" values for background, foreground and word.
REPEAT
  c=b g=f x=w                                   :REM c,g and x contain the old values for background, foreground and word.
  REPEAT
    b=RND(6)f=RND(6)w=RND(6)                    :REM pick random numbers between 1 and 6
  UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x)      :REM until all colours are different from each other and their previous values
  VDU17,b+128,17,f,12                           :REM VDU 17 sets colour, using the 128's bit to say if it is foreground or background. VDU 12 clears the screen.
  PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4) :REM MID$ picks the colour. The string is considered 1-indexed.
  WAIT 99                                       :REM wait 99 centiseconds
UNTIL0

Output
The first few images show the program as written, running in screen mode 6. The bottom image shows the program with the ,12 removed so that the screen is not cleared in between word printings. That way it is easier to verify that the colours comply with the rules.


Imperative Tampio, 168 bytes
Listan x on riippuen siitä,onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus,joko sen ensimmäinen alkio tai sen hännän x.

Online version
Ungolfed:

Listan pisin alkio on riippuen siitä, onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus, joko

sen ensimmäinen alkio tai
sen hännän pisin alkio.

Online version
The only golfing opportunity this has is to replace pisin alkio (meaning "the longest element") with x.
Translation:

The longest item in a list is, depending on whether the length of the first item is greater or equal to the length of each element in the list, either

the first item in the list, or
the longest item in the tail of the list.


Encode a program with the fewest distinct characters possible


C, 47 45 characters
30+(m>7^m&1)-(m^2?0:2-!(y%100||(y/=100),y%4))

Taken from an answer to an earlier question where I borrowed a couple of tricks from another user. Returns the length of month m in year y for the Gregorian calendar. ugoren's answer to the same question is shorter and may give a shorter answer to this question.
With thanks to mob for his leap year calculation.


PHP, 67 Bytes

for(;date(LN,mktime(0,0,0,1,1,$y=$argn+$i))>1;)$i=($i<1)-$i;echo$y;

Try it online!

or

for(;date(LN,strtotime("1/1/".$y=$argn+$i))>1;)$i=($i<1)-$i;echo$y;

Try it online!

Expanded

for(;
date(LN,mktime(0,0,0,1,1,$y=$argn+$i)) # N is 1 for Monday and L is 0 for Non leap year
>1;) # loop so long as expression is not 1
  $i=($i<1)-$i; # set $i 0,1,-1,2,-2 ...
echo$y; # Output Year

date


JavaScript (ES6), 57 50 48 45 42 bytes
Takes the string as an array of individual characters, outputs an array containing a comma separated string of the original followed by a subarray of comma separated strings for each step.
s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]

3 bytes saved thanks to Arnauld
suggesting I abuse the loose output spec more than I already was, which led me to abusing it even more for another 3 byte saving.

Test it

o.innerText=JSON.stringify((f=

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]

)([...i.value="codegolf"])(j.value=[1,4,4,0,2]));oninput=_=>o.innerText=JSON.stringify(f([...i.value])(j.value.split`,`))
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
<label for=i>String: </label><input id=i><label for=j>Indices: </label><input id=j><pre id=o>

Explanation
We take the two inputs via parameters s (the string array) and a (the integer array) in currying syntax, meaning we call the function with f(s)(a).
We build a new array and start it off with the original s. However, as the splice method we'll be using later on modifies an array, we need to make a copy of it, which we can do by converting it to a string (simply append an empty string).
To generate the subarray, we map over the integer array a (where x is the current integer) and, for each element, we splice 1 element from s, beginning at index x. We return the modified s, again making a copy of it by converting it to a string.


Retina, 33 22 17 bytes

-5 bytes thanks to @MartinEnder

-2`\D(\d+)
$&&&$1

Try it online!


APL (Dyalog Unicode), 146 115 bytes
{(∨/+⍺⊃⊢)∨⌿↑{'O'=1↓⊃¨⊢∘(((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨1⌈¯2+'X O\/'⍳⊃)\(4×≢,⍵)⍴⊂⍵}¨({¯1+⊃⊃⍸'X'=⍵}⌽⍉)⍣2¨(⊢,⌽∘⊖¨)(⊂,⊂∘⍉)⍵,⍳≢⍵}

-31 bytes (!) thanks to @Bubbler (combining transformations; simplifying iteration end condition; smaller details)
Try it online!
Outputs 2 for truthy, 1 for mediumy, and 0 for falsy.
Similarly to my solution to Solve the Halting Problem for Modilar SNISP, this moves the grid around the ball location, so the ball is always in the top-left, moving right. This might not be the best strategy (as opposed to storing a pointer position and direction) in this case because the ball doesn't always start from the top-left moving right, so I spend many bytes rotating and aligning the grid.
Details
Append 1,2,3,4,...,n to the input grid.
This prevents symmetric grids from comparing equal after some sequence of moves
⍵,⍳≢⍵

We must be careful here and elsewhere in the code that we do not affect
the angle of / and \. Using a simple reflection ⌽ to reverse direction
should change / to \, but the reflection of the character '/' is '/'.
Conveniently, APL matrix reflection operators are visually sensible:

⌽ reflects across a vertical line: swaps / and \
⊖ reflects across a horizontal line: swaps / and \
⍉ (transpose) reflects across the main diagonal: no change

Thus we must use an even total number of ⌽ and ⊖ in all transforms.
Obtain all 4 starting directions/rotations:
(⊢,⌽∘⊖¨)(⊂,⊂∘⍉)

Shift each grid so that 'X' is in the top left
(Shifts 'X' to the left edge twice, transposing the matrix in between)
{(¯1+⊃⊃⍸'X'=⍵)⌽⍉⍵}⍣2¨

For each starting grid, beginning with the starting grid, repeat 4×#coordinates (= max # of states) times...
\(4×≢,⍵)⍴⊂⍵

...move by one step:
(((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨1⌈¯2+'X O\/'⍳⊃)
  ⍝ Get the ID of the entry: `X`, ` `, or `O`:1, `\`:2, `/`:3, `|`,`+`, or `-`:4
  ⍝ We can consider |, +, and - as the same because we are always travelling
  ⍝ horizontally (albeit on a rotated grid), and these all do the same action
  1⌈¯2+'X O\/'⍳⊃
  ⍝ Get the corresponding grid position after the move
  ((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨

1 if there exists a move history whose final move's top-left element is O, and add another 1 if there exists a move history where the ⍺-th move has top-left element equal to O.
(∨/+⍺⊃⊢)∨⌿↑{'O'=1↓⊃¨


Shortest Program to Solve a Quartic Equation

C++ A fast and robust solution, 704 chars + numeric - recursion = 679
#include "stdafx.h"
#include "math.h"
double a,b,c,e,j,k,l,p,q,t,z;void s(double x, int i){if(i==99)printf("%f\n",x);else s(x-((x+b)*x*x*x+c*x*x+l*x+e)/(4*x*x*x+j*x*x + k*x + l),i+1);}
void _tmain(){double r[8];scanf_s("%lf%lf%lf%lf%lf",&a,&b,&c,&l,&e);b/=a;c/=a;l/=a;e/= a;j=3*b;k=2*c;p=(12*k-j*j)/48;q=(2*j*j*j-36*j*k+432*l)/1728;z=q*q/4+p*p*p/27;int u=0,v=0,g;
for(g=1;g<4;g++){r[g]=z>0|p==0?cbrt(-q/2+sqrt(z))+cbrt(-q/2-sqrt(z))-j/12:sqrt(-p/.75)*cos(acos(-q/sqrt(-p*p*p*4/27))/3-g*acos(-.5))-j/12;r[g+4]=(r[g]+b)*pow(r[g],3)+c*r[g]*r[g]+l*r[g]+e;if(r[g+4]>r[g+3]|g==1)u=g;if(r[g + 4]<r[g+3]|g==1)v=g;}
if(r[v+4]>0)printf("n\n");if(r[v+4]==0)printf("%f\n",r[v]);if(r[v+4]<0)s(2*r[v]-r[u]+(r[v]-r[u]==0),0);}

This is by no means the shortest answer, but so far no other answer has confirmed that it will work with curves with the full 3 stationary points (maxima/minima.) These correspond to curves with large values of b and c of opposite sign to a. None of the test data in the other solutions has local maxima/minima apart from the global one. The nearest is Eelvex's 1 2 0 0 1 which has a kink on one side where dy/dx falls to zero.
This program handles all the test data shown in other solutions, plus the following interesting examples, amongst others:
1 0 1 0 0 --> multiple root 0
1 0 -1 0 0 --> multiple root at 0, but the program prefers the simple root at -1
1 0 -1 0 0.25 -->  multiple roots at +/- 0.7071 = sqrt(0.5)

It cannot handle the case a=0, but that is not a quartic so it is out of scope.  The only problem I have found but not eliminated is b=c=d=0, but that is an easy problem to fix. I will do it when I golf the code (if I get round to that.) I expect it to come in around 700-800 chars.
How it works
The program divides the whole formula by a (which does not affect the roots, but ensures that we know that y= +infinity at x = +/- infinity )
It then calculates the formula for dy/dx (a cubic) and solves this analytically for dy/dx=0. The code to do this is quite short (the explanation in the comments is much longer than the code itself.)
It calculates the values of y at the up to 3 stationary points where dy/dx=0 and looks for the lowest (global minimum.) If this y is positive here , the whole curve is above the x axis and there are no roots.
If y is zero, then it is a root and this is reported directly. Such a root would be problematic for newton raphson.
If y is less than zero, the program makes a guess for the root on the opposite side of the global minimum from the other stationary points (to avoid getting trapped in the local maximum if there is one.)
Then it searches using newton-raphson (recursive, as you insisted.) This method is fast and simple, and once the right region of the curve has been identified, does not run the risk of dividing by zero.
I did run into other problems with it though. It quickly got very close to a solution (good enough for a human) but kept searching. With the rapid initial convergence, I assumed that the problem was that it couldn't get to f(x)==0 because f'(x) was large and f(x)/f'(x) was being rounded to zero in the calculation. So I put in an extra test condition for f(x)/f'(x) but it still did the same. Then I limited it to just 10 iterations, which is more than enough for all the tests I have done.
The current version goes up to 99 iterations. The ungolfed version has medium verbosity output (with uncommentable code for high verbosity) as seen in the screenshot and has its iterations terminated when f(x)==0. The golfed version has low verbosity (in accordance with specified requirements) and always runs to 99 iterations. The golfed version has other minor differences, such as no while loop and simplified (but less clear) expressions.
There are certainly other methods which might work better, but I think that might go into another answer (which I don't think I have time for.)
Ungolfed version
#include "stdafx.h"
#include "math.h"

double a,b,c,d,e,j,k,l,p,q,t,z;
//explanation of variables
//dy/dx= i* x3 + j*x2 + k*x + l. No i variable needed as it is normalised to 4.
//depressed form of dy/dx: t3+pt+q. A subsitution is used to eliminate the squared term, see below.
//z=q2/4 + p3/27. z is proportional to the "discriminant." The sign tells the number of roots of dy/dx
// +ve z means 1 real root, -ve z means 3 real roots, 0 means one simple root plus a double root.

// recursive newton-raphson to depth i
void s(double x, int i){
    double m=(x + b)*x*x*x + c*x*x + d*x + e;
    if (m == 0 | i == 99)  printf("z= %f x= %f y= %f iteration %d\n", z,x,m,i);
    else s(x-m/(4*x*x*x + j*x*x + k*x + l), i+1);

}

void _tmain(){
    while (true){

        double r[8];
        //r[1,2,3] and r[5,6,7] store x and y values of the maxima and minima.
        //r[0] and r[4] are dummies to handle [subscript-1] references.

        scanf_s("%lf %lf %lf %lf %lf", &a, &b, &c, &d, &e);
        //uncomment for verbose output: printf("data for minima and maxima \n");
        //uncomment for verbose output: printf("   z       x       dy/x      y     hi/low \n");
        //hi/low indicate which y values are highest and lowest: 1st, 2nd, 3rd.

        //Divide by a to give a "monic polynomial" with a=1.
        //This does not affect the roots but saves a lot of typing of powers of a.
        // differentiate to i*x3 + j*x2 + k*x + l. As a=1, we know i=4.
        b /= a; c /= a; d /= a; e /= a;
        j = 3*b; k = 2*c; l = d;

        // to prepare to solve this cubic, convert to depressed cubic t3+pt+q, eliminating x2. x=t-j/(3*i)
        // p=(3*i*k - j2)/(3*i2) q=(2*j3 - 9*i*j*k + 27*i2*l)/27*i3. But we know i=4.
        p = (12 * k - j*j) / 48;
        q = (2 * j*j*j - 36 * j*k + 432 * l) / 1728;
        z = q*q / 4 + p*p*p / 27;

        //u and v indicate which of the stationary points are highest and lowest.
        //solve dy/dx, store the roots in r[1,2,3] and the y values in r[5,6,7].
        int u=0,v=0,g;
        for (g = 1; g < 4; g++){

            //if z>0 or p==0 use cardano's method to store the one real root of dy/x three times in r[1,2,3]
            //if z<=0 use viete's trigonometric method to find the multiple real roots.
            //use of different methods for each case avoids the need to handle complex numbers.

            r[g] =z > 0 | p==0? cbrt(-q / 2 + sqrt(z)) + cbrt(-q / 2 - sqrt(z)) - j / 12 :
                sqrt(-p / .75)*cos(acos(-q / sqrt(-p * p * p * 4 / 27)) / 3 - g*acos(-.5)) - j / 12;

            r[g+4] = (r[g]+b)*pow(r[g],3) + c*r[g]*r[g] + d*r[g] + e;

            if (r[g + 4]>r[g+3]|g==1)u=g;
            if (r[g + 4]<r[g+3]|g==1)v=g;

            // uncomment for verbose output
            //printf("%f %f %f %f %d %d \n  \n", z, r[g], 4 * pow(r[g], 3) + j*pow(r[g], 2) + k*r[g] + l, r[g+4], u, v);
        }

        //because we divided by a, the new a=1 and y tends to infinity at large |x|.
        //so if the lowest stationary point has y>0, the whole curve is above the x axis and there is no solution.

        //if the lowest stationary point has y=0 it is tangent to the x axis and would cause problems for newton-raphson

        //if the lowest stationary point has y<0, use newton raphson, 99 iterations. ensure 1st guess is on the side
        //opposite the highest stationary point, just in case that point also has y<0, to avoid getting trapped.
        //special case: if r[v]-r[u] == 0 (implies only one stationary point) then add 1!

        if (r[v+4] >0) printf("n\n");
        if (r[v+4]==0) printf("z= %f x= %f multiple root", z,r[v]);
        if (r[v+4] <0) s(r[v]+(r[v]-r[u])+(r[v]-r[u]==0),0);
    }
}

Output
All data tested by other answers is here, as well as many additional examples. The sign of the value z is positive when there is only one stationary point where dy/dx=0, negative when there are three (2 minima and a maximum if a is positive), and zero when there are two (a minimum if a is positive, plus an inflexion.) This is the only answer so far that presents test cases for three stationary points.
The y values are shown for easy checking of the program. y is zero at the root, and as can be seen, an acceptable zero is always found.
The golfed version is low verbosity, displaying only the root per question spec.


J, 50 40 38 37 characters

f=:3 :'+/y<:}.~.,(~:/**/)~p:i._1&p:y'

Usage:

   f 1
0
   f 62
18
   f 420
124
   f 10000
2600

With thanks to FUZxxl.

Performance test

   showtotal_jpm_ ''[f 1[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000046│0.000046│100.0│100 │1  │
│[total]│      │        │0.000046│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000095│0.000095│100.0│100 │2  │
│[total]│      │        │0.000095│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000383│0.000383│100.0│100 │3  │
│[total]│      │        │0.000383│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.084847│0.084847│100.0│100 │4  │
│[total]│      │        │0.084847│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[f 50000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │5.014691│5.014691│100.0│100 │5  │
│[total]│      │        │5.014691│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘

I'm no theoretician as has been seen here in the past, but I think the time complexity is something like O(np2) where np is the number of primes up to and including the input number n. This is based on the assumption that the complexity of my method (generating a very large multiplication table) far outweighs the complexity of the prime generating function built in to J.

Explanation

f=:3 :'...' declares a (monadic) verb (function). The input to the verb is represented by y within the verb definition.

p:i._1&p:y The p: verb is the multi purpose primes verb, and it's used in two different ways here: _1&p:y returns the number of primes less than y then p:i. generates every one of them. Using 10 as input:

   p:i._1&p:10
2 3 5 7

(~:/**/)~ generates the table I spoke of earlier. */ generates a multiplication table, ~:/ generates a not-equal table (to eliminate the squares) and both of these are multiplied together. Using our previous output as input:

   */~2 3 5 7
 4  6 10 14
 6  9 15 21
10 15 25 35
14 21 35 49

   ~:/~2 3 5 7
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

   (~:/**/)~2 3 5 7
 0  6 10 14
 6  0 15 21
10 15  0 35
14 21 35  0

}.~., now we turn the numbers into one list , get the unique values ~. and remove the 0 at the start }.

   }.~.,(~:/**/)~2 3 5 7
6 10 14 15 21 35

y<: a comparison with the original input to check which values are valid:

   10<:6 10 14 15 21 35
1 1 0 0 0 0

+/ and then sum that to get the answer.

   +/1 1 0 0 0 0
2


Shortest code to print ':)' random times


Write the shortest code to match a tail-repeating string where one character falls off the head in each repetition

Python

Used the fact that the length of a valid string will always be a Triangle Number.

t=raw_input()
x=int(len(t+t)**.5)
print t==''.join(t[i:x]for i in range(x))

A Ruby solution might be shorter, will post soon.


Print the current time… taking leap seconds into account

PowerShell, 161 bytes

(('{0:H:m:s}','23:59:60')[(($d=[datetime]::UtcNow).Ticks-6114960*98e9)/1e8-in((irm ietf.org/timezones/data/leap-seconds.list)-split'[^@]	|
'-match'^\d{9}')])-f$d

Try it online! (doesn't work here, it seems that TIO doesn't recognize irm and iwr, maybe it's a security feature?)

Logic Test (Hardcoded Date):

(('{0:H:m:s}','23:59:60')[(($d=[datetime]'1/1/2017 00:00:00').Ticks-6114960*98e9)/1e8-in((irm ietf.org/timezones/data/leap-seconds.list)-split'[^@]	|
'-match'^\d{9}')])-f$d

Notes

There is a literal TAB and a literal linebreak (0xA) in the regex string, so that I didn't have to escape them (saved 1 byte each).

Explanation

The times given (of the leap seconds) in the ietf file are in seconds since NTP epoch which is 1/1/1900 00:00:00. On Windows, a "tick" is simply one ten-millionth of a second (10,000,000 ticks/sec).

If you add an integer to a [datetime] it counts the integer value as ticks, so I'm using the hardcoded tick value of NTP epoch, then subtracting it from the tick value of the current UTC time (the original value of which is simultaneously being assigned to $d).

To make that hardcoded tick value smaller, I took away some zeros (9 of them) and divided by 98, then multiply by 98e9 (98*109).

The result of that subtraction is the value in ticks since NTP epoch. That gets divided by 1e8 (not 1e9, for reasons that will be clear in a moment) to get the value in seconds (sort of) since NTP epoch. It will be smaller by a factor of 10, actually.

Retrieving the document from the IETF, rather than split it into lines first, then process the lines with the timestamps, I decided to split on both line breaks and on TAB characters, since that's what comes after the timestamp. Because of a single errant line in the file, that alone would include an additional timestamp we don't want. The line looks like this:

#@	3707596800

So I changed the regex to split on [^@]\t (any character that's not @ followed by a TAB) which works to exclude that line, but also ends up consuming the last 0 in each of the timestamps.

That's why I divide by 1e8 and not 1e9, to account for the missing 0.

The current timestamp is checked to see it exists inside the list of neutered leap second timestamps. This whole process I described is inside the array accessor [], so the resulting [bool] value gets coalesced to a 0 ($false) or 1 ($true). The array we're indexing into contains two elements: a format string for displaying the time, and a hardcoded 23:59:60. The truthiness of the aforementioned comparison determines which one will be chosen, and that is fed into the format operator -f with the previously assigned current date $d as its parameter.


Write a hello world GUI program that closes itself after three seconds

Unix shell, 31 characters

xmessage -timeout 3 hello world

This program requires the xmessage(1) utility from X.Org. It uses the traditional black-and-white X Athena Widgets (Xaw).


Advent Challenge 8: Storage Cart Transport Planning!

JavaScript (ES7), 172 bytes
Returns an array of 0-indexed time frames.
a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0)

NB: This can only work with labels in [0-31]. This is a JS limit, not a limit of the algorithm.
Test cases

let f =

a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0)

console.log(JSON.stringify(f([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))                   // -> [0, 0, 0]
console.log(JSON.stringify(f([[1, 2, 3], [1, 2, 3]])))                              // -> [0, 1] or [1, 0]
console.log(JSON.stringify(f([[1, 2, 3], [3, 2, 1]])))                              // -> [0, 1] or [1, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4], [4, 3, 2, 1]])))                        // -> [0, 0]
console.log(JSON.stringify(f([[1, 1, 1], [1, 1, 1]])))                              // -> [0, 3] or [3, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4], [2, 4, 3, 1]])))                        // -> [1, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4, 5, 6, 7], [2, 3, 3, 4], [5, 4, 3]])))    // -> [0, 2, 3]
console.log(JSON.stringify(f([[1, 2, 3, 4, 4], [1, 2, 3, 5, 4], [1, 2, 3, 4, 5]]))) // -> [1, 2, 0]

Commented
a => (                         // given a = array of tracks
  g = k =>                     // g = recursive function taking k = counter
    a.map((t, i) => [          // map each track t in a to a new entry made of:
      l = t.length + 1,        //   - its length + 1 (l)
      i,                       //   - its original index in the input array
      t,                       //   - the original track data
      L = L < l ? l : L        //   and update the maximum track length L
    ])                         // end of map()
    .sort(([a], [b]) =>        // let's sort the tracks from shortest to longest
      a - b                    // so that solutions that attempt to delay short
    )                          // tracks are tried first
    .every(([, n, b],          // for each track b with an original position n,
                      i) =>    // now appearing at position i:
      b.every((c, t) =>        //   for each label c at position t in b:
        o[t += A[n] =          //     add to t the time frame A[n] corresponding
          k / L**i % L | 0     //     to this position (i) and this combination (k)
        ] & 1 << c ?           //     if the station c is already occupied at time t:
          0                    //       make every() fail
        :                      //     else:
          o[t] |= 1 << c       //       mark the station c as occupied at time t
      ),                       //   end of inner every()
      o = [],                  //   start with: o = empty array (station bitmasks)
      A = []                   //               A = empty array (time frames)
    ) ?                        // end of outer every(); if successful:
      A                        //   return A
    :                          // else:
      g(k + 1)                 //   try the next combination
)(L = 0)                       // initial call to g() + initialization of L


count number of valid, unique sequences for moving on a 1xn board

Python, 74

f=lambda t,n,i=1:i==n or t*i and sum(f(t-1,n,i+d)for d in[-1,0,1])%(1e9+7)

A recusive solution. The current position i is stored 1-indexed as an optional argument.

If the current position i==n, we've arrived at the final square and are forced to stay still, giving 1 path.
Otherwise,

If the remaining time t==0, we've run out of time, so there's 0 paths.
If the current position i==0, we've run off the left end already, so there's 0 paths.

If neither of those was true, there we recurse. We add up the path counts for each of the directions left, none, and right, corresponding to displacements [-1,0,1], and take the result modulo 1e9+7 as required.

An alternative solution that uses eval with string substitution to do the sum. Same number of chars. Note the use of unary + to start the sum.

f=lambda t,n,i=1:i==n or t*i and eval(3*'+f(t-1,n,i+%d)'%(-1,0,1))%(1e9+7)

Here's another a solution that is surely short for any language with built-in matrices, so anyone who can golf it is welcome to take it.

Let M be the n*n transition matrix for the walk, which is a tridiagonal banded matrix with 1's on the main diagonal and the diagonals above and below it, except for a 0 for movement left from the rightmost cell.

1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 0 1

Then, the output is (1,n) entry of the matrix power M^t.


Haskell, 49 46 bytes

u=length
f x|j<-x>>=id=maximum j+u x-u j`div`2

Try it online!

I get the number of vertices by concating the faces and finding the maximum.  I find the number of faces by taking the length.  I find the number of edges by summing the lengths of the faces and dividing by 2.


Matlab, 104 92 bytes

This makes use of the 3d-array/matrix representation of RGB images in Matlab, as well as the Kronecker product which is exactly what we need creating this new 2x2 "metapixel" form each source pixel. The output is then displayed in a popup window.

a=double(imread(input('')));for n=1:3;b(:,:,n)=kron(a(:,:,n),[1:2;2:3]==n)/255;end;imshow(b)

Resized screencapture:


Python, 138 bytes
q,r,t,i=1,180,60,2
while 1:u,y=27*i*(i+1)+6,(q*(27*i-12)+5*r)//(5*t);print(y,end="");q,r,t,i=10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1

Implementation of http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf.


Python 2, 444 391 372 bytes

Crossed out 444 is still regular 444 ;(

Huge thanks to @Dennis for a whopping -52 -71 bytes!

k=lambda c,a,b:abs(a+c*a-c*b)-c<abs(b-a)>0and k(c,b-c*a,a+b-c*b)or(a,b)
def f(*t):
 a,b=sorted(t);m=b-a+1,0;g=lambda _:min([k(1,*k(0,*s)),m][_!=b:],key=lambda(x,y):abs(x-y))
 if b<0:x,y=f(-a,-b);return-x,-y
 for c in range(-b,b+1):
    for s in(c,a),(a,c):
     x,y=s
     if min(s)>0:
        while y<b:x,y=y,x+y
        m=g(y)
     x,y=s
     while(x!=b)&((x>b)^(b>0)):x,y=y-x,x
     m=g(x)
 return m

Try it online!

The solution can be run by calling f(a, b) on the two input integers. It is based on the idea that if both a and b are within at least one of the same sequence (where a and b are ordered beforehand such that a ≤ b), it follows that there is at least one integer c equivalent to an adjacent value of a in a shared sequence of a and b for which the sequence generated by a and c contains b in it.

Furthermore, if at least one of the two integers is positive, all values of c must be bounded by -b ≤ c ≤ b for it to even be possible to generate the value of b on either side of the starting pair. Thus, the solution simply brute-forces values of c between -b and b that in combination with a are capable of generating b within the sequence, and finds the one for which the difference of the kernel values for a and c are minimal (this is possible because finding the kernel for two adjacent numbers in a sequence is trivial).

If neither a nor b is positive, the solution simply negates both and returns the negative of the kernel generated for the negated pair.


Retina, 29 27 bytes

Saved 2 bytes thanks to @MartinEnder

^0\.0*.|^\d(\d*?)0+$
1$1
\d

Try it online! | Test suite


Convert braces to Right Hand Brace (Sad Brace)

V + Bash utilities, 64 62 61 60 62 bytes

1 byte saved thanks to @DJMcMayhem for putting the ex commands together

:se ve=all|%!wc -L
y$uò/^ *<93>[{};]
xk$pòò/<84> {};][{};]«$
lDî^R0|p

^R is the character literal for <C-r> (0x12) and <84> is 0x84 and <94> is 0x94.

wc -L works on most *nix based systems, but not macOS. For macOS, you have to do gwc -L  after getting coreutils using brew, if you haven't already.

Try it online! (Java)

Try it online! (Python)

Try it online! (Java again)

This preserves all blank lines and does not handle tabs, only spaces.

Hexdump:

00000000: 3a73 6520 7665 3d61 6c6c 7c25 2177 6320  :se ve=all|%!wc
00000010: 2d4c 0a79 2475 f22f 5e20 2a93 5b7b 7d3b  -L.y$u./^ *.[{};
00000020: 5d0a 786b 2470 f2f2 2f84 207b 7d3b 5d5b  ].xk$p../. {};][
00000030: 7b7d 3b5d ab24 0a6c 44ee 1230 7c70       {};].$.lD..0|p

Explanation

First we need to be able to move the cursor anywhere in the buffer, so we use

:se ve=all|...

and we chain this with another ex command using |

We need to get the length of the longest line in the input. This can be done with the shell command wc -L.

       ...|%!wc -L

This overwrites the current buffer (containing the input) with the result of wc -L. It gives an output of something like:

            42

and the cursor lands on the 4 in 42. Then we copy this number by using y$: yank text from the cursor's position to the end of the line. This conveniently stores this number in register 0. But more on that later. The input is replaced with this number, so to revert back, we undo.

Now say the input looked somewhat like this:

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello, World!");
    }
}

we need to move the braces } from the end of the buffer to just after the println statement.

ò                  " recursively do this until a breaking error:
 /^ *<93>[{};]     "   this compressed regex becomes /^ *\zs[{};]
                   "   this finds any character from `{};` after leading spaces
                   "   the cursor then goes to the `{};`

x                  "   delete character
 k$                "   go to the end of the line above
   p               "   and paste
    ò

If the regex cannot be found, a breaking error happens and breaks out of the recursion caused by ò.

Now comes the main part of this program, move all braces and semi-colons and align them as stated in the question.

ò                  " starts recursion
 /<84> {};][{};]«$ "   compressed form of [^ {};][{};]\+$
                   "   finds a sequence of `{};`s at the end of the line with a non-`{};` char to preceding it
 l                 "   move the cursor 1 to the right (since we were on the non-`{};` char now)
  D                "   delete everything from this position to the end of line
                   "   the deleted text contains `{};`
   î               "   execute as normal commands:
    ^R0            "   contains what's in register `0`, ie the length of the longest line
       |           "   now go to the column specified by that number
        p          "   and paste the contents
                   " implicit ending `ò`

Again, this recursion will be stopped by a breaking error caused when the regex could not be found in the buffer.

Edits

Used D instead of d$ (I don't even know why I missed that in the first place)
Compressed [^ (in the regex) to <84>
Fixed bug by using \zs (compressing it into <93>) and by removing the $ in $xk$pò
Removed useless newline
Changed regex to make submission compliant with new rules and gained 2 bytes


Mathics, 24 bytes

#^#2&@@@FactorInteger@#&

Try it online!


Most destructive "forgot-to-enter-insert-mode" sequence in Vim


Outputting ordinal numbers (1st, 2nd, 3rd)

Python 2, 49 bytes

lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4]

An anonymous function. A full program would be counted at 55 bytes.

'tsnrhtdd'[i::4] encodes the suffixes th st nd rd for values of i from 0 to 3. Given this, all we need is a way to map the values of n to the index of the corresponding suffix, i. A straightforward expression that works is (n%10)*(n%10<4 and 10<n%100<14). We can easily shorten this by dropping the first set of parentheses and observing that n%5 gives the same results as n%10 for the values of n with the special suffixes. With a bit of trial and error, one may also shorten 10<n%100<14 to n%100^15>4, which can be chained with the other conditional to save even more bytes.


6502 machine code routine (C64), 57 bytes

20 44 E5 A0 03 84 FB 20 9B B7 A4 FB 96 22 C6 FB 10 F5 85 FC A6 24 20 F0 E9 A4
25 B1 D1 09 01 49 02 91 D1 C8 C4 23 D0 F3 E8 E4 22 D0 E9 A9 2C C5 FC F0 D0 A5
C6 F0 FC C6 C6 4C 44 E5

This is position-independent code, put it somewhere in RAM and use the correct start address calling it with sys.

Online demo (start address $C000 / 49152).

Usage: sys<startaddress>,<x1>,<y1>,<x2>,<y2>[,<x1>,<y1>,<x2>,<y2>[,...]]

Example: sys49152,0,0,9,9,1,1,10,10,2,2,11,11

On reasonable number ranges: The natural range on this 8-bit machine is [0-255], and the program will accept this as parameters. But the C64 screen only has 40 columns and 25 rows, therefore limiting the reasonable range to [0-40] for x values and [0-25] for y values. Using other values will have unpredictable behavior.

commented disassembly listing:

20 44 E5    JSR $E544           ; clear screen
 .mainloop:
A0 03       LDY #$03            ; index for reading coordinates
84 FB       STY $FB
 .inputrect:
20 9B B7    JSR $B79B           ; read 8bit value from parameter
A4 FB       LDY $FB
96 22       STX $22,Y           ; and store to $22-$25
C6 FB       DEC $FB
10 F5       BPL .inputrect      ; parameter reading loop
85 FC       STA $FC             ; store last character
A6 24       LDX $24             ; load y1
 .rowloop:
20 F0 E9    JSR $E9F0           ; get pointer to screen row in $d1/$d2
A4 25       LDY $25             ; load x1
 .colloop:
B1 D1       LDA ($D1),Y         ; load character at screen position
09 01       ORA #$01            ; set bit 0 ( -> '#')
49 02       EOR #$02            ; toggle bit 1 (toggle between '#' and '!' )
91 D1       STA ($D1),Y         ; store character at screen position
C8          INY                 ; next x
C4 23       CPY $23             ; equals x2?
D0 F3       BNE .colloop        ; no -> repeat
E8          INX                 ; next y
E4 22       CPX $22             ; equals y2?
D0 E9       BNE .rowloop        ; no -> repeat
A9 2C       LDA #$2C            ; load ','
C5 FC       CMP $FC             ; compare with last character from parsing
F0 D0       BEQ .mainloop       ; if ',', repeat reading coordinates
 .waitkey:
A5 C6       LDA $C6             ; load input buffer size
F0 FC       BEQ .waitkey        ; and repeat until non-empty
C6 C6       DEC $C6             ; set back to empty
4C 44 E5    JMP $E544           ; clear screen


Counting creatures on a hexagonal tiling

JavaScript (Node.js),  578 ... 433  431 bytes

f=(n,T=[B=[N=0,0,0,1,1]])=>!n||T.some(([x,y,q,m])=>B.some((p,d)=>m>>d&1&&((p=x+~-s[d],q=y+~-s[d+2],t=T.find(([X,Y])=>X==p&Y==q))?(q=t[3])&(p=D[d*3+t[4]])^p?t[f(n,T,t[3]|=p),3]=q:0:[0,1,2].map(t=>f(n-1,[...T,[p,q,-p-q,D[d*3+t],t]])))),s="2100122",D=Buffer("160).(9!'8 &$<%"))|n>1||[0,1,2,1,2,0].some((_,d,A)=>B[k=T.map(a=>[(h=n=>Math.min(...T.map(R=a=>a[A[(d+n)%6]]))-R(a))(0),h(3),(x=(a[4]+d*2)%3,d>2)*x?3-x:x]).sort()])?N:B[k]=++N

Try it online! (\$n=1\$ to \$n=13\$)

How?

Directions and tiles

We use the following codes for the 6-direction compass and the tiles:

We assume that the creature is blue.

Connections

We need a table to know which parts of the creature need to be connected to other tiles when we enter a given tile in a given direction:

     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 | 0,4,5 | 1,2,4 |   4
 d=1 | 0,3,5 | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 | 3,4,5 |   5   | 1,2,5
 d=4 |   2   | 2,3,4 | 0,2,5
 d=5 |   1   | 1,3,4 | 0,1,5

Example:

If we enter a tile of type \$1\$ with direction \$5\$, we need to connect in directions \$1\$, \$3\$ and \$4\$:

But the way the tiles are designed, there can't possibly be a single missing connection in a single direction. A consequence of that is that we can ignore one direction entirely and still be able to detect if the path is closed or not. By convention, we are going to ignore direction \$5\$.

     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 |  0,4  | 1,2,4 |   4
 d=1 |  0,3  | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 |  3,4  |   -   |  1,2
 d=4 |   2   | 2,3,4 |  0,2

These updated sets of directions are first re-encoded as 5-bit integers, and then as ASCII characters with a fixed offset of \$+32\$:

     |  T=0  |  T=1  |  T=2              |  T=0  |  T=1  |  T=2
-----+-------+-------+-------       -----+-------+-------+-------
 d=0 |   17  |   22  |   16          d=0 |  "1"  |  "6"  |  "0"
 d=1 |    9  |   14  |    8          d=1 |  ")"  |  "."  |  "("
 d=2 |   25  |    1  |    7    -->   d=2 |  "9"  |  "!"  |  "'"
 d=3 |   24  |    0  |    6          d=3 |  "8"  |  " "  |  "&"
 d=4 |    4  |   28  |    5          d=4 |  "$"  |  "<"  |  "%"

Once flattened, this gives:

D = Buffer("160).(9!'8 &$<%")

Coordinates

To describe the positions of the tiles, we use cube coordinates with \$x+y+z=0\$:

Credits: www.redblobgames.com

It will make it easier to process rotations and reflections in the final step of the algorithm.

Tile encoding

The tiles are stored in a list, with no specific order. It means that we don't have to worry about some dynamic 2D allocation and we can easily iterate on the existing tiles. The downside is that, given specific coordinates, we need to find() the corresponding tile in the list.

Each tile is stored as \$(x, y, z, m, t)\$ where:

\$(x, y, z)\$ are the cube coordinates of the tile as described above
\$m\$ is the 5-bit mask of directions that need to be connected
\$t\$ is its type (\$0\$, \$1\$ or \$2\$)

Algorithm

We start with a single tile of type \$1\$ at \$(0,0,0)\$, with a required connection in direction \$0\$:

Therefore, this tile is encoded as [0,0,0,1,1].

At each iteration, we look for:

Tiles with missing connections: in this case, we successively try to complete the connection with each type of tile.
Tiles that are already connected but for which new connections need to be added because they have been reached in a different direction: in this case, we update the direction mask (with a bitwise OR) and force a new iteration.

If all connections are valid and we have reached the requested number of tiles, we still need to test whether it is a new creature or just a modified version of an existing one:

We apply the following transformations:

We perform the 3 possible rotations by replacing \$(x,y)\$ with \$(x,y)\$ (no rotation), \$(y,z)\$ (120°) or \$(z,x)\$ (240°), and updating the types of the tiles accordingly.
We perform the 3 corresponding reflections by replacing \$(x,y)\$ with \$(y,x)\$, \$(z,y)\$ or \$(x,z)\$, and updating the types of the tiles accordingly.

For each transformation, we translate all tiles such that the bottom-right corner is always located at \$(0,0)\$. (The signs of the coordinates are inverted in the process, which technically leads to another reflection, but this is harmless.)
We sort the tiles according to their coordinates and types. (This sort is processed in lexicographical order, which is fine.)
We finally coerce the resulting list to a key string which can be compared with the other keys.
We abort as soon as a known key is matched, or store the new key and increment the final result if none of the transformations lead to a known key.

Commented

f = (n, T = [B = [N = 0, 0, 0, 1, 1]]) =>
  // abort if n = 0
  !n ||
  // for each tile in T
  T.some(([x, y, q, m]) =>
    // for d = 0 to d = 4
    B.some((p, d) =>
      // if this tile requires a connection in this direction
      m >> d & 1 && (
        // look for a connected tile t at the corresponding position (p, q)
        (
          p = x + ~-s[d],
          q = y + ~-s[d + 2],
          t = T.find(([X, Y]) => X == p & Y == q)
        ) ?
          // if t exists, make sure that its direction mask is up-to-date
          (q = t[3]) & (p = D[d * 3 + t[4]]) ^ p ?
            // if it's not, update it and force a new iteration
            t[f(n, T, t[3] |= p), 3] = q
          :
            0
        :
          // if t does not exist, try each type of tile at this position
          [0, 1, 2].map(t => f(n - 1, [...T, [p, q, -p - q, D[d * 3 + t], t]]))
      )
    ),
    // s is used to apply (dx, dy)
    s = "2100122",
    // D holds the direction masks for the connections
    D = Buffer("160).(9!'8 &$<%")
  ) |
  // stop here if the above some() was truthy or we have more tiles to add
  n > 1 ||
  // otherwise, apply the transformations
  [0, 1, 2, 1, 2, 0].some((_, d, A) =>
    B[
      // compute the key k
      k =
        // by generating the updated tuples [x, y, type] and sorting them
        T.map(a =>
          [
            // transform the 1st coordinate
            (h = n => Math.min(...T.map(R = a => a[A[(d + n) % 6]])) - R(a))(0),
            // transform the 2nd coordinate
            h(3),
            // update the type
            (x = (a[4] + d * 2) % 3, d > 2) * x ? 3 - x : x
          ]
        ).sort()
    ]
  ) ?
    // if the key was found, just return N
    N
  :
    // if this is a new creature, store its key and increment N
    B[k] = ++N


Remove single line and multiline comments from string

Shell + coreutils + gcc compiler collection, 31 bytes
This answer may seem a bit loopholey, but I didn't see anything specifically banning it in the question.
Rather than using clumsy regular expressions, why not use the tool that was built for the job.  It should have no problem giving correct results:
cpp -fpreprocessed -o- -|sed 1d

Takes input from STDIN and output to STDOUT.  Normally ccp will do all preprocessing (header files, macro expansion, comment removal, etc), but with the -fpreprocessed option, it will skip most of the steps, but it will still remove comments.  In addition, cpp adds a line like # 1 "<stdin>" to the beginning of the output, so the sed is there to delete it.


JavaScript (ES6), 46 + 55 + 6 + 36 = 282 274 ... 158 143 bytes

A:

n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)

B:

n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))

C:

?!g:!q

D:

?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

The result is 4 anonymous functions which give truthy/falsy values for their respective inputs (AC, AD, and BC give true/false, BD gives 1/0).

Test snippet

let AC =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?!g:!q

let AD =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

let BC =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?!g:!q

let BD =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

let update = n => O.innerText = [
  'perfect: ' + AC(n),
  'refactorable: ' + AD(n),
  'practical: ' + BC(n),
  'highly composite: ' + BD(n)
].join("\n")
<input type=number value=1 min=1 oninput=update(this.value)>


Jelly, 17 16 bytes

×€ȷ5R¤ÆDL€€Z=Ḅi3

This is a brute force solution that tries all possible values up to 100,000. Try it online!

Non-competing version

The latest version of Jelly has a bug fix that allows to golf down the above code to 15 bytes.

ȷ5R×€³ÆDL€€=Ḅi3

Try it online!

How it works

×€ȷ5R¤ÆDL€€Z=Ḅi3  Main link. Left input: x,z. Right input: w,y

     ¤            Combine the two atoms to the left into a niladic chain.
  ȷ5              Yield 100,000 (1e5).
    R             Apply range. Yields [1, ..., 100,000].
x€                Multiply each r in the range by x and z.
                  This yields [[x, ..., 100,000x], [z, ..., 100,000z]].
      ÆD          Compute the divisors of each resulting integer.
        L€€       Apply length to each list of divisors.
                  This counts the divisors of each integer in the 2D array.
           Z      Zip; group the divisors of kx and kz in pairs.
            =     Compare each [divisors(kx), divisors(kz)] with [w, y].
                  This yields a pair of Booleans.
             Ḅ    Convert each Boolean pair from binary to integer.
              i3  Find the first index of 3. Yields 0 for not found.


Python 2, 95 71 70 55 bytes

lambda i,m:min(i.count(c)/m.count(c)for c in m if" "<c)

Try it online!

Input: Ingredients i as a comma-separated string, and a meal m as a string.
Output: Max number of meals that can be made.

How: Divides the frequency of each character in the ingredient by its corresponding character in the meal, then takes the minimum.


bash, 38 bytes

read -t10||a=no;echo $a input received

This uses the -t (timeout) option to bash's read, which causes it to fail and return a nonzero exit code if no input is given in the specified number of seconds.


Make a working digital clock with ascii numbers

Python, 411 408 chars

import time,os
s=" ";p=".";a=s*3;b=" _ ";c="|_|";d="| |";e="|  ";f="  |";g="|_ ";h=" _|";P=[s,p,p]
z=[[b,d,c],[a,f,f],[b,h,g],[b,h,h],[a,c,f],[b,g,h],[b,g,c],[b,f,f],[b,c,c],[b,c,h]]
A=range(10);B=A[:6];C=A[:3]
while 1:
 for i in C:
  for j in A:
   if i==2&(j==4):break
   for k in B:
    for l in A:
     for m in C:
      print z[i][m]+s+z[j][m]+P[m]+z[k][m]+z[l][m]
     time.sleep(1);os.system('clear')

Not so pretty but working.


Jelly, Score 1 * 8 bytes = 8
String zip:
+Ẇɼ+

Try it online!
Cantor pairing function:
+ẆL+

Try it online!
We use the fact that the Cantor pairing is equal to
$$ {n + m + 1 \choose 2} + m $$
Where the left term just happens to be the number of nonempty contiguous slices of \$m+n\$. This saves two bytes per program over the naive +‘×+H+, and one byte over the (less naive) +‘c2+.
Conveniently, in Jelly + zips strings (I had no idea!).
Explanations:
          Implicit input: strings s1, s2
+         Zip s1, s2.
 Ẇ        All nonempty slices.
  ɼ       Save the result to register (ignore previous 2).
   +      Zip s1, s2.

          Implicit input: numbers n, m
+         Compute m+n.
 Ẇ        All nonempty slices of implicit range m+n.
  L       Length.
   +      Add m.

Note that there are many ways to get 4 for the pairing function (+R;S, +R+ƒ, etc)


This code assumes that both x0 and x1 are inclusive endpoints, and that words are little endian (i.e. the (0,0) pixel can be set with array[0][0]|=1).

int line(word *array, int x0, int x1, int y) {
  word *line = array + (y << 4);
  word *start = line + (x0 >> 4);
  word *end = line + (x1 >> 4);
  word start_mask = (word)-1 << (x0 & 15);
  word end_mask = (unsigned word)-1 >> (15 - (x1 & 15));
  if (start == end) {
    *start |= start_mask & end_mask;
  } else {
    *start |= start_mask;
    *end |= end_mask;
    for (word *p = start + 1; p < end; p++) *p = (word)-1;
  }
}


Haskell, 576 554 532 507 bytes

No built-ins!

import Data.Complex
s=sum
l=length
m=magnitude
i=fromIntegral
(&)=zip
t=zipWith
(x!a)b=x*a+b
a#b=[[s$t(*)x y|y<-foldr(t(:))([]<$b)b]|x<-a]
f a|let c=[1..l a];g(u,d)k|m<-[t(+)a b|(a,b)<-a#u&[[s[d|x==y]|y<-c]|x<-c]]=(m,-s[s[b|(n,b)<-c&a,n==m]|(a,m)<-a#m&c]/i k)=snd<$>scanl g(0<$c<$c,1)c
p?x|let f=foldl1(x!);c=l p-1;n=i c;q p=init$t(*)p$i<$>[c,c-1..];o=f(q p)/f p;a|d<-sqrt$(n-1)*(n*(o^2-f(q$q p)/f p)-o^2)=n/last(o-d:[o+d|m(o-d)<m(o+d)])=last$p?(x-a):[x|m a<1e-9]
z[a,b]=[-b/a]
z p=p?0:z(init$scanl1(p?0!)p)

Try it online!

Many thanks @ØrjanJohansen for a total of -47 bytes!

Explanation

First this computes the characteristic polynomial with the Faddeev–LeVerrier algorithm which is the function f. Then the function z computes all roots of that polynomial by iterating g which implements Laguerre's Method for finding a root, once a root is found it is removed and g gets called again until the polynomial has degree 1 which is trivially solved by z[a,b]=[-b/a].

Ungolfed

I re-inlined the functions sum,length,magnitude, fromIntegral, zipWith and (&) as well as the little helper (!). The function faddeevLeVerrier corresponds to f, roots to z and g to laguerre respectively.

-- Transpose a matrix/list
transpose a = foldr (zipWith(:)) (replicate (length a) []) a

-- Straight forward implementation for matrix-matrix multiplication
(#) :: [[Complex Double]] -> [[Complex Double]] -> [[Complex Double]]
a # b = [[sum $ zipWith (*) x y | y <- transpose b]|x<-a]

-- Faddeev-LeVerrier algorithm
faddeevLeVerrier :: [[Complex Double]] -> [Complex Double]
faddeevLeVerrier a = snd <$> scanl go (zero,1) [1..n]
  where n = length a
        zero = replicate n (replicate n 0)
        trace m = sum [sum [b|(n,b)<-zip [1..n] a,n==m]|(m,a)<-zip [1..n] m]
        diag d = [[sum[d|x==y]|y<-[1..n]]|x<-[1..n]]
        add as bs = [[x+y | (x,y) <- zip a b] | (b,a) <- zip as bs]
        go (u,d) k = (m, -trace (a#m) / fromIntegral k)
          where m = add (diag d) (a#u)

-- Compute roots by succesively removing newly computed roots
roots :: [Complex Double] -> [Complex Double]
roots [a,b] = [-b/a]
roots   p   = root : roots (removeRoot p)
  where root = laguerre p 0
        removeRoot = init . scanl1 (\a b -> root*a + b)

-- Compute a root of a polynomial p with an initial guess x
laguerre :: [Complex Double] -> Complex Double -> Complex Double
laguerre p x = if magnitude a < 1e-9 then x else laguerre p new_x
  where evaluate = foldl1 (\a b -> x*a+b)
        order' = length p - 1
        order  = fromIntegral $ length p - 1
        derivative p = init $ zipWith (*) p $ map fromIntegral [order',order'-1..]
        g  = evaluate (derivative p) / evaluate p
        h  = (g ** 2 - evaluate (derivative (derivative p)) / evaluate p)
        d  = sqrt $ (order-1) * (order*h - g**2)
        ga = g - d
        gb = g + d
        s = if magnitude ga < magnitude gb then gb else ga
        a = order /s
        new_x = x - a


Haskell, 132 bytes

v=0:[95,135..255]
f c=snd$maximum[(-sum(abs<$>zipWith(-)c x),i)|(i,x)<-zip[16..]$[[r,g,b]|r<-v,g<-v,b<-v]++[[g,g,g]|g<-[8,18..238]]]

Try it online!

Takes input as a list of integers [red, green, blue].

Fairly straightforward implementation. First I build a list of the Xterm colors we're using with two list comprehensions concatenated together. The first of which handles colors 16-231 by triple iterating over v which contains the values those colors use. The second one just iterates over the grey values and puts them in all three slots. Then I index it with zip (starting at 16) and make a pair with the manhattan distance (negated) and that index and take the maximum. I used maximum because we're tie-breaking on the largest index and this way saves me one extra -.


J, 94

f=:>@(0&{)
d=:0{[%~0{[:f]
D=:4 :'x((1}.([:f])-((#@]{.[)f)*d);([:>1{]),d)^:(>:((#f y)-(#x)))y'

eg.

(1 0 _5) D (12 _5 3 _1;'')
63 _26 | 12  _5

Explanation of some snippets, given that a: (12 -5 3 -1) and b: (1 0 -5)

length of a:

#a
4

make a and b same order by appending zeroes to b:

(#a) {. b
1 0 -5 0

divide higher powers (first elements) of a, b:

(0{a) % (0{b)
12

multiply b by that and subtract it from a:

a - 12*b
12 0 _60

repeat n times b = f(a,b):

a f^:n b


A small language deserves a small interpreter

Ruby, 182 bytes

$h=Hash.new 0
def r(c)c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){$4?($1=~/(.*?)<(.*)>/
($h[$1]-=1;r$2)while$h[$1]>0):$3<?"?p($h[$2]):$h[$2]+=$3<?@?STDIN.gets.to_i:
1}end
r IO.read *$*

Try it like this:

$ cat code
a?b<>c<>a<c^c^c<b^>>b!

$ ruby lynn.rb code
3                           <-- input
6                           <-- output

How it works

The r function tokenizes an input string and executes each token:

def r(c)
    c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){
        ...
    }
end

We look for some variable name $2 matching [^!?^<>]*, followed by either

<...> where ... matches zero or more programs (\g is recursion), in which case $4 isn't nil
A !, ?, or ^ character, captured by $3, in which case $4 is nil.

Then the logic for executing a token is quite simple when indenting it a bit:

$4 ? (                                    # If it's a loop:
    $1 =~ /(.*?)<(.*)>/                   #   Re-match token*
    ($h[$1]-=1; r $2) while $h[$1] > 0    #   Recurse to run loop
) :                                       # Else:
    $3 < ?"                               #   If it's an !:
      ? p($h[$2])                         #     Print the var
      : $h[$2] +=                         #   Else, increment it by:
          $3 < ?@                         #     If it's a ?:
              ? STDIN.gets.to_i           #       User input
              : 1                         #     Else: 1

* There's an oniguruma bug, I think, that keeps me from simply using $3 here.


An Array of Challenges #1: Alternating Arrays

Jelly, 4 bytes

ḣ2ṁ⁼

Try it online!

How it works

ḣ2ṁ⁼  Main link. Argument: A (array)

ḣ2    Head 2; truncate A after its second element. If A has two or less elements,
      this returns A itself.
  ṁ   Mold; cyclically repeat the elements of the previous result to create an
      array that has the same shape/length as A.
   ⁼  Test the result for equality with A.


Shortest code to check if a number is in a range in JavaScript

13 chars, checks both variants a<b and b<a

(x-a)*(x-b)<0

In C may be used expression (may be also in JavaScript). 11 chars, No multiplications (fast)

(x-a^x-b)<0


Pyth, 18 chars

mj\*dfqzsTsm^Qkhlz

This solution is adapted from my Interpreting Fish
solution. The problems are actually very similar.

Expects input as such:

aaaa
"a", "aaa"

Gives output like this:

['a*aaa', 'aaa*a', 'a*a*a*a']

Try it here.

sm^Qkhlz: Generates all sequences of variables containing up to the length of the input string number of variables.
fqzsT: Filters out the variable sequences that match the input string
mj\*d: Inserts the * symbol and prints.


MATL, 12 bytes
YF2:&Y)dwd*s

Input is an array [num1 den1 num2 den2].
Try it online! Or verify all test cases.
Explanation
Consider example input [20 1 14 15].
YF      % Implicit input: array of 4 numbers. Exponents of prime factorization.
        % Gives a matrix, where each row corresponds to one of the numbers in
        % the input array. Each row may contain zeros for non-present factors
        % STACK: [2 0 1 0
                  0 0 0 0
                  1 0 0 1
                  0 1 1 0]
2:&Y)   % Push a submatrix with the first two rows, then a submatrix with the
        % other two rows
        % STACK: [2 0 1 0
                  0 0 0 0],
                 [1 0 0 1
                  0 1 1 0]
d       % Consecutive difference(s) along each column
        % STACK: [2 0 1 0
                  0 0 0 0],
                 [-1 1 -1 1]
wd      % Swap, and do the same for the other submatrix
        % STACK: [-1 1 -1 1]
                 [-2 0 -1 0]
*       % Element-wise product
        % STACK: [2 0 -1 0]
s       % Sum. Implicit display
        % STACK: 1


Use preinitialized variables
Pip has many global variables that are pre-initialized so you can avoid manually writing a number/string/something else out yourself.
Here are some of them (complete list):

_ Identity function (== {a})

h 100

i 0

k ", "

l Empty list

m 1000 (mnemonic: Roman numeral M)

n Newline character

o 1

s Space character

t 10

v -1

w Matches whitespace \s+

x Empty string

z Lowercase alphabet a to z

B Block that returns its second argument ({b})

G Block that returns its argument list ({g})

AZ Uppercase alphabet A to Z

CZ Lowercase consonants b to z

PA All Printable ASCII characters, 32 through 126

PI \$\pi\$ (3.141592653589793)

VW Lowercase vowels a to u

VY Lowercase vowels a to y

XA Matches one Latin letter [A-Za-z] (there are more X* commands)

Link to documentation


ASCII clock with dot & comma time markers

Pyth, 19 bytes

:.iF*V.DQ60J"',"J\;

Test suite

:.iF*V.DQ60J"',"J\;
      .DQ60            Divmod the input by 60, giving [hours, minutes].
           J"',"       Set J equal to the string "',".
    *V                 Perform vectorized multiplication, giving H "'" and M ','.
 .iF                   Interleave the two lists into a single string.
:               J\;    Perform a substitution, replacing J with ';'.


Python 3, 388 398 408 409 415 417 493 bytes

To make it more accurate, increase n

from random import*
u=uniform
c=lambda A,B,C:(C[1]-A[1])*(B[0]-A[0])>(B[1]-A[1])*(C[0]-A[0])
I=lambda A,B,C,D:c(A,C,D)!=c(B,C,D)and c(A,B,C)!=c(A,B,D)
def a(l,v,n=9**6,s=0):
 g=lambda i:(min(x[i]for x in v),max(x[i]for x in v))
 for _ in'x'*n:
  h=((u(*g(0)),u(*g(1))),l);s+=any([I(*f,*h)for f in list(zip(v,v[1:]+[v[0]]))])^1
 return(abs(g(0)[0]-g(0)[1])*abs(g(1)[0]-g(1)[1]))*float(s/n)

Basic Monte-Carlo approach.  Steps listed below.

Find x and y ranges that the shape occupies.
Create a list of edges created by the vertices
Iterate a large number of times (the more the better)
Create a random point (j,k) inside the x,y range.
Check if any of the edges intercept with the line-segment created by the light and the random point. If any of the edges intercept, increment the variable s
Divide s by the total numbers, then multiply by the total range area.

Ungolfed version:

import random

def ccw(A,B,C):
    return (C[1]-A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0])

def intersect(A,B,C,D):
    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

def lit_area(light, vertices):
    # points: list of points
    # i     : x => i=0
    #       : y => i=1
    get_range = lambda i: (min(x[i] for x in vertices), max(x[i] for x in vertices))
    xr = abs(get_range(0)[0] - get_range(0)[1])
    yr = abs(get_range(1)[0] - get_range(1)[1])

    edges = list(zip(vertices, vertices[1:] + [vertices[0]]))

    num_sims = 1000000

    num_successes = 0
    for _ in range(num_sims):
        guess_x = random.uniform(*get_range(0))
        guess_y = random.uniform(*get_range(1))

        light_guess_line = ((guess_x, guess_y), light)

        if not any([intersect(*e, *light_guess_line) for e in edges]):
            num_successes += 1
    return float(num_successes / num_sims) * (xr * yr)

if __name__ == "__main__":
    points = [
    (1/2, 18),
    (1,3),
    (5,1/2),
    (7,5),
    (12,7),
    (16,3),
    (15,11),
    (8,19),
    (3,7)
    ]
    light_source = (5,8)
    print("Area lit by light: %f"% lit_area(light_source, points))

Try it online!

Credit for line intersection algorithm

Also, credit to all the helpful commenters on how to golf this even further.


Shortest POSIX command line that eagerly removes dual newline sequences

Bash, 32 bytes

awk 'BEGIN{RS="\n\n";ORS="";} 1'

Try it online!


Could you please stop shuffling the deck and play already?

JavaScript (ES6), 44 bytes
Shorter version suggested by @nwellnhof
Expects a deck with 1-indexed cards as input.

f=(a,x=1)=>a[x]-2&&1+f(a,x*2%(a.length-1|1))

Try it online!
Given a deck \$[c_0,\ldots,c_{L-1}]\$ of length \$L\$, we define:
$$x_n=\begin{cases}
2^n\bmod L&\text{if }L\text{ is odd}\\
2^n\bmod (L-1)&\text{if }L\text{ is even}\\
\end{cases}$$
And we look for \$n\$ such that \$c_{x_n}=2\$.

JavaScript (ES6),  57 52  50 bytes
Expects a deck with 0-indexed cards as input.

f=(a,x=1,k=a.length-1|1)=>a[1]-x%k&&1+f(a,x*-~k/2)

Try it online!
How?
Since JS is lacking native support for extracting array slices with a custom stepping, simulating the entire riffle-shuffle would probably be rather costly (but to be honest, I didn't even try). However, the solution can also be found by just looking at the 2nd card and the total number of cards in the deck.
Given a deck of length \$L\$, this code looks for \$n\$ such that:
$$c_2\equiv\left(\frac{k+1}{2}\right)^n\pmod k$$
where \$c_2\$ is the second card and \$k\$ is defined as:
$$k=\begin{cases}
L&\text{if }L\text{ is odd}\\
L-1&\text{if }L\text{ is even}\\
\end{cases}$$


JavaScript (Node.js), 121 110  bytes

Same as TFled. A "golfed" version of the example.

-11 bytes from @Arnauld

with(Math)f=(a,[b,B],c,d)=>(g=w=>a--?g(w.map(_=>_+d*(c-(y=1/(1+exp(B*w[1]-b*w[0])))))):y)([random(),random()])

Try it online!


Bloatware contest: producing 100+ MiB executable

OK, here's another one in C, going for the vaguely defined bonus points:

#define a(x) x,x|1,x|2,x|3,x|4,x|5,x|6,x|7
#define b(x) a(x),a(x|8),a(x|16),a(x|24)
#define c(x) b(x),b(x|32),b(x|64),b(x|96)
#define d(x) c(x),c(x|128),c(x|256),c(x|384)
#define e(x) d(x),d(x|512),d(x|4<<8),d(x|6<<8)
#define f(x) e(x),e(x|2048),e(x|4096),e(x|6144)
#define g(x) f(x),f(x|8192),f(x|4<<12),f(x|6<<12)
#define h(x) g(x),g(x|2<<14),g(x|4<<14),g(x|6<<14)
#define i(x) h(x),h(x|2<<16),h(x|4<<16),h(x|6<<16)
#define j(x) i(x),i(x|2<<18),i(x|4<<18),i(x|6<<18)
#define k(x) j(x),j(x|2<<20),j(x|4<<20),j(x|6<<20)
int u,v,z[]={k(0),k(2<<22),k(4<<22),k(6<<22)}
int main(){for(u=v=0;u<1<<25;u++)v|=u!=z[u];return v;}

Basically, at compile time, it build a ascending sequence of integers from 0 to 225 − 1.  At runtime, it verifies that the sequence indeed contains the expected values, and if not, returns a non-zero error code.

Ps. If I did my math right, the executable should be over 100 MiB.  I'll let you know the exact size once it's done compiling...


Retina 0.8.2, 82 bytes

+1`/-o-./o./o.|(/-o-.)/o.|(/o.(/o.)?)/-o-.(/o.)|/o./o./-o-.|/o.(/-o-.)
$1$2$4$5

Try it online! Link includes test suite. Explanation: The first stage simply deletes whitespace. (The footer spaces the remaining Jimmies back out out.) The second stage then repeatedly replaces the first available match with the captures until no more replacements can be made. The matches are as follows:

/-o-./o./o. Matches a bodybuilder next to two acrobats. There is no capture because this takes out the bodybuilder as well.
(/-o-.)/o. Matches a bodybuilder next to an acrobat. There's no second acrobat here, because it would have matched above, so the lone acrobat is taken out, while the bodybuilder survives.
(/o.(/o.)?)/-o-.(/o.) Matches a bodybuilder between two acrobats, with up to two acrobats to his left. The bodybuilder is taken out.
/o./o./-o-. Matches a bodybuilder with two acrobats to his left (but no acrobats to his right, as that would have already matched). All three are taken out.
/o.(/-o-.) Matches a bodybuilder with one acrobat to his left (but no acrobats to his right, as that would have already matched). The acrobat is taken out.


Source = Target = CJam, 19 17 16 bytes

{`"_~"+}`)q\"_~"

This assumes that the input program Q (given on STDIN) is some CJam snippet which expects a string on the top of the stack and leaves another string on top of the stack.

Test it here.

Examples

The identity would just be an empty snippet, so leaving STDIN empty prints

{`"_~"+}_~

Which is the standard quine, with an additional +.
To reverse a string in CJam, you can use W%, so putting that on STDIN, this yields:

{`"_~"+W%}_~

which we can run to obtain

~_}%W+"~_"`{

As a third example, say we use a snippet which intersperses a string with spaces: ' *. Running P with that as input, we get

{`"_~"+' *}_~

which in turn prints

{ ` " _ ~ " + '   * } _ ~

It now also works if Q contains line breaks (although that's never necessary in CJam). Here is a program with a line break, which removes all line breaks from a string (in an unnecessarily convoluted way - split into lines, then join):

N/
""
*

This results in the following R:

{`"_~"+N/
""
*}_~

which in turn prints

{`"_~"+N/""*}_~

Explanation

Let's look at the produced output first:

The standard CJam quine is

{`"_~"}_~

It works as follows:

Push the block {`"_~"}.
Duplicate it with _.
Execute the copy with ~.
Now inside the block, ` turns the first block into its string representation.
"_~" pushes the two characters of the source that are not part of the block (and hence missing from the string representation).
The two strings are printed back to back at the end of the program.

In the basic quine the ` is unnecessary, because if you just leave the block as it is, it's printed all the same at the end of the program.

The output of my program P is a modified version of this snippet. First, I've added a + to the block, which concatenates the two strings into one string containing the entire source. Note that this will be true no matter what I do inside the block, because that will all get added to the string representation obtained with `. Now I can simply put the program/snippet Q inside the block after the +, so that it can modify the source string before it is printed. Again, since Q goes inside the block, it will be part of said source string.

In summary, P prints

{`"_~"+Q}_~

Now, for how I go about constructing this output in P:

{`"_~"+}         "Push the block without Q.";
        `        "Turn it into a string. This is shorter than writing a string right away,
                  because I'd have to escape the quotes, and I'd need two quotes instead of
                  one backtick.";
         )       "Pop off the last character (the brace) and push it on the stack.";
          q      "Read input Q.";
           \     "Swap Q with the brace.";
            "_~" "Push the final two characters.";

The four strings are printed automatically (back-to-back) at the end of the program.


JavaScript 140 chars

For the first solution, I assume that the fuel pits are provided in order order of location around the track and in the form:

var fuelPitInfo = [
    {
       location: 2,//The location from some point on the track
       fuelDistance: 1//The distance you can travel with the fuel from this stop
    },
    ..
]

Thus, a potential non code-golfed JavaScript function to calculate a working starting location is as follows (test fiddle):

function calculateStartingLocation(trackLength, fuelPitInfo) {
    for(i=0;;i++){
        var fuelPit = fuelPitInfo[i];
        var remainingFuelDistance = fuelPit.fuelDistance;
        for(j=i+1;;j++){
            var nextFuelPit = fuelPitInfo[j = j % fuelPitInfo.length];
            if (i == j) return fuelPitInfo[i].location;
            remainingFuelDistance -= (nextFuelPit.location - fuelPit.location + trackLength) % trackLength;
            if (remainingFuelDistance < 0) break;
            remainingFuelDistance += nextFuelPit.fuelDistance;
            fuelPit = nextFuelPit;
        }
    }
}

And the code-golfed function version (140 chars) is as follows (assuming location is replaced with l and fuelDistance is replaced with d in the provided fuelPitInfo object) (test fiddle):

function a(b,c){for(i=0;e=c[i],f=e.d;i++){for(j=i+1;g=c[j=j%c.length];){if(i==j++)return c[i].l;f-=(g.l-e.l+b)%b;if(f<0)break;f+=g.d,e=g;}}}


Perl 5, 130 bytes

print$e=("+"."-"x10)x3 ."+
";printf"|$_.exe%4s |%-10s|%-9s |
$e",$|--&&$@++<9?("$@0%","#"x$@,leeching):("","#"x10,seeding)for a..z

Try it online!

I expect that there are a few bytes that can be golfed, but I've ran out of inspiration.

Short explanations:
$e contains the separation line (+----------+----------+----------+); its construction is straight forward (("+"."-"x10)x3 ."+\n").
Then, I loop over the characters from a to z:
Every time, print "|$_.exe%4s |%-10s|%-9s |\n$e; this is a standard printf with placeholders for strings (%s) and left-padded strings (%-9s).
if $|--&&$@++<9 is true ($| is a special variable that contains either 0 or 1, and decrementing it toggles its value), then the percentage is not 100%, and the three values in the print are "$@0%","#"x$@,leeching ($@0% is actually just $@ . "0" . "%" - remember that $@ was incremented earlier), otherwise, the three values are "","#"x10,seeding).


Reduce the amount of loops when finding if an element is stored only once in the array?

D

bool containsOnce(E,R)(R haystack,E needle){
     bool foundOnce=false;
     foreach(e;haystack){
          if(e==needle){
              if(foundOnce)return false;
              foundOnce=true;
          }
     }
     return foundOnce;
}

this is pretty much the best case on unsorted data, you loop until you find a match and then set a flag to true and continue looping, when you find the second match return false immediately, when you looped over the entire thing return state of the flag

this has better timebounds when the double match is found near the beginning of the array (and in general when the items are close together) (but is better in a code-golf contest ;) )

in interest of time bound you'll remain at O(n) regardless on any algorithm (sometimes there simply are no improvements possible except with micro-optimizations). as finding a single match (a subproblem of the current problem) in an unsorted array is O(n)


Haskell, 53 bytes

[tail$do c<-reverse a;' ':[c|c<=d]|d<-a]
a=['A'..'Z']

Try it online!

This uses that each line has exactly 25 spaces. So, instead of separately handling the prefix spaces and the spaces between letters, we take 26 spaces, and decide whether to put a letter after each. This unfortunately gives one extra leading space, which we remove.

54 bytes

foldl(\m c->map(' ':)m++[c:' ':last m])["A"]['B'..'Z']

Try it online!

55 bytes

"A"%['B'..'[']
s%(h:t)=((' '<$t)++s):(h:' ':s)%t
s%_=[]

Try it online!


Jelly, 17 bytes

I went off-piste with the meals in my example without realising! It shouldn't matter I think, and looks tastier to my British eyes.

ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż

A dyadic link taking a list of foods (lists of characters) on the left and people (also lists of characters) on the right which returns a list containing a list per person containing a list of characters (their name) and a list of foods (each a list of characters).

e.g. (using "..." to represent a list of characters):

left = ["Champagne", "Turkey", "Stuffing", "Port", "Roast Potatoes", "Brussel Sprouts", "Parsnips", "Pigs In Blankets", "Gravy", "Steamed Vegetables", "Cheese Plate", "Christmas Pudding"]
right = ["Aunt Gertrude", "Cousin Sally", "Grandpa Joe"]

output = [[["Champagne", "Brussel Sprouts"],"Aunt Gertrude"],[["Stuffing", "Parsnips"],"Cousin Sally"],[["Port", "Pigs In Blankets"],"Grandpa Joe"]]

(leaving us with Turkey, Roast Potatoes, Gravy, Steamed Vegetables, and Christmas Pudding.)

Try it online! (The footer calls the dyadic link and then pretty prints the result)

How?

ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż - Link: foods, people
            ¤     - nilad followed by link(s) as a nilad:
         ⁹        -   chain's right argument, people
          L       -   length
           ‘      -   increment (add yourself to the cook count)
       ¤          - nilad followed by link(s) as a nilad:
 “Øẇ½»            -   compressed string = list of characters, ['T','u','r','k','e','y']
      W           -   wrap in a list                          [['T','u','r','k','e','y']]
ḟ                 - filter discard (from foods) if exists in that list (we cook any Turkey)
        s         - split (the resulting list of foods) into chunks (of number of cooks)
             Ṗ    - pop off the excess
              Z   - transpose to a list of fair shares
               Ṗ  - pop off our share
                ż - zip with people names (to provide the allocations)


Mathematica, 125 bytes (121 chars)

(f@{_}=0;f@l_:=1+Min[Max[{g=GatherBy[l,vFreeQ[#-v,0]]}~With~If[Length@g<2,∞,f/@g]]&/@R~T~#];f@(T=Tuples)[R=Range@10,#])&

Try it online!

(it actually does not run the code, just the function pasted into TIO. So because the function is not invoked, it does nothing)

This cannot be run even with input n=1 because it has no memoization or whatever optimization. The ungolfed code below, however, does return 9 for n=1.

Ungolfed code:

n = Input[];

base = 10;

Clear@f;
f@{_} = 0;
f@l_ := f@l =
  1 + Min[
    Max[
       With[{groups = GatherBy[l, v \[Function] FreeQ[# - v, 0]]},
        If[Length@groups == 1, Infinity, f /@ groups]
        ]
       ] & /@ Tuples[Range@base, n]
    ]

f@Tuples[Range@base, n]

This code run in upper bound time O(2^(10^n poly(n))), which is impractical for all n ≥ 2.

Explanation:

Let a number be represented as a list of n numbers from 1 to 10. There are 10^n numbers.
Then, the function f receive a list of "numbers" l (so a 2D list of digits), and return the information "assuming all the possible candidate numbers are in the list l, at least how many question are necessary to reduce it to 1 candidate in the worst case?"
So the function f is defined as:

f@{_} = 0;

When there is only 1 candidate, we only need to ask 0 more questions.

f@l_ := f@l =

Memoization (in ungolfed code) to slightly improve performance.

1 +

Ask one question.

/@ Tuples[Range@base, n]

For each possible number (numbers are represent as n-tuple of digits, each digit is in the range from 1 to base (10)) to be asked,

Min[]

find the minimum (best strategy)

groups = GatherBy[l, v \[Function] FreeQ[# - v, 0]]

partition the candidates to 2 groups: one gives the value "Close" when ask this number, and the other gives the value "Fail" when ask this number.

If[Length@groups == 1,

If all the numbers in the list l get to the same answer when test,

Infinity

return Infinity (avoid asking this question, avoid loop forever)

, f /@ groups

otherwise recursively apply the function f to the resulting group

Max[]

and get the maximum (worst case).


JavaScript (ES7), 58 bytes

Takes the two strings in currying syntax (a)(b).

a=>b=>(g=s=>parseInt(s)*'_dp'.search(s[1])**3)(a)>g(b)?a:b

Try it online!

How?

The helper function g() translate the input string s into a score.

1) We look for s[1] into the string "_dp". This gives:

1 for a dan rank "xd"
2 for a professional dan rank "xp"
-1 for a kyū rank "xk" or "xxk" because s[1] is either "k" or a digit

2) We cube this result, which leaves 1 and -1 unchanged but gives 8 for a professional dan rank.

3) We multiply by the decimal part of the rank.