Postscript

Not fully golfed, but this illustrates a different approach than deCasteljau subdivision: evaluating the basis polynomial. Uses mat.ps.

(mat.ps)run[    % load matrix library, begin dictionary construction

/N 17
/C [ 0 7 4 ]   % Cam
/E [ 0 0 40 ] % Eye
/R 0 roty 120 rotx 90 rotz   % Rot: pan tilt twist
          matmul   matmul

/f(teapot)(r)file
/t{token pop exch pop}      % parse a number or other ps token
/s{(,){search not{t exit}if t 3 1 roll}loop}  % parse a comma-separated list
/r{token pop{[f 99 string readline pop s]}repeat}>>begin   % parse a count-prefixed paragraph of csv numbers
[/P[f r]/V[f r]/v{1 sub V exch get}        % Patches and Vertices and vert lookup shortcut
/B[[-1 3 -3 1][3 -6 3 0][-3 3 0 0][1 0 0 0]]              % Bezier basis matrix
/A{dup dup mul exch 2 copy mul 3 1 roll 1 4 array astore} % x->[x^3 x^2 x 1]
/M{[1 index 0 4 getinterval 2 index 4 4 getinterval       % flattened matrix->rowXcolumn matrix
3 index 8 4 getinterval 4 index 12 4 getinterval]exch pop}
/J{ C{sub}vop R matmul 0 get                              % perspective proJection  [x y z]->[X Y]
    aload pop E aload pop
    4 3 roll div exch neg
    4 3 roll add 1 index mul 4 1 roll
    3 1 roll sub mul}
>>begin

300 400 translate
1 14 dup dup scale div currentlinewidth mul setlinewidth  % global scale
/newline { /line {moveto /line {lineto} store} store } def
newline
P{
    8 dict begin
        [exch{v J 2 array astore}forall]/p exch def   % load patch vertices and project to 2D
        /X[p{0 get}forall] M B exch matmul B matmul def  % multiply control points by Bezier basis
        /Y[p{1 get}forall] M B exch matmul B matmul def

        0 1 N div 1 1 index .2 mul add{A/U exch def   % interpolate the polynomial over (u,v)/(N)
            /UX U X matmul def
            /UY U Y matmul def
            0 1 N div 1 1 index .2 mul add{A/V exch 1 array astore transpose def
                /UXV UX V matmul def
                /UYV UY V matmul def
                UXV 0 get 0 get
                UYV 0 get 0 get line
            }for
            newline
        }for

        0 1 N div 1 1 index .2 mul add{A/V exch def   % interpolate the polynomial over (u,v)/(N)
            /V [V] transpose def
            /XV X V matmul def
            /YV Y V matmul def
            0 1 N div 1 1 index .2 mul add{A/U exch 1 array astore transpose def
                /UXV U XV matmul def
                /UYV U YV matmul def
                UXV 0 get 0 get
                UYV 0 get 0 get line
            }for
            newline
        }for

    end

    %exit
}forall
stroke

1112

Stripping out the vertical lines, and discounting the parameters, yields
this 1112 char version. Uses mat.ps.

(mat.ps)run[    % 12

/N 17
/C [ 0 7 4 ]   % Cam
/E [ 0 0 40 ] % Eye
/R 0 roty 120 rotx 90 rotz   % Rot: pan tilt twist
          matmul   matmul

/f(teapot)(r)file/t{token pop exch pop}/s{(,){search not{t exit}if t   % 1100
3 1 roll}loop}/r{token pop{[f 99 string readline pop
s]}repeat}>>begin[/P[f r]/V[f r]/v{1 sub
V exch get}/B[[-1 3 -3 1][3 -6 3 0][-3 3 0 0][1 0 0 0]]/A{dup dup mul exch
2 copy mul 3 1 roll 1 4 array astore}/M{[1 index 0 4 getinterval 2 index 4 4 getinterval
3 index 8 4 getinterval 4 index 12 4 getinterval]exch pop}/J{C{sub}vop R matmul 0 get
aload pop E aload pop 4 3 roll div exch neg 4 3 roll add 1 index mul 4 1 roll
3 1 roll sub mul}>>begin 300 400 translate
1 14 dup dup scale div currentlinewidth mul setlinewidth
/newline{/line{moveto/line{lineto}store}store}def newline
P{8 dict begin[exch{v J 2 array astore}forall]/p
exch def/X[p{0 get}forall] M B exch matmul B matmul
def/Y[p{1 get}forall] M B exch matmul B matmul def
0 1 N div 1 1 index .2 mul add{A/U exch def/UX U X matmul def/UY U Y matmul def
0 1 N div 1 1 index .2 mul add{A/V exch 1 array astore transpose
def/UXV UX V matmul def/UYV UY V matmul def UXV 0 get 0 get UYV 0 get 0 get line}for
newline}for end}forall stroke


05AB1E, 18 bytes

[DR²£O©‚˜³®>‹#]³QZ

Try it online!

Uses: [X,Y], N, A

I feel like some unintended functionality made that harder than it needed to be.

There's no greater-than-or-equal-to, never noticed that before.

And #³ didn't work, and required a ], for +1 bytes #]³.


Write a polyglot that prints the language's name

Bash, C, C++, Obj-C, Obj-C++, Perl, PHP, Ruby, 183 chars

score ~ 0.1236

For the C and C-like codes I owe a debt to @baby-rabbit. The others are inspired by the recognition that many languages have an eval statement that will grudgingly accept invalid syntax.

Outputs the language name to standard output. Sometimes generates a lot of error messages on standard error, so suppress them with 2>/dev/null as you run them.

#if 0
'PHP<?/*';eval "print\$=?'Perl':'Ruby';echo Bash";exit
__END__
#endif
#include <stdio.h>
main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}//*/?>'

The php solution outputs 'PHP' (including the single quotes), which may be bending the rules a little bit.

Last edit: shaved 12 chars from insight that $= is false in Ruby, 60 in Perl, and print$=?... is almost surely an error in Bash. Shaved 7 more from insight the Perl/Ruby/Bash test can now go into a single eval statement.

If the rules can tolerate more bending, I present this 8 language, 43 character solution (score 0.5262)

print("phperluarscriptrubypythoncatebg13");

for which the output includes the name of the interpreter for php, perl, lua, rscript, ruby, python, cat, and rot13.


Python 3, 91 77 bytes
-14 Bytes thanks to OMᗺ
I thought that the printout of a Python dictionary would be close enough to JSON to make it a very competitive language for this challenge.  However, the string representation of python dictionaries is different enough from JSON that I had better luck using python's built-in JSON library. I'll bet this can be done more succinctly in JavaScript.
import json
f=lambda x:json.dumps(dict(i.split("=")for i in x.split("\n")if i))

Try it Online!

Edit:
Bash + Sed, 68 63 bytes
Bug fix thanks to OMᗺ and Night 2
-5 Bytes thanks to OMᗺ
I realized that it might be more byte efficient to directly convert the text to JSON without bundling it in an object, as was my approach for the python solution.  Per byte, sed is the most powerful language for regex replacement that I know of.
echo {`echo "$1"|sed 's/"/\\\"/g;s/\(.*\)=\(.*\)/"\1":"\2",/'`}

Try it Online!
Explanation
echo {`                                  #  prints the leading curly brace
       echo "$1"|sed                     # feeds the input into sed
       's/"/\\"/g;                       # replaces " with \"
       s/\(.*\)=\(.*\)/"\1":"\2",/'      # surrounds the left and right hand sides of the equals with quotes and joins them with a colon
`}                                       # prints the closing curly brace


Python, 209 203 199 characters

I=input
x=I()+1
s=0
C=lambda:eval(raw_input().replace(' ','*%d+'%x))
exec's^=1<<C();'*I()
exec's^=1+(7<<x)/2+(1<<x<<x)<<(C()-x);'*I()
R=range(1,x)
for r in R:print''.join('OX'[s>>r*x+c&1]for c in R)

The state of the lights is kept in a single (big) integer variable, s.  XORs with bitmasks are used to toggle the lights.  I keep an extra bit per row to prevent wraparound.


JavaScript (ES6), 123 bytes
Returns the order as a space-separated string.

f=n=>n?(x=n>128|n==125?125:n>50?n<54?25:n-70?302256705>>n-80&n>79&n<109?80:50:n:n-24&&n-49?n<31|n%5<1?n:25:9)+' '+f(n-x):''

Try it online!
How?
Given a number \$n\$ of wings, we recursively apply the following strategy.
High values: \$n>128\$ or \$n=125\$
For high values, our best option is to buy \$125\$ wings. So that's what we're doing as long as \$n\$ is greater than or equal to \$129\$ or when \$n\$ is exactly equal to \$125\$.
We can't do that for \$125 < n < 129\$ because we'd be left with less than \$4\$ wings to buy, which is not possible.
Low values: \$n<31\$
For \$n<31\$, the best deal is to buy all remaining wings at once, except for \$n=24\$ which must be purchased as either \$2\times 12\$, \$18+6\$ or \$15+9\$. We arbitrarily buy \$9\$ wings in that case.
Range \$31 \le n \le 50\$
In this range, buying \$25\$ wings usually leads to an optimal order. But the following exceptions apply:

If \$n\$ is a multiple of \$5\$, we must buy all remaining wings at once.
If \$n=49\$, the best deals are \$40+9\$ and \$28+21\$. We arbitrarily buy \$9\$ wings in that case.

Range \$51 \le n \le 53\$
We can't buy \$50\$ wings in that range or we'll be left with less than \$4\$ wings. Our best option is to buy \$25\$ of them instead. (We could buy \$2\times26\$ wings for \$n=52\$, but buying \$25+27\$ is just as good.)
Range \$54 \le n \le 128\$ with \$n \neq 125\$
In this range, buying \$50\$ wings usually leads to an optimal order. But the following exceptions apply:

If \$n=70\$, we must buy all of them at once.

If \$n\$ is in \$\{80,86,89,92,98,105,108\}\$, we must buy \$80\$ wings. These values are encoded with the following bitmask, where the least significant bit is mapped to \$80\$ and the most significant one to \$108\$:
$$10010000001000001001001000001_{(2)} = 302256705_{(10)}$$


Write a program which performs brute force letter combination until the word "password" is found

Perl, 19 chars

say for a..password

Uses newlines as delimiters, per clarification above.  Run with perl -M5.010 (or just perl -E 'say for a..password') to enable the Perl 5.10+ say feature.  Per meta, this doesn't count as extra chars.

(If you insist on spaces as delimiters, $,=$";say a..password is only two chars longer.  However, it's also very slow and wasteful of memory, to the point of being unusable in practice, since it tries to build the entire list in memory before printing it.)


Jelly, 9 bytes

ŻŒḂ€ḋṚ$HĊ

A monadic Link accepting a non-negative integer which yields a non-negative integer.

Try it online!

How?

Counts all pairs without the \$a\leq b\$ restriction, halves and rounds up. Note that the halved count is only a fraction if \$\frac n 2\$ is a palindrome and in such cases we want to count this \$a=b\$ pair.

ŻŒḂ€ḋṚ$HĊ - Link: integer, n    e.g. 22
Ż         - zero-range               [0,1,2,...,9,10,11,12,...,21,22]
   €      - for each:
 ŒḂ       -   is palindrome (digits) [1,1,1,...,1,0,1,0,...0,1]
      $   - last two links as a monad:
     Ṛ    -   reverse                [1,0,...,0,1,0,1,...,1,1,1]
    ḋ     -   dot-product           3  (=1×1+1×0+...+1×0+1×1+0×1+...+0×1+1×1)
       H  - halve                   1.5
        Ċ - ceil                    2


C, 201 (Encoding) + 175 (Decoding) = 376 bytes
To Encode:
E(char*J){size_t L=ceil(sqrt(strlen(J)));int U;srand(time(NULL));for(int i=0;i<L;i++){for(int f=0;f<L;f++){printf("#%02X%02X%02X ",rand()%256,(U<strlen(J))?(int)J[U]:32,rand()%256);U+=1;}printf("\n");}}

Encodes each character of the input string in the green channel of the RGB spectrum while setting the two other channels as random hex values. Takes input through STDIN as a string and outputs to STDOUT a multiline string of hex color code in the shape of a square. Assuming you have Python 3 and ImageMagick installed, and the above file is compiled into a file named a.out in the current working directory (CWD), you can directly get the resulting image, named Output.png, to the CWD from the textual output using the following command:
./a.out "<Multiline Input>"|python3 -c "import sys,subprocess;Input=sys.stdin.read();print('# ImageMagick pixel enumeration: {0},{0},255,rgb\n'.format(len(Input.split('\n')[1].split()))+'\n'.join(['%d,%d:(%d,%d,%d)'%(g,i,int(j[1:][:2],16),int(j[1:][2:4],16),int(j[1:][4:6],16))for g,h in enumerate(Input.split('\n'))for i,j in enumerate(h.split())]))"|convert - -scale 1000% Output.png

Here is a sample output image created by the above commamd using Programming Puzzles and Code Golf as the input string:

To Decode:
D(int c,char**U){char T[c];for(int Y=1;Y<c;Y++){char G[2]={U[Y][3],U[Y][4]};T[Y-1]=(char)strtol(G,NULL,16);}int C=c-1;T[C]='\0';while(T[C]==' '){T[C]='\0';C-=1;}printf("%s\n",T);}

Takes input through STDIN a sequence of space-separated hex color code strings with each one enclosed in double quotes (") (char** argv in main) and also, when called in main, int argc for the integer input. Outputs to STDOUT a single/multi-line string representing the decoded message.
I will try to golf these more over time whenever and wherever I can.

Also, if you same both of the methods into the same file, you can use the following main method to put it all together with each function getting the correct inputs:
int main(int argc,char**argv){if(strcmp(argv[1],"E")==0){Encode(argv[2]);}else{Decode(argc,argv);}}

and using this, for encoding you must provide E as the first argument to call the encoding method followed by the single string argument, whereas for decoding, all you need to provide is the sequence of space-separated hex color code strings with each one enclosed in double-quotes (").

Finally, if you want, you can get the fully prepared, ready-to-use version here, although it is not golfed, but also does not output any warnings or errors upon compilation.


JavaScript ES6, 81 69 bytes

(y,m,d)=>d+parseInt("03479cehkmpr"[--m],36)+m*28-(y%(y%25?4:16)&&m>1)

Assuming months are 1-based, otherwise I could save 2 bytes.

Edit: Saved 12 bytes using @user81655's tip.


Python 2/C (clang), 109 107 100 84 95 88 89 88 87 84 bytes

i=0;
#/*
while 1:i+=1L;print`i`[::-1]
'''*/
a(){for(;;)printf("%i %1$i ",++i);}//'''

Python: Try it online!

C: Try it online!

The L in the Python code is part of the delimiter.

Explanation:

In the C code, It first sets i to 0. Then, it starts a comment (# is valid code in C for #include statements) where the Python code goes. At the end of the comment, it defines a function that forever increments a variable and prints it twice, space-delimited. It then begins a comment.

In the Python code, i=0; sets i to zero. Python ignores the next line because # starts a single-line comment. It then forever increments it and turns it into a long a number and prints its reversed string representation. The 'L' from the long is part of the delimiter. After that, it starts a multi-line string to comment the C code, that ends later.

-2 bytes thanks to @LuisMendo. -7 bytes thanks to @ZacharyT. -6 more bytes thanks to @ZacharyT. +11 bytes to fix a bug thanks to @mbomb007. -7 bytes thanks to @Doorknob. +1 byte to fix a bug thanks to @Doorknob. -1 byte thanks to @yoann. -1 more byte thanks to @yoann. -3 bytes thanks to @Cyoce.


Jelly, 9 bytes

‘ḶDœ|/ḟ9L

Try it online!

How it works

‘ḶDœ|/ḟ9L
‘Ḷ         [0,1,...,n]
  D        convert each to list of its digits
   œ|/     fold by multiset union
      ḟ9   remove 9
        L  length


CJam, 87 83 82 80 bytes

0"hTHøìð¼Ä¿håêÛ¾ªÔ¼"256b6b5a/4a8**li<{[33:B_B*65_B*1]=\_B%8=B\#*+}/Bb0-`

The above code contains unprintable characters.

Try it online in the CJam interpreter. If the link doesn't work for you, copy from this paste.

Background

To obtain the electron configuration of the Nth atom, we start with an atom without electrons and apply N transformations to it.

To reduce the byte count of the implementation, we represent the electron configuration of an atom as an integer. Each digit of that integer in base 33 corresponds to the number of electrons in a certain shells; the least significant digit represents the outer shell.

For example, the electron configuration of Molybdenum (42) is [2 8 18 13 1]. This corresponds to the integer 2 × 334 + 8 × 333 + 18 × 332 + 13 × 33 + 1 = 26,79,370.

Palladium (48) is a special case, which we treat as [2 8 18 18 0] instead of [2 8 18 18].

This convenient representation reduces the aforementioned transformations to simple arithmetic:

R += 1 (add an electron to the outer shell)
R += 33 (add an electron to the second outer shell)
R += 65 (add two electrons to the second outer shell; remove one from the first)
R += 1089 (add an electron to the third outer shell)
R += 2145 (add two electrons to the third outer shell; remove one from the second)
R *= 33, R += 1 (add a new shell containing a single electron)

All that's left is to somehow encode which transformation has to be applied to pass from a particular atom to the next. The differences of the integer representations of two consecutive atoms are as follows:

[1 1 65 1 1 1 1 1 1 1 2369 1 1 1 1 1 1 1 78401 1 33 33 33 65 1 33 33 33 65 1 1 1 1 1 1 1 2598017 1 33 33 65 33 1 65 33 65 1 1 1 1 1 1 1 1 85745345 1 33 1089 2145 1089 1089 1089 1089 33 2145 1089 1089 1089 1089 1089 33 33 33 33 33 33 33 65 33 1 1 1 1 1 1 1 2830095041 1 33 33 2145 1089 1089 2145 1089 33 2145 1089 1089 1089 1089 1089 65 1 33 33 33 33 33 33 65 1 1 1 1 1 1 1]

The unique differences in this array are the following:

[1 33 65 1089 2145 2369 78401 2598017 85745345 2830095041]

All but the first 5 correspond to instances when a new shell is added; these can be omitted since multiplying by 33 and adding 1 yields the same result as adding the difference.

Since we have to add a new shell if and only if the current atom has exactly eight electrons in its outer shell (with the exception of He (2) ↦ Li (3), which can be encoded as add 65), we can encode those transformations as add 1 and determine the need for multiplication on the fly.

Thus, if we define

X := 0
I := 0
L := [33 1089 65 2145 1]
T := [1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 3 1 0 0 0 3 1 1 1 1 1 1 1 1 1 0 0 3 0 1 3 0 3 1 1 1 1 1 1 1 1 1 1 0 2 4 2 2 2 2 0 4 2 2 2 2 2 0 0 0 0 0 0 0 3 0 1 1 1 1 1 1 1 1 1 0 0 4 2 2 4 2 0 4 2 2 2 2 2 3 1 0 0 0 0 0 0 3 1 1 1 1 1 1 1]

the electron configuration of the Nth atom can be computed as follows:

while(X < N):
    R *= (33 ** (R % 33 == 8))
    R += L[T[X]]
    X += 1

How it works

" Push 0, the initial value of R; convert the following array into an integer by
  considering it a base 256 number, then back to the array of its digits in base 6.       ";

0"hTHøìð¼Ä¿håêÛ¾ªÔ¼"256b6b

" Replace each 5 in the resulting array by [4 4 4 4 4 4 4 4]. This yields the array T
  from the above section.                                                                 ";

5a/4a8**

" Read an integer N from STDIN and discard all but the first N elements of T.             ";

li<

" For each element Y of the remainder of T, do the following:                             ";

{
    [33:B_B*65_B*1]=\   " Define B := 33, push L, retrieve L[Y] and swap it with R.       ";

    _B%8=B\#*           " Execute R *= 33 ** (R % 33 == 8).                               ";

    +                   " Execute R += L[Y].                                              ";
}/

" Convert R into the array of its digits in base 33, remove eventual zeros (Palladium)
  and replace the resulting array with its string representation.                         ";

Bb0-`

Example run

$ base64 -d > electrons.cjam <<< MCJoVEgM+OzwErzEGL9o5erbvqrUB4YZhrwRIjI1NmI2YjVhLzRhOCoqbGk8e1szMzpCX0IqNjVfQioxXT1cX0IlOD1CXCMqK30vQmIwLWA=
$ cksum electrons.cjam
3709391992 80 electrons.cjam
$ for i in {1..118}; do LANG=en_US cjam electrons.cjam <<< $i; echo; done
[1]
[2]
[2 1]
[2 2]
[2 3]
[2 4]
[2 5]
[2 6]
[2 7]
[2 8]
[2 8 1]
[2 8 2]
[2 8 3]
[2 8 4]
[2 8 5]
[2 8 6]
[2 8 7]
[2 8 8]
[2 8 8 1]
[2 8 8 2]
[2 8 9 2]
[2 8 10 2]
[2 8 11 2]
[2 8 13 1]
[2 8 13 2]
[2 8 14 2]
[2 8 15 2]
[2 8 16 2]
[2 8 18 1]
[2 8 18 2]
[2 8 18 3]
[2 8 18 4]
[2 8 18 5]
[2 8 18 6]
[2 8 18 7]
[2 8 18 8]
[2 8 18 8 1]
[2 8 18 8 2]
[2 8 18 9 2]
[2 8 18 10 2]
[2 8 18 12 1]
[2 8 18 13 1]
[2 8 18 13 2]
[2 8 18 15 1]
[2 8 18 16 1]
[2 8 18 18]
[2 8 18 18 1]
[2 8 18 18 2]
[2 8 18 18 3]
[2 8 18 18 4]
[2 8 18 18 5]
[2 8 18 18 6]
[2 8 18 18 7]
[2 8 18 18 8]
[2 8 18 18 8 1]
[2 8 18 18 8 2]
[2 8 18 18 9 2]
[2 8 18 19 9 2]
[2 8 18 21 8 2]
[2 8 18 22 8 2]
[2 8 18 23 8 2]
[2 8 18 24 8 2]
[2 8 18 25 8 2]
[2 8 18 25 9 2]
[2 8 18 27 8 2]
[2 8 18 28 8 2]
[2 8 18 29 8 2]
[2 8 18 30 8 2]
[2 8 18 31 8 2]
[2 8 18 32 8 2]
[2 8 18 32 9 2]
[2 8 18 32 10 2]
[2 8 18 32 11 2]
[2 8 18 32 12 2]
[2 8 18 32 13 2]
[2 8 18 32 14 2]
[2 8 18 32 15 2]
[2 8 18 32 17 1]
[2 8 18 32 18 1]
[2 8 18 32 18 2]
[2 8 18 32 18 3]
[2 8 18 32 18 4]
[2 8 18 32 18 5]
[2 8 18 32 18 6]
[2 8 18 32 18 7]
[2 8 18 32 18 8]
[2 8 18 32 18 8 1]
[2 8 18 32 18 8 2]
[2 8 18 32 18 9 2]
[2 8 18 32 18 10 2]
[2 8 18 32 20 9 2]
[2 8 18 32 21 9 2]
[2 8 18 32 22 9 2]
[2 8 18 32 24 8 2]
[2 8 18 32 25 8 2]
[2 8 18 32 25 9 2]
[2 8 18 32 27 8 2]
[2 8 18 32 28 8 2]
[2 8 18 32 29 8 2]
[2 8 18 32 30 8 2]
[2 8 18 32 31 8 2]
[2 8 18 32 32 8 2]
[2 8 18 32 32 10 1]
[2 8 18 32 32 10 2]
[2 8 18 32 32 11 2]
[2 8 18 32 32 12 2]
[2 8 18 32 32 13 2]
[2 8 18 32 32 14 2]
[2 8 18 32 32 15 2]
[2 8 18 32 32 16 2]
[2 8 18 32 32 18 1]
[2 8 18 32 32 18 2]
[2 8 18 32 32 18 3]
[2 8 18 32 32 18 4]
[2 8 18 32 32 18 5]
[2 8 18 32 32 18 6]
[2 8 18 32 32 18 7]
[2 8 18 32 32 18 8]


Python 3, 68 62 48 bytes
-6 bytes thanks to xnor!
-14 bytes thanks to Jitse!

lambda n:' 11 'in f' {n:b} {n} '.replace('0','')

Try it online!


I uppercase the source code, you reverse the input!

05AB1E, 1 byte
r

Try it online lowercase or uppercase!
Finally a question which I (a dumb brain) can answer! Thanks for this easy, yet fun challenge! (I do feel great, even though it requires little effort to make an answer in 05AB1E.)
Wait, how?
r # reverses the stack. (Which literally does not do anything since only the
  # implicit input is in the stack)
R # actually reverses the top string of the stack (Which is the implicit input).
  # at the end, the input is automatically printed.


Jelly, 3 bytes

SĊṆ

Input is in form of complex numbers, which will be real or purely imaginary.

Try it online!

How it works

SĊṆ  Main link. Argument: A (array of directions)

S    Take the sum of A.
 Ċ   Get the imaginary part of the sum.
  Ṇ  Take the logical NOT of the imaginary part.


Python

I've figured out all the secret phrases, but I won't post them here.  Run the code if you care.

The code works by picking a space character, enumerating all possible substitutions for each word, then searching for compatible substitutions.  It also allows for some out-of-lexicon words to deal with misspellings in the cleartext :)

I used a large lexicon (~500K words) from http://wordlist.sourceforge.net/.

import sys,re

# get input
message = sys.argv[1]

# read in lexicon of words
# download scowl version 7.1
# mk-list english 95 > wordlist
lexicon = set()
roman_only = re.compile('^[A-Z]*$')
for word in open('wordlist').read().upper().split():
  word=word.replace("'",'')
  if roman_only.match(word): lexicon.add(word)

histogram={}
for c in message: histogram[c]=0
for c in message: histogram[c]+=1
frequency_order = map(lambda x:x[1], sorted([(f,c) for c,f in histogram.items()])[::-1])

# returns true if the two maps are compatible.
# they are compatible if the mappings agree wherever they are defined,
# and no two different args map to the same value.
def mergeable_maps(map1, map2):
  agreements = 0
  for c in map1:
    if c in map2:
      if map1[c] != map2[c]: return False
      agreements += 1
  return len(set(map1.values() + map2.values())) == len(map1) + len(map2) - agreements

def merge_maps(map1, map2):
  m = {}
  for (c,d) in map1.items(): m[c]=d
  for (c,d) in map2.items(): m[c]=d
  return m

def search(map, word_maps, outside_lexicon_allowance, words_outside_lexicon):
  cleartext = ''.join(map[x] if x in map else '?' for x in message)
  #print 'trying', cleartext

  # pick a word to try next
  best_word = None
  best_score = 1e9
  for (word,subs) in word_maps.items():
    if word in words_outside_lexicon: continue
    compatible_subs=0
    for sub in subs:
      if mergeable_maps(map, sub): compatible_subs += 1
    unassigned_chars = 0
    for c in word:
      if c not in map: unassigned_chars += 1  #TODO: duplicates?
    if compatible_subs == 0: score = 0
    elif unassigned_chars == 0: score = 1e9
    else: score = 1.0 * compatible_subs / unassigned_chars   # TODO: tweak?
    if score < best_score:
      best_score = score
      best_word = word
  if not best_word:  # no words with unset characters, except possibly the outside lexicon ones
    print cleartext,[''.join(map[x] if x in map else '?' for x in word) for word in words_outside_lexicon]
    return True

  # use all compatible maps for the chosen word
  r = False
  for sub in word_maps[best_word]:
    if not mergeable_maps(map, sub): continue
    r |= search(merge_maps(map, sub), word_maps, outside_lexicon_allowance, words_outside_lexicon)

  # maybe this word is outside our lexicon
  if outside_lexicon_allowance > 0:
    r |= search(map, word_maps, outside_lexicon_allowance - 1, words_outside_lexicon + [best_word])
  return r

for outside_lexicon_allowance in xrange(3):
  # assign the space character first
  for space in frequency_order:
    words = [w for w in message.split(space) if w != '']
    if reduce(lambda x,y:x|y, [len(w)>20 for w in words]): continue  # obviously bad spaces

    # find all valid substitution maps for each word
    word_maps={}
    for word in words:
      n = len(word)
      maps = []
      for c in lexicon:
        if len(c) != n: continue
        m = {}
        ok = 1
        for i in xrange(n):
          if word[i] in m:                      # repeat letter
            if m[word[i]] != c[i]: ok=0; break  # repeat letters map to same thing
          elif c[i] in m.values(): ok=0; break  # different letters map to different things
          else: m[word[i]]=c[i]
        if ok: maps.append(m);
      word_maps[word]=maps

    # look for a solution
    if search({space:' '}, word_maps, outside_lexicon_allowance, []): sys.exit(0)

print 'I give up.'


Generate all square sub-matrices of a given size

05AB1E, 8 bytes

2FεŒsù}ø

Try it online!

Explanation

2F            # 2 times do:
  ε    }      # apply to each element in the input matrix (initially rows)
   Œsù        # get a list of sublists of size input_2
        ø     # transpose (handling columns on the second pass of the loop)


Canvas, 5 4 bytes
║Ｑ↷↷

First Canvas answer, so let's start with an easy one. :)
-1 byte thanks to @dzaima.
The slashes are automatically converted when mirroring or rotating in Canvas.
Could have been 1 byte ╬ (Try it online), but unfortunately it also transforms the dots . to single quotes ' when mirroring horizontally.
Try it online.
Explanation:

         # (Take the multi-line input implicitly as canvas object)
║        # Palindromize the canvas object (without overlap)
 Ｑ      # Output it with a trailing newline (without popping)
  ↷↷    # Rotated the canvas object that's still on the stack by 90 degrees twice
         # (and output it implicitly as well at the end)


APL (Dyalog), 175 bytes

1↓' +'⎕R' '⊢'[AEIOU][^AEIOU]+ '⎕R{m/⍨1,3×2≠/m←⍵.Match}'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1'⊢'$| |^'⎕R'  '⊢1(819⌶)⍞

Try it online!

⍞ prompt for character input

1(819⌶) convert to uppercase (819 ≈ Big)

⊢ pass the result further (serves to separate the strings and the 1)

'$| |^'⎕R'  ' Replace:
 the end, any space, and the beginning
 → two spaces

⊢ pass the result further (serves to separate two groups of strings)

'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1' Replace:
 any number of identical vowels and any number of non-vowels and a space
 → the vowel thrice and the unmodified consonants
 a space and a vowel
 → themselves
 a space and a consonant cluster
 → themselves
 a run of identical consonants
 → three of those vowels

'[AEIOU][^AEIOU]+ '⎕R{…} Replace:
 a run of non-vowels and a space
 → the result of the following anonymous function with the namespace ⍵ as argument:
  ⍵.Match the text that was found
  m← assign that to m
  2≠/ pair-wise different-from
  3× multiply by three
  1, prepend one
  m/⍨ use that to replicate m

⊢ pass the result further (serves to separate two strings)

' +'⎕R' ' Replace:
 one or more spaces
 → with a single space

1↓ drop the initial letter (a space)


Charcoal, 9 bytes

↘✂β⁰Ｎ↓✂βη

Try it online!

How it works

↘✂β⁰Ｎ↓✂βη
 ✂β⁰Ｎ         the alphabet from position 0 to the input
↘               print diagonally, down and to the right
        ✂βη    the alphabet starting from the position of the input
       ↓        print downwards

This solution no longer works in the current version of Charcoal (most likely due to a bug fix), but the issue is resolved for 10 bytes with ↘✂β⁰Ｎ↓✂βＩθ.


Find the largest prime under a number... but only for the test cases

C
Results will be correct for the test cases, all others will be wrong for one or more reasons. The key is using the specifier %g which will round enough for the test cases but show the others as real numbers. Above inputs of 614, the results are all less than zero. Assuming inputs are in the integer domain!
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    // Convert input
    double x = atof(argv[1]);

    // Cubic prime determination function
    double y = -1.386269645E-5 * x * x * x + 7.572051723E-3 * x * x + 5.774239804E-1 * x + 1.199953896;

    // Print output, use %g because it guarantees the shortest output
    printf("First prime less than or equal to %g is %g - happy day.\n", x, y);

    // Done!
    return 0;
}

Sample output:
$ ./fake 2
First prime less than or equal to 2 is 2.38498 - happy day.
$ ./fake 3
First prime less than or equal to 3 is 3 - happy day.
$ ./fake 4
First prime less than or equal to 4 is 3.62992 - happy day.
$ ./fake 5
First prime less than or equal to 5 is 4.27464 - happy day.
$ ./fake 6
First prime less than or equal to 6 is 4.9341 - happy day.
$ ./fake 7
First prime less than or equal to 7 is 5.6082 - happy day.
$ ./fake 8
First prime less than or equal to 8 is 6.29686 - happy day.
$ ./fake 9
First prime less than or equal to 9 is 7 - happy day.
$ ./fake 28
First prime less than or equal to 28 is 23 - happy day.
$ ./fake 486
First prime less than or equal to 486 is 479 - happy day.


Brachylog v2, 19 bytes

;Az{\-ᵐ~√ᵐ+}ᵐ≤ᵛ√;A≜

Try it online!

This program was easy to write – Brachylog's almost perfect for this sort of problem – but hard to golf. It wouldn't surprise me if there was a byte saving somewhere here, as few things I did seemed to have any effect (and it contains nested map instructions, normally a sign that you should be using member/findall, but I can't see a way to do it).

This is a function submission. Input is from the left argument to the function in the format [[x,y],[x,y],…], output from the right argument in the form [r,[[x,y]]]. (If you want to try negative numbers in the input, note that Brachylog uses _ for the minus sign, not -. This is confusing because the function → full program wrapper that Brachylog ships with, requested using the command-line argument Z, will present negative numbers in the output with a regular minus sign.)

Explanation

;Az{\-ᵐ~√ᵐ+}ᵐ≤ᵛ√;A≜
;A                   Append something
  z                    to every element of the input
   {       }ᵐ        such that for each resulting element:
     -                 Subtracting
    \ ᵐ                  corresponding elements {of the (input, appended) element}
       ~√              and un-squarerooting
         ᵐ               {the result of} each {subtraction}
          +            and summing {the resulting square numbers}
             ≤       {lets us find} a number at least as large as
              ᵛ        every element {of the list of sums}
               √     which can be square-rooted;
                ;A   append the same list as initially to it.
                  ≜  Find the first integer solution to the above, lexicographically.

This is interesting in that we're asking Brachylog to find a value of certain properties (in this case, the radius of a disk centred at point A that fits all the input points), but hardly placing any requirements on it (all we require is that the radius is a number). However, Brachylog will internally calculate the radius in question symbolically rather than trying to use concrete numbers, so when the final ≜ is reached, it accomplishes two things at once: first, it ensures that only integers are used for the coordinates of A and for the radius (forcing the squared radius to be a square number, and explaining the use of ≤ᵛ to find a "maximum or greater"); second, it finds the smallest possible viable radius (as the radius comes first in the output).

One thing that isn't specified in the program at all is that all the points are measured against the same centre of a disk; as written, there are no constraints that we don't use a different centre for each point. However, the tiebreak order (which in this case is set by the third ᵐ, and which as a structure constraint will be evaluated before the value constraint implied by ≜) wants A to be as short as possible (i.e. a single element, so we use the same centre each time; it tries a zero-length A first but that obviously doesn't work, so it tries a singleton list next). As a result, we end up getting a useful constraint (that we only have one disk) "for free".

This solution happens to generalise to any number of dimensions, with no changes to the source code; there are no assumptions here that things are two-dimensional. So if you happen to need the smallest integer sphere, you can have that too.


Last Nonzero Digits of a Factorial in Base

Mathematica, 57 48 bytes
Saved 9 bytes thanks to @2012rcampion .
IntegerString[#!/#2^#!~IntegerExponent~#2,##2]&


How to determine if a number is odd or even without mod -or- bitwise operations?

Python

print('even' if (-1)**n==1 else 'odd')


Python 2, 74 64 56 55 53 bytes

def f(x):a=ord(max(x))-54;a+=7*(a<8);print int(x,a),a

Call the function (i.e. f("HELLOWORLD")) and outputs to stdout (809608041709942 33)

This is case-sensitive, requiring upper case letters, and crashes for invalid input (e.g. "$^$%!(&£%)())

This code gets the max letter in the string (z>x>y>...>b>a>9>8>...>2>1>0) and gets the largest base needed to represent it.

Change the 54 into a 76 to make it work for lowercase (but no longer upper case).


Python 2, 192 162 bytes

I have an argument that this produces the maximum set of cards for every scenario and it does handle the 3 test cases.

from itertools import*
def m(a,s):
    C=["".join(x)for x in combinations(a,s)]
    while len(C):
        print C[0]
        C=list(set(A for A in C if len(set(A)&set(C[0]))==1<s))

Try it online!

Algorithm

Given an alphabet a and a card size s, take all combinations of s elements in a and call it C,  then:

Take the first element of C, call it C0
Save C0
Remove all elements fromC that have a union with C0 not equal to 1
Repeat with second element of C
Continue until C is empty

Then print the saved elements.

Argument

Some non-empty subset of C is our maximal solution, K. Since it contains at least one element and any two elements are indistinguishable, choose an arbitrary element, C0, of C to be in K. For any element e in the K, the cardinality of e union x is 1 for x != e in K; so eliminate all elements in C whose union with C0 does not have cardinallity 1. By the same reasoning, choose a new arbitrary element in C, add it to K, and reduce C. Eventually C is the empty set and K will be the maximal solution because at no point did we choose an element that was distinguishable from any other element.

Test Cases

These test cases were written before I realized that the printing was a requirement.

a=["a","b","c"]
b=2
c=3
d=m(a,b)
print d,len(d)==c
>> ['bc', 'ab', 'ac'] True

a=["a","b","c","d","e","f","g"]
b=3
c=7
d=m(a,b)
print d,len(d)==c
>> ['aef', 'abc', 'bde', 'ceg', 'adg', 'cdf', 'bfg'] True

a=["a","b","c","d","e"]
b=4
c=1
d=m(a,b)
print d,len(d)==c
>> ['abcd'] True

Update

+9 [16-12-07] Fit the print requirement
-11 [16-12-07] Golfed out my R variable
-30 [16-12-09] Golfed out my K variable, Thanks to @Leo!


Wolfram Language (Mathematica), 16 bytes

Ha! Of course it is biased towards Mathematica!

Nest[Range,#,#]&

Try it online!


Pyth, 20 bytes

j\-msm.HO16*4hdj83 3

Demonstration.

Encodes [1, 0, 0, 0, 2] as 83 in base 3, then adds one and multiplies by four to get the length of each segment. Then makes hex digits and joins on hyphens.


Haskell, 23 bytes

EDIT:

-1 byte: @xnor got rid of parentheses with a $.

An anonymous function taking an Int and returning a Char.

Output is '1' for triangular numbers and '0' for others.

(!!)$show.(10^)=<<[0..]

Try it online!

Use as ((!!)$show.(10^)=<<[0..]) 998991.
Generates the numbers 1, 10, 100, 1000, ..., converts those to strings, and concatenates them. Then indexes into the resulting infinite string

"1101001000100001000001000000...


Laver table computations and an algorithm that is not known to terminate in ZFC


JavaScript (ES6), 413 ... 343 342 bytes

Saved 5 bytes by tweaking the loop indices, as suggested by @KevinCruijssen

Takes input as 2 strings in currying syntax. Returns an array of 3 strings.

b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]}

Test cases

let f =

b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]}

console.log(f('ABCDEF')('AFBECD').join`\n`);
console.log(f('This_is_an       _example_text')('This_is_a_test_as_example').join`\n`);
console.log(f('AaAaABBbBBcCcCc')('abcABCabcABC').join`\n`);
console.log(f("intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}")("intf(){intr=(int)(Math.random()*10);returnr>0?r%2:2;}").join`\n`);
console.log(f('ABCDEF')('XABCDF').join`\n`);

Less golfed

b => a => {
  m = []; x = a.length; y = b.length;

  // initialize the leftmost column and the topmost row
  for(i = j = 0, c = d = ''; i <= y; c += R = 'R')
    m[i] = [[c, i++]];
  for(; j++ < x;)
    m[i = 0][j] = [d += A = 'A', j];

  // walk through the Levenshtein matrix
  for(; i < y; i++)
    for(j = 0; j < x;)
      [C] = m[                                // C = current string, once updated
        [X, S] = m[i][j],                     // substitution
        [Y, I] = m[i + 1][j],                 // insertion
        [Z, D] = m[i][++j],                   // deletion
        Q = [Z + R, D + 1],                   // precomputed update for deletion
        i + 1
      ][j] =
        b[i] == a[j - 1] ?
          [X + ' ', S]                        // unchanged character
        :
          S < I ?
            D < S ? Q : [X + 'M', S + 1]      // deletion or substitution
          :
            D < I ? Q : [Y + A, I + 1];       // deletion or insertion

  return [
    // g = helper function to format the output strings by inserting spaces
    (g = s => C.replace(/./g, c => c == s ? ' ' : b[i++], i = 0))(A),
    g(R, b = a),

    // final modification string, picked from the last visited cell
    C
  ]
}

Example

Below is the initial matrix for b = "foo" and a = "ok":

//                     'o'           'k'
[ [ [ '',    0 ], [ 'A',   1 ], [ 'AA',  2 ] ],
  [ [ 'R',   1 ],  (undefined),  (undefined) ],  // 'f'
  [ [ 'RR',  2 ],  (undefined),  (undefined) ],  // 'o'
  [ [ 'RRR', 3 ],  (undefined),  (undefined) ] ] // 'o'

and here is the final matrix after all iterations:

//                     'o'           'k'
[ [ [ '',    0 ], [ 'A',   1 ], [ 'AA',  2 ] ],
  [ [ 'R',   1 ], [ 'M',   1 ], [ 'MA',  2 ] ],  // 'f'
  [ [ 'RR',  2 ], [ 'R ',  1 ], [ 'R A', 2 ] ],  // 'o'
  [ [ 'RRR', 3 ], [ 'RR ', 2 ], [ 'R M', 2 ] ] ] // 'o'

The final modification string along with the Levenshtein distance are stored in the bottom-right cell.


Pyth, 103 89 84 chars

Saved 18 bytes with string compression, thanks to @Dennis and @FryAmTheEggman
Saved another byte thanks to @isaacg

Warning: there are many unprintables in the code; use the links below to try it.

VQjd%Q>cs[J."@y)òÎ5O¹c×Ú"."@yæ\J}ÇZH66¥ÓÀD¸¶=ðÉ §J%ÔþÖúÅ="J"MOE!")\@N

Try it online | Test suite

Could probably be golfed. Suggestions welcome!

How it works

VQjd%Q>cs[J."..."."..."J"MOE!")\@N    Implicit: Q = eval(input)
VQ                                    For each item N in range 0...int(Q):
         [                    )        Create an array out of the following:
          J."..."                       Set J to this string, decompressed. ("Eeny@meeny@miny@")
                 ."..."                 This string, decompressed. ("moe@Catch@...let@him@go@")
                       J                J.
                        "MOE!"          "MOE!".
        s                              Join the array with the empty string.
       c                       \@      Split the result on "@".
      >                          N     Cut off the first N items.
    %Q                                 Take every Qth item.
  jd                                   Join with spaces.


Turn 2D boolean array into (rectilinear) polygons

Perl, 345 311 265 chars

s!.!$i{$x++}=$&eq'#'!ge,$x=$r+=64for<>;sub a{$d+=@_||3;$d%=4;$y=$x%64;$z=$x>>6;$c.=", ($y,$z)";}for$x(keys%i){if($c=!$v{$x}&$i{$x}&!$i{$x-1}){$i{($x+=(1,64)[$d^3])-(64,65,1)[$d]}?$i{$x-(65,1,0,64)[$d]}?a 1:($x-=(64,1)[$d]):a while$d||!$v{$x}++;print substr$c.$/,3}}

Limitations

Assumes that the input is no wider than 64 characters (but its height is in principle unbounded). This can be extended to 512 or 8192 or any other power of two by changing the relevant constants, making the code only slightly longer.

Slightly more readable version

Some credit goes to mob because the first line is my re-use of his idea in lasers. The rest is entirely my work.

# Read “%i”nput (this line is essentially mob’s idea, see above)
s!.! $i{$x++} = $& eq '#' !ge, $x = $r += 64 for <>;

# Subroutine to add a vertex to the current polygon and change the current “$d”irection
sub a
{
    $d += @_ || 3;
    $d %= 4;
    $y = $x % 64;
    $z = $x >> 6;
    $c .= ", ($y,$z)";
}

for $x (keys %i)
{
    # Go to the next “upward-pointing” edge that we haven’t already “%v”isited.
    if ($c = !$v{$x} & $i{$x} & !$i{$x-1})
    {
        # We’re going in the “$d”irection of 0=up, 1=left, 2=down, 3=right
        $i{($x += (1,64)[$d^3]) - (64,65,1)[$d]}
        ?  $i{$x - (65,1,0,64)[$d]}
           ?  a 1               # take a 90° turn to the left
           : ($x -= (64,1)[$d]) # move straight ahead
        : a                     # take a 90° turn to the right

        # Only stop if the current “$d”irection is “up” and we encounter a “%v”isited edge
        # (which necessarily is the one we started from)
        while $d || !$v{$x}++;

        # Remove “1, ” and output this polygon
        print substr $c.$/, 3
    }
}

Edits

(345 → 312) Realised there’s no need to update $x when taking a turn because the next iteration will already do it
(312 → 311) Change 1=down,2=left to 1=left,2=down and update $d via XOR instead of directly
(311 → 265) Remove repetition of the innermost expression and use arrays to parametrise it


CJam, 34 31 bytes

qN/W%zSf-La%{_{s'*&}#_)@@=}3*;\

This requires the input to be padded to a rectangle with spaces.

Try it online! Alternatively, run all test cases.

Explanation

qN/      e# Read input and split into lines.
W%z      e# Rotate 90° counter-clockwise.
Sf-      e# Remove all spaces from the rows.
La%      e# Split into buildings. We've now got a 3D array of rooms, where the first
         e# dimension is the building, the second the room number and the third is the
         e# the floor number.
{        e# Run this block three times. At each stage it will find the index of the "*"
         e# along the current dimension and leave the element at that index on the stack
         e# for the next round...
  _      e#   Duplicate the current array.
  {      e#   Find the index of the first element where this block yields something
         e#   truthy...
    s    e#     Flatten into a single string.
    '*&  e#     Set intersection with "*".
  }#
  _)     e#   Duplicate the index and increment it, because the results should be 1-based.
  @@=    e#   Pull up the array and the other copy of the index and select the
         e#   corresponding element.
}3*
;\       e# We've now got the building, room and floor index on the stack, as well as the
         e# "*" character itself. We discard the character and swap the room and the floor
         e# floor number. When the three indices are printed back-to-back at the end of
         e# the program, that will yield the desired result.


PHP – 355 bytes
The byte count doesn't include '<image-url>'.
<?php
m('<image-url>');function m($f){$i=imagecreatefrompng($f);$r=f($i,17);$c=f($i,9);echo($c-$r).' '.$r."\n";}function f($i,$k){$w=imagesx($i);$h=imagesy($i);$r=0;for($y=0;$y<$h;$y++)for($x=0;$x<$w;$x++)if(!imagecolorat($i,$x,$y))$r+=g($i,$x,$y,$w,$k);return$r;}function g($i,&$x,$y,$w,$k){$l=$x;while(!imagecolorat($i,$x,$y)&&$x<$w)$x++;return($x-$l>$k)?1/2:0;}

In the two test cases, the URLs I used are http://i.stack.imgur.com/qnIFk.png and http://i.stack.imgur.com/HV9k3.png.
Counts horizontal lines and divides by two to get the number of shapes. Relies on the observation that circles have shorter horizontal segments and rectangles have longer horizontal segments.
Admitted hack, not guaranteed to work for anything other than the test cases!
I tried rotating the images by ± 45° and detecting for horizontal lines. This would be equivalent to checking for diagonal lines and would pick up the circles better, but I couldn't find an interpolation algorithm which left clean enough edges to work with. For example, they might smudge a line into two rows of pixels and mess up the count.


Python 3, 90 - 10 = 80

def S(N,x,n=[],i=1):
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

(Mega thanks to @xnor for tips, especially the restructuring of the for loop into a while)

A simple recursive attempt. It starts off with the target number and continuously subtracts square roots until it hits 0 or lower. The function S can be called like S(2,3.414213562373095) (the second argument is assumed to be positive).

The program doesn't just print out all solutions, it prints out all permutations of solutions (a little extraneous, I know). Here's the output for the last case: Pastebin.

A slight tweak gives a 98 - 10 = 88 solution which doesn't print permutations, making it more efficient:

def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

And just for fun, this 99 - 10 = 89 one is about as efficient as it gets (unlike the others, it doesn't blow the stack on S(1,1000):

def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N:print(*n)
 while(.1+x*x>i)*N:S(N-1,x-i**.5,n+[i]);i+=1

Note that, although we have a mutable default argument, this never causes a problem if we rerun the function since n+[i] creates a new list.

Proof of correctness

In order to end up in an infinite loop, we must hit some point where x < 0 and 0.1 + x2 > 1. This is satisfied by x < -0.948....

But note that we start from positive x and x is always decreasing, so in order to hit x < -0.948... we must have had x' - i0.5 < -0.948... for some x' > -0.948... before x and positive integer i. For the while loop to run, we must also have had 0.1 + x'2 > i.

Rearranging we get x'2 + 1.897x' + 0.948 < i < 0.1 + x'2, the outer parts implying that x' < -0.447. But if -0.948 < x' < -0.447, then no positive integer i can fit the gap in the above inequality.

Hence we'll never end up in an infinite loop.


Befunge-98, ><>, Fission, Wumpus, Cardinal, Gol><> and Beeswax, Score: \$(100/103)*2^6 = 62.136\$
"[0#34o+]l2:)&o@.0*74#!,!?:o#_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

Try it online!
Verification!
When given an input of 0, this program produces itself. When given a different number, it produces the quines in the format
"[0#34o+]l2:)&o@.0*74#!,!?:o1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 #_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

Where the 1s are the input number. Since there are 26 copies of the 1, this makes each quine distinct at least \$bytes/4\$ Levenshtein distance. The quines are entirely interchangeable as no program actually cares about the number part. I might see if I can add some more 2D languages to this (I'm thinking Cardinal Gol><> next) Don't have one in mind right now.


Generate a golfed program to evaluate an arithmetic expression

Lua, 202 + 166 = 368

File "generate_code.lua"

F=...
C='function G(v)io.write(v.." = ")_G[v]=io.read"*n"end 'V={}for v in F:gmatch'%l'do V[v]=0 end
for v in pairs(V)do C=C..'G"'..v..'"'end
print(C..'F="'..F..'"print(F.." = "..load("return "..F)())')

Usage:

$ lua generate_code.lua "1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000"

Code generated (order of variables is not specified):

function G(v)io.write(v.." = ")_G[v]=io.read"*n"end G"g"G"e"G"d"G"b"G"a"G"h"F="1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000"print(F.." = "..load("return "..F)())

Generated code in action:

g = 4
e = 3
d = 2
b = 1
a = 6.5
h = 4.3
1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 = 29787.941860465


Wolfram Language (Mathematica), 2 bytes

Tr finds the trace of the matrix or tensor list

Tr

Try it online!


bash, 43 bytes

factor $1|awk '{print $2-$3&&$3-$4&&NF==4}'

Try it online!

Input via command line argument, outputs 0 or 1 to stdout.

Fairly self-explanatory; parses the output of factor to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors).


Highlight the Bounding Box, Part II: Hexagonal Grid

Pyth, 82 71 bytes

L,hbebMqH@S+GH1KhMyJs.e,Lkfq\#@bTUb.zA,ySm-FdJySsMJj.es.eXW&&gKkgG-kYgH+kYZ\.\#b.z
MqH@S[hGHeG)1j.es.eXW&&ghMJs.e,Lkfq\#@bTUb.zkgSm-FdJ-kYgSsMJ+kYZ\.\#b.z

Try it online!

Explanation

Let A be the point with the lowest y-coordinate and B the point with the highest y-coordinate.
Let C be the point with the lowest (x-value minus y-value) and D the point with the highest.
Let E be the point with the lowest (x-value plus y-value) and F the point with the highest.

Then it is equivalent to finding the coordinates which the y-coordinate is between A and B, the x-value minus y-value is between C and D, and the x-value plus y-value is between E and F.


J - 17 char

g=:(f=:_ q:>:)inv

We implement the prime exponent idea with this bijection—that's what the _ q: is doing, getting a list of the exponents of the primes of a number—except we also increment the input number by one before doing so, with >:, so that we don't forget 0, who doesn't have its own prime factorization.

For the definition of g, it's exactly what it looks like: instead of writing it ourselves, we just tell J to take the inverse of f. Arguably this is cheating, or just not interesting, but I think that the ability to do this is what makes J such an interesting language: J can often figure things out for you, allowing you to focus on expressing your solution instead of implementing it.

   i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   f i. 20  NB. J pads with zeroes on right
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
2 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
1 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
3 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0
1 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0
2 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0
1 0 0 1 0 0 0 0
0 1 1 0 0 0 0 0
4 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
1 2 0 0 0 0 0 0
0 0 0 0 0 0 0 1
2 0 1 0 0 0 0 0
   g f i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Proving that this is a bijection is straightforward: the injectivity of this f is a well known fact and, if you assume that J's automagical inverse is correct (which it is), then this is trivial.

If you don't want to take it on faith that J knows how to take the inverse of f, we can inspect its automatic inverse for _&q::

   _&q: b. _1
(p:@i.@# */ .^ ])"1 :.(_&q:)

and then check the definition:

(p:@i.@# */ .^ ])"1 :.(_&q:)  NB. the alleged inverse of _&q:
                    :.(_&q:)  NB. defining _&q:inv inv to be _&q:
(               )"1           NB. operate on rows of the argument
       #                      NB. length of argument
    i.@                       NB. nonnegative integers less than
 p:@                          NB. n-th prime for each integer n
               ]              NB. the argument again
            .^                NB. pointwise exponentiation
         */                   NB. product

and then confirm that J's inverse of f gives the decrement of the result of this:

   >: b. _1  NB. inverse of increment is decrement
<:
   f b. _1   NB. ([: f g) is one way of writing f composed with g
[: <: (p:@i.@# */ .^ ])"1 :.(_&q:)


Print three columns vertically separated by space(s)

Husk, 24 17 bytes

TmoTT' §CȯmLTC3Ow

Try it online!

Explanation

This was a surprisingly tricky challenge, as Husk currently lacks a builtin for breaking a list into a given number of parts.

TmoTT' §CȯmLTC3Ow  Implicit input, say s="bbb a cc ddd e"
                w  Split at spaces: x=["bbb","a","cc","ddd","e"]
             C3    Cut into slices of length 3: [["bbb","a","cc"],["ddd","e"]]
            T      Transpose: [["bbb","ddd"],["a","e"],["cc"]]
         ȯmL       Map length: [2,2,1]
                   These are the correct lengths of the columns.
       §C      O   Sort x and split into these lengths: [["a","bbb"],["cc","ddd"],["e"]]
                   These are the columns of the correct output, without padding.
 mo                For each column,
    T'             transpose and pad with spaces: [["ab"," b"," b"],["cd","cd"," d"],["e"]]
   T               then transpose back: [["a  ","bbb"],["cc ","ddd"],["e"]]
T                  Transpose the whole list: [["a  ","cc ","e"],["bbb","ddd"]]
                   Implicitly join each row by spaces,
                   join the resulting strings by newlines and print.


Bash, 23 bytes

Canonical 23-character answer:

tr A-Za-z N-ZA-Mn-za-m


JavaScript (ES6), 98

Note while I found it myself, it's annoyingly similar to @Neil's, just with the additional logic to split the whole input string in sentences.

s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

Test

f=s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

console.log=x=>O.textContent+=x+'\n'

;[['Hello Hello, World!','Hello, World!']
,['Code Code! Golf Code','Code! Golf Code']
,['Hello  hello   World','Hello   World']
,['Programming Golf Programming!','Programming Golf!']]
.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log((r==k?'OK ':'KO ')+i+' -> '+r)
})


What's this constructed number's starter?

05AB1E, 7 5 4 bytes

>9*н

Try it online!

>            # input + 1
 9*          # * 9
   н         # take the first digit

The \$(n-1)^{th}\$ term of the sequence starting with \$a\$ is \$\sum _{i=1}^{n-1} a \times i \times 10^{i-1} = a \times \frac{(10^n - 1) / 9 - n}{9}\$. Multiply that by \$9\$ and add \$a\times n\$, and you get \$a \times \frac{10^n - 1}{9}\$, aka the digit \$a\$ repeated \$n\$ times. Turns out adding \$9\$ instead of \$a\times n\$ works for \$n=1\$, and for bigger \$n\$ the linear difference is negligible next to the exponential growth.


><>, 40 38 bytes

1v!rnr~<oa
?\i:0(?^3%\+$
{/?:-{:}-1/1:

Try it online!

An appropriate language. For reference ><> itself yields 2,1,2,1.

How it Works:

1v   Initialise the stack as 1 and enter loop
 \i:0(?^  If we're out of input, go to the first line
        3%\ Otherwise mod the input by 3, yielding 0 for < and 2 for >
        -1/Subtract 1 to get -1 and 1 respectively
    -{:}   Copy the previous number and subtract the above from it

 /?:    If the number is not 0, repeat the loop

?\        \+$  Otherwise:
                Increment each number until we reach the original 0
{/        /1:   And enter the first loop again

      ~<    When we're out of input, pop the extra -1 from EOF
   rnr      Output the first number
1v!         Push a 1
        oa  Print a newline and repeat, popping the extra 1 each time


TCL 220

proc a b {
if {"$b"=="bb"} {
rename puts w
rename p puts
set b \;exit
}
puts [set q [open [incr ::i] w]] "proc a b \{[info body a]\};a b"
catch {rename puts p}
proc puts {n m} "p \$n \${m}$b"
close $q
source $::i
};a b

The code generates files 1, 2, 3 and 4. The variation is only present in 2, the others are equivalent to the original.


Printing a "Hello World" one-liner in bourne shell without directly using white space char

One which works in dash, so I suppose it is sh compatible;

IFS=@;command=echo@Hello@World;$command


Retina, 9 bytes

m`^\d
$*

Try it online! Note: Trailing space on last line.


Haskell, 42 + 31 = 73 bytes

To base 94: 42 bytes

(l!!)
l="":tail[s++[c]|s<-l,c<-['!'..'~']]

Try it online!

Instead of using modular arithmetic, we generate the list l of all strings in the desired order and index into it.

The recursive definition of l is similar to this one for generating all strings, but modified to output strings in the desired order by appending the new character, and with a tail to prevent the analogue of leading zeroes.

From base 94: 31 bytes

foldl(\n->(94*n-33+).fromEnum)0

Try it online!

Iterates over the characters c of the string, updating the current value n to 94*n-33+fromEnum c.


Haskell, 125 bytes

t=tail.p
p=g.break(=='[')
g(a,(_:t))=(:)&(map(a++).z)$t#[]
z[]=[""];z x=x
(']':u)#a=u:a
s#a=(#)&(a++)$p s
(g&f)(x:y)=g x$f y

The function is t (for traversal):

λ: t "cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"
["catsup","cats","cat","catcher","catches","catamaran","catacomb","catapult","catapulting"]
λ: t "[donut[][]cruller[]]"
["donut","","cruller"]
λ: t "[[[[[]]]]]"
[""]


Jelly, 5 bytes

Ġị§§M

Try it online!

1-based indices of sorted unique elements of input.


Pyth, 22 19

hfq_TTsm,+z_d+_dzyz

Try it online.

Explanation

The two-way palindromic closure is either of the form AX or XA, where X is the input string and A is a substring of X. I actually has to be a contiguous substring of X, a prefix for the one form, a suffix for the other form. But I don't care about these defails. A substring (contiguous or not) is all I need in Pyth.

                        Implicit: z = raw_input() // Read a string
                 yz     A list with all substrings (contiguous or not) of z
       m                For each of these substrings d, build
        ,                  a pair of two strings:
         +z_d              ( z + inveres(d) ,
             +_dz            inverse(d) + z )
      s                 Sum (put all created pairs into a list)
 fq_TT                  filter elements T, where inverse(T) == T (Palindrom)
h                          Take the first element

Edit

The old version ordered the the strings after filtering by length .olN.... Just realized, that y returns the substrings ordered by length. So these palindromes are already sorted.


Python, 51 bytes

f=lambda n,k=2:n<3or k<n and f(k)*f(n-k-2)+f(n,k+1)

Try it online!

Simplifies the formula a bit:

$$a(n) =  \sum_{k=2}^{n-1} a(k)\cdot a(n-2-k)$$

$$ a(-1) = a(0)= a(1)= a(2) = 1$$


Bash + system utilities, 56 53 49 48 bytes

Update: saved 4 bytes thanks to Digital Trauma and 1 byte more thanks to Dennis

curl -L `yes google.com|sed $1q`|wc|dc -e1k?$1/p

In my original answer I was using yes in combination with xargs to emulate a for loop. But curl can accept as input a list of URLs, so only the output from yes is actually needed.

When curl accesses google.com, it receives a 302 redirection page that has the new URL in the body section, so the -L option is needed to follow it.

Run example: answer is printed to STDOUT, I redirect STDERR just for clarity

me@LCARS:/PPCG$ ./google_length.sh "8" 2> /dev/null
10583.2

Explanation: (of the initially submitted code)

yes google.com|     # repeatedly output a line containing the string "google.com"
sed $1q|            # print the first $1 lines only (shorter than head -$1)
xargs curl -sL|     # xargs reads the input lines and executes "curl -sL" with the
                    #current input line as an additional argument.
wc -m|              # count the number of characters
dc -e1k?$1/p        # dc script: set precision to 1, read input, push $1 and divide

Edit: I replaced wc -m with wc, because even if without arguments it prints 2 more statistics than the one I wanted, the same dc script following this output still works, because the count we want is, happily, placed on top of the stack during parsing.


Construct a line graph / conjugate graph

Ruby, 51 bytes

->a{a.combination(2){|x,y|p [x*'',y*'']if(x&y)[0]}}

Try it online!

For each combination of two edges, if they have a vertex in common (i.e. if the first element of their intersection is non-nil), print an array containing the two edges to STDOUT.


RegEx-golf: match all contents in a string

PCRE, 21 20 15 19 bytes
(.|^)"\K(\\.|[^"])*

Try it here.
This matches a character (or the beginning of the input) before the beginning double quote and then reset the match, to make sure the double quote isn't shared with another match.
PCRE, 25 23 bytes
Thanks to Martin Büttner for golfing off 2 bytes.
(\\.|[^"])*+(?!"(?R)|$)

Try it here.
Explanation
(
    \\.|[^"]     # An escaped character, or a character that isn't a double quote
)*+              # Possessive zero-or-more quantifier, which means backtracking
                 # could not happen after first match is found. That means if \\.
                 # matched, it would never switch to [^"], because it is always a
                 # match if it just stopped after the \\. without backtracking.
(?!"(?R)|$)      # Make sure it is not followed by a double quote and another
                 # match, or the end of the input.

Note that the possessive quantifier (*+) made sure the negative lookahead always begins after a whole string, or a whole segment of non-string.
There are 4 cases:

The match begins anywhere outside of a string. \\. would never match a double quote according to the clarification. It could only end just before the next double quote which begins a string, or the end of input. Both cases fails the negative lookahead.
The match begins at the beginning of a string. (\\.|[^"])*+ would match a complete string. The next character must be a double quote, and couldn't be the end of input. After the double quote it is outside of the string, so it couldn't be another match. So it passes the negative lookahead.
The match begins at the end of a string. It matches an empty string in the same way as the previous case. But it doesn't matter according to the clarification.
The match begins in the middle of a string. Impossible because matches don't overlap.


Jelly, 9 bytes

×ḃ62ịØWŒs

Try it online!

How?

×ḃ62ịØWŒs - Main link: X, Y
×         - multiply X by Y
 ḃ62      - convert to bijective base 62 (uses modulo arithmetic under the hood)
    ị     - index into (1-based)
     ØW   - word yield -> "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
       Œs - swap case


Determine the optimal cruise control options

JavaScript (ES6), 91 84 75 bytes

Saved 4 bytes thanks to @Neil

f=(s,d)=>s-d?(q=s+10-s%10)>d?s>d?0+f(s-(s%10||10),d):1+f(s+1,d):2+f(q,d):""

Uses 0 for D, 1 for T, and 2 for U.


Jelly, 11 bytes
µÆE;¬g/’µ#Ṫ

Try it online!.
Background
Every positive integer \$k\$ can be factorized uniquely as the product of powers of the first \$m\$ primes, i.e., \$k=p_1^{\alpha_1}\cdots p_m^{\alpha_m}\$, where \$\alpha_m>0\$.
We have that \$a^b\$ (\$b>1\$) for some positive integer \$a\$ if and only if \$b\$ is a divisor of all exponents \$\alpha_j\$.
Thus, an integer \$k > 1\$ is a perfect power if and only if \$\gcd(α_1, ⋯, α_m) ≠ 1\$.
How it works
µÆE;¬g/’µ#Ṫ  Main link. No arguments.

µ            Make the chain monadic, setting the left argument to 0.
        µ#   Find the first n integers k, greater or equal to 0, for which the
             preceding chain returns a truthy value.
             In the absence of CLAs, n is read implicitly from STDIN.
 ÆE          Compute the exponents of the prime factorization of k.
   ;¬        Append the logical NOT of k, i.e., 0 if k > 0 and 1 otherwise.
             This maps 1 -> [0] and [0] -> [1].
     g/      Reduce the list of exponents by GCD.
             In particular, we achieved that 1 -> 0 and 0 -> 1.
       ’     Decrement; subtract 1 from the GCD.
             This maps 1 to 0 (falsy) and all other integers to a truthy value.
          Ṫ  Tail; extract the last k.


Funny, I just made one of these. It is quite efficient because it compiles selectors. I don't know if it's IE6-compatible but it should be, I think. It supports CSS3 too - bonus points? :)

if(![].indexOf)Array.prototype.indexOf=function(a,i){i=i||0;while(i<this.length)if(this[i++]===a)return i-1;return-1};
String.prototype.startsWith=function(s){return this.length>=s.length&&this.substring(0,s.length)===s};
String.prototype.endsWith=function(s){return this.length>=s.length&&this.substring(this.length-s.length)===s};

var Sprint = {
    Error: function(m) {
        this.message = m;
        this.toString = function() {
            return this.message;
        };
    },
    getAllElementsIn: function(element) {
        var r = [];
        var f = function recurse(l, arr) {
            from(l).each(function(k, v) {
                if(v.nodeType === 1) {
                    arr.push(v);
                    recurse(v, arr);
                }
            });
        };
        f(element, r);
        return r;
    },
    getAllElements: function() {
        return Sprint.getAllElementsIn(document.documentElement);
    },
    getSiblings: function(element) {
        return element.parentNode ? from(element.parentNode).where(function(k, v) { return v.nodeType === 1; }).toArray() : [element];
    },
    getInfo: function(selector) {
        var r = {ATTR: {}, CLASS: [], PSEUDO: []};

        var quotes = '\'"', nestable = '(){}', inAttribute = false, escaped = false, currentQuotes = null, currentNested = [], nonchar = /^[^a-zA-Z0-9_\-]$/, lastSplitter = null, i = -1, c, s = '';
        while(++i < selector.length) {
            c = selector.charAt(i);
            if(escaped) {
                escaped = false;
            } else if(c === '\\') {
                escaped = true;
                continue;
            } else if(currentQuotes) {
                if(currentQuotes === c) {
                    currentQuotes = null;
                }
            } else if(quotes.indexOf(c) > -1) {
                currentQuotes = c;
            } else if(currentNested.length) {
                if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) {
                    currentNested.pop();
                }
            } else if(nestable.indexOf(c) > -1) {
                currentNested.push(c);
            } else if(nonchar.test(c)) {
                if(lastSplitter) {
                    switch(lastSplitter) {
                        case '#':
                            r.ID = s;
                            break;
                        case '.':
                            r.CLASS.push(s);
                            break;
                        case '[':
                        case ',':
                            if(inAttribute) {
                                var j;
                                if((j = s.indexOf('=')) > -1) {
                                    r.ATTR[s.substring(0, j)] = s.substring(j + 1);
                                } else {
                                    r.ATTR[s] = true;
                                }
                            }
                            break;
                        case ':':
                            r.PSEUDO.push(s);
                            break;
                    }
                } else {
                    r.TAG = s;
                }

                if(c === ']') {
                    inAttribute = false;
                } else if(c === '[') {
                    inAttribute = true;
                }

                lastSplitter = c;

                s = '';
                continue;
            }
            s += c;
        }

        if(lastSplitter) {
            switch(lastSplitter) {
                case '#':
                    r.ID = s;
                    break;
                case '.':
                    r.CLASS.push(s);
                    break;
                case '[':
                case ',':
                    if(inAttribute) {
                        var j;
                        if((j = s.indexOf('=')) > -1) {
                            r.ATTR[s.substring(0, j)] = s.substring(j + 1);
                        } else {
                            r.ATTR[s] = true;
                        }
                    }
                    break;
                case ':':
                    r.PSEUDO.push(s);
                    break;
            }
        } else {
            r.TAG = s;
        }

        return r;
    },
    compileSingle: function(info) {
        var f = 'var t=l.nodeName?l.nodeName.toLowerCase():"",i=l.id?l.id.toLowerCase():"",c=l.className?" "+l.className.toLowerCase()+" ":"",s=Sprint.getSiblings(l),ss=from(s).where(function(k,v){return v.nodeName?v.nodeName.toLowerCase()===t:false;}).toArray(),si=s.indexOf(l),ssi=ss.indexOf(l);return ';
        if(info.TAG && info.TAG !== '*') {
            f += 't===\'' + info.TAG.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&';
        }
        if(info.ID) {
            f += 'i===\'' + info.ID.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&';
        }
        if(info.CLASS) {
            for(var i = 0; i < info.CLASS.length; i++) {
                f += 'c.indexOf(\' ' + info.CLASS[i].toLowerCase() + ' \')>-1&&';
            }
        }
        if(info.PSEUDO) {
            for(var i = 0; i < info.PSEUDO.length; i++) {
                var p = info.PSEUDO[i], j, v = '';
                if((j = p.indexOf('(')) > -1) {
                    v = p.substring(j + 1, p.length - 1);
                    p = p.substring(0, j);
                }
                switch(p) {
                    case 'first-child':
                        f += '!si';
                        break;
                    case 'first-of-type':
                        f += '!ssi';
                        break;
                    case 'nth-child':
                        // TODO: Implement all nth-*** selectors.
                        break;
                    case 'nth-of-type':

                        break;
                    case 'last-child':
                        f += 'si===s.length-1';
                        break;
                    case 'last-of-type':
                        f += 'ssi===ss.length-1';
                        break;
                    case 'nth-last-child':

                        break;
                    case 'nth-last-of-type':

                        break;
                    case 'only-child':
                        f += 's.length===1';
                        break;
                    case 'only-of-type':
                        f += 'ss.length===1';
                        break;
                    case 'disabled':
                        f += 'l.disabled';
                        break;
                    case 'enabled':
                        f += '!l.disabled';
                        break;
                    case 'checked':
                        f += 'l.checked';
                        break;
                    case 'empty':
                        f += '!l.childNodes.length'; // TODO: Maybe restrict to elements (t 1) only?
                        break;
                    case 'not':
                        f += '!Sprint.isMatch(\'' + v.replace(/\\'/g, function(x) { return '\\' + x; }) + '\')(0,l)';
                        break;
                    default:
                        throw new Sprint.Error("Unrecognized pseudo-class \"" + p + "\".");
                }
                f += '&&';
            }
        }
        if(info.ATTR) {
            from(info.ATTR).each(function(k, v) {
                var c = k.charAt(k.length - 1);
                f += 'l.getAttribute(\'' + ('$^*~|'.indexOf(c) > -1 ? k.substring(0, k.length - 1) : k).replace(/\\'/g, function(x) { return '\\' + x; }) + '\')';
                if(typeof v === 'string') {
                    v = v.replace(/\\'/g, function(x) { return '\\' + x; });
                    switch(c) {
                        case '$':
                            f += '.endsWith(\'' + v + '\')';
                            break;
                        case '^':
                            f += '.startsWith(\'' + v + '\')';
                            break;
                        case '*':
                            f += '.indexOf(\'' + v + '\')+1';
                            break;
                        case '~':
                            f += '.split(\' \').indexOf(\'' + v + '\')+1';
                            break;
                        case '|':
                            f += '.split(\'-\').indexOf(\'' + v + '\')+1';
                            break;
                        default:
                            f += '===\'' + v + '\'';
                    }
                }
                f += '&&';
            });
        }

        if(f.substring(f.length - 2) !== '&&') {
            // It matches anything.
            f = 'return true  ';
        }

        return new Function(['l'], f.substring(0, f.length - 2) + ';');
    },
    compileTree: function(selector) {
        var t = Sprint.tokenizeSelector(selector), i = -1, j, splitters = ', >~+';
        while(++i < t.length) {
            if(splitters.indexOf(t[i]) > -1) {
                j = i;
                while(--j >= 0 && t[j] === ' ') t[j] = null;
                j = i;
                while(++j < t.length && t[j] === ' ') t[j] = null;
            }
        }
        return from(t).where().select(function(k, v) {
            return k % 2 ? v : Sprint.compileSingle(Sprint.getInfo(v));
        }).toArray();
    },
    matchSingleTree: function(element, tree) {
        if(!tree.length) {
            return true;
        }

        if(!tree[tree.length - 1](element)) {
            return false;
        }

        for(var i = tree.length - 3; i >= 0; i -= 2) {
            switch(tree[i + 1] || ' ') {
                case ' ':
                    while(true) {
                        if(!(element = element.parentNode)) {
                            return false;
                        }
                        if(tree[i](element)) {
                            break;
                        }
                    }
                    break;
                case '>':
                    if(!(element = element.parentNode) || !tree[i](element)) {
                        return false;
                    }
                    break;
                case '+':
                    while(true) {
                        if(!(element = element.previousSibling)) {
                            return false;
                        }
                        if(element.nodeType === 1) {
                            if(!tree[i](element)) {
                                return false;
                            } else {
                                break;
                            }
                        }
                    }
                    break;
                case '~':
                    while(true) {
                        if(!(element = element.previousSibling)) {
                            return false;
                        }
                        if(tree[i](element)) {
                            break;
                        }
                    }
                    break;
            }
        }

        return true;
    },
    matchTree: function(element, tree) {
        var c = [];
        for(var i = 0; i < tree.length; i++) {
            if(tree[i] === ',') {
                if(Sprint.matchSingleTree(element, c)) {
                    return true;
                }
                c = [];
            } else {
                c.push(tree[i]);
            }
        }
        return Sprint.matchSingleTree(element, c);
    },
    tokenizeSelector: function(selector) {
        var quotes = '\'"', nestable = '(){}[]', escaped = false, currentQuotes = null, currentNested = [], tokens = [], splitters = ', >~+', i = -1, c, s = '';
        while(++i < selector.length) {
            c = selector.charAt(i);
            if(escaped) {
                escaped = false;
            } else if(c === '\\') {
                escaped = true;
                continue;
            } else if(currentQuotes) {
                if(currentQuotes === c) {
                    currentQuotes = null;
                }
            } else if(quotes.indexOf(c) > -1) {
                currentQuotes = c;
            } else if(currentNested.length) {
                if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) {
                    currentNested.pop();
                }
            } else if(nestable.indexOf(c) > -1) {
                currentNested.push(c);
            } else if(splitters.indexOf(c) > -1) {
                tokens.push(s);
                tokens.push(c);
                s = '';
                continue;
            }
            s += c;
        }
        tokens.push(s);

        return tokens;
    },
    isMatch: function(selector) {
        var f = Sprint.compileTree(selector);
        return function(key, element) {
            return Sprint.matchTree(element, f);
        };
    },
    select: function(selector) {
        return from(Sprint.getAllElements()).where(Sprint.isMatch(selector)).toArray();
    },
    selectIn: function(selector, element) {
        return from(Sprint.getAllElementsIn(element)).where(Sprint.isMatch(selector)).toArray();
    }
};

function from(x) {
    if(!x) {
        throw new Sprint.Error("null or undefined passed to Sprint:from().");
    }

    var r = {
        keys: [],
        values: []
    };

    if(x.length) {
        for(var i = 0; i < x.length; i++) {
            r.keys.push(i);
            r.values.push(x[i]);
        }
    } else if(x.childNodes) {
        return from(x.childNodes);
    } else {
        for(var y in x) {
            if(x.hasOwnProperty(y)) {
                r.keys.push(y);
                r.values.push(x[y]);
            }
        }
    }

    r.length = r.keys.length;

    r.where = function(f) {
        if(f) {
            if(typeof f === 'string') return this.where(new Function(['k', 'v'], 'return ' + f + ';'));

            var r = {};
            for(var i = 0; i < this.length; i++) {
                if(f(this.keys[i], this.values[i])) {
                    r[this.keys[i]] = this.values[i];
                }
            }
            return from(r);
        } else {
            return this.where(function(k, v) { return v; });
        }
    };

    r.select = function(f) {
        var r = {};
        for(var i = 0; i < this.length; i++) {
            r[this.keys[i]] = f(this.keys[i], this.values[i]);
        }
        return from(r);
    };

    r.each = function(f) {
        for(var i = 0; i < this.length; i++) {
            f(this.keys[i], this.values[i]);
        }
    };

    r.first = function() {
        return this.values[0];
    };

    r.last = function() {
        return this.values[this.length - 1];
    };

    r.splitBy = function(f) {
        if(typeof f === 'function') {
            var r = [], c = {};
            for(var i = 0; i < this.length; i++) {
                if(f(this.keys[i], this.values[i])) {
                    r.push(c);
                    c = {};
                } else {
                    c[this.keys[i]] = this.values[i];
                }
            }
            r.push(c);
            return from(r);
        } else {
            return this.splitBy(function(x) { return x === f; });
        }
    };

    r.limit = function(f) {
        var r = {}, i = -1;

        if(typeof f === 'function') {
            while(++i < this.length && f(this.keys[i], this.values[i])) {
                r[this.keys[i]] = this.values[i];
            }
        } else {
            while(++i < Math.min(this.length, f)) {
                r[this.keys[i]] = this.values[i];
            }
        }

        return from(r);
    };

    r.after = function(f) {
        var r = {}, i = -1;

        if(typeof f === 'function') {
            while(++i < this.length && !f(this.keys[i], this.values[i])) {
            }
            while(++i < this.length) {
                r[this.keys[i]] = this.values[i];
            }
        } else {
            if(f < this.length) {
                i = f - 1;
                while(++i < this.length) {
                    r[this.keys[i]] = this.values[i];
                }
            }
        }

        return from(r);
    };

    r.toArray = function() {
        return this.values;
    };

    return r;
}

You use it like so:

Sprint.selectIn("mySelector", element);

Or

Sprint.select("mySelector")

. The code is 6.89KB minified and 2.26KB gzipped.


J - 23 char

A little late to the party, but I'd like to bust out a neat little J trick here.

1($1+2|I.)^:_~".>2{ARGV

Given input N, this verb operates by executing N&($1+2|I.) on a starting argument of 1 until it reaches a fixed point. If the item at index i in y is n, there will be n copies of i in I.y, so for instance I. 0 1 1 0 0 3 1 is 1 2 5 5 5 6. We mod the result of that by 2 and add one. Then, x $ y forces y into a list of length x, truncating it or extending it cyclically as necessary.

So here's what happens when the input is, say, 10.

   10 ($1+2|I.)^:a: 1
1 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2
1 2 2 1 2 2 1 2 2 1
1 2 2 1 1 2 1 1 2 2
1 2 2 1 1 2 1 2 2 1

We start with a row of all 1s and then "settle down" into the Kolakoski sequence. First, it turns into 1 2 1 2 1 2... as each contiguous block of ones or twos is described by length 1. Then we apply it again and it turns into 1 2 2 1 2 2 1 2 2... since the ones are described by 1 and the twos are described by 2. The we continue again and again until we see there is no change, at which point we stop and give the result.

Other "self-describing" sequences can be similarly derived in J using I. and ^:_.

Edit

Over a year ago, @ardnew asked:

  what is the relationship between n and the number of those intermediate iterations required to generate the sequence of length n?

To make sure we're on the same page, I consider the calculation for n = 10 above to have taken 5 iterations.

If there are s terms settled at the i-th iteration for n, then at the (i+1)-th iteration, there will be (at least) k0 + k1 + ... + ks + 1 terms settled. The '+ 1' appears because the next term will also be correct, since it must be and is different from the term before it.

So if K(s) is the sequence of partial sums of kn, then we can lower bound the number of iterations for n by the least a such that (1+K)a(1) ≥ n. I don't how to prove we don't accidentally do a bit better (by picking up more correct terms than we expected in some iteration), but according to the numbers, we don't:

   k =: ($ 1 + 2 | I.)^:_&1               NB. Kolakoski seq
   pk =: +/\ @: k                         NB. partial sums ("K")
   ((1 + pk 2000) {~ <:) ::_:^:(i.20) 1   NB. iterating 1+K, say, 20 times
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2590 _ _
   NB. compare with observed number of settled terms up to 2000:
   +/"1 }. (k <./\ . ="1 ($1+2|I.)^:a:&1) 2000
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2000

The underscores are index errors (:: _:), telling us 20 iterations is too much for the first 2000 terms of kn to handle.


Haskell, 77 bytes

(&2) is an anonymous function taking an Integer and returning a (potentially very long) list of Integers, use as (&2) 13.

(&2)
n&b|n<0=[]|let _?0=0;e?n=(e+1)?div n b+mod n b*(b+1)^0?e=n:(0?n-1)&(b+1)

Try it online! (cuts off at 10^25.)

How it works

(&2) starts the sequence with base 2.
n&b calculates the subsequence starting with the number n and base b.

It halts with an empty list if n<0, which generally happens the step after n==0.
Otherwise, it prepends n to the list returned recursively by the expression (0?n-1)&(b+1).

? is a local function operator. 0?n gives the result of converting n to hereditary base b, then incrementing the base everywhere.

The conversion recurses with the variable e keeping track of the current exponent. e?n converts the number n*b^e.
The recursion halts with 0 when n==0.
Otherwise, it divides n by the base b.

(e+1)?div n b handles the recursion for the quotient and next higher exponent.
mod n b*(b+1)^0?e handles the remainder (which is the digit corresponding to the current exponent e), the increment of base, and converting the current exponent hereditarily with 0?e.


Given N, output n-th element of ['A', 'B', 'AB', 'C', 'D', 'CD', 'ABCD', 'E', ...]?

Python 2, 53 bytes

x,y=0,1
exec"x^=y-x;y+=x/y;"*input()
print range(x,y)

Try it online!

Similar to this construction with the transformation x = u-v, y = u


05AB1E, 23 bytes

hgÌ¹gD<g>¹ÀðìÁ0ÜðÜg+)Wk

Try it online!

-1 thanks to Emigna.

0 for hexadecimal, 1 for decimal, 2 for scientific.


Mathematica, 38 bytes

StringLength@StringJoin@IntegerName[Range[1000]]

@Doorknob has a leaner implementation:

Tr@StringLength@IntegerName@Range@1000

(* 20961 *)

Explanation

IntegerName[Range[10]]

(* {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"} *)

StringJoin@IntegerName[Range[10]]

(* "onetwothreefourfivesixseveneightnineten" *)

StringLength@StringJoin@IntegerName[Range[10]]

(* 39 *)


C++11
Simply compares single core performance with threaded performance until there is not a linear speedup anymore. It's important that you do not have any other CPU intensive process running at the same time.
Compile with -O2 -m64 -march=native -std=c++11. You might have to pass -lpthread.
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <vector>

double f() {
    double cnt = 0;
    std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
    start = std::chrono::system_clock::now();

    while (true) {
        end = std::chrono::system_clock::now();
        std::chrono::duration<double> elapsed = end - start;
        if (elapsed.count() > 1.) break;
        cnt++;
    }

    return cnt;
}

int main(int argc, char** argv) {
    double one_core = f();

    int n = 1;
    while (true) {
        std::vector<std::future<double>> futures;
        for (int i = 0; i < n; ++i) {
            futures.push_back(std::async(std::launch::async, f));
        }

        double tot = 0;
        for (int i = 0; i < n; ++i) tot += futures[i].get();
        if (int(tot / one_core + 0.5) != n) {
            std::cout << n - 1 << " core(s)\n";
            return 0;
        }

        ++n;
    }
}


Fundamental Solution of the Pell Equation

Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:

Pell's equation § Fundamental solution via continued fractions
Methods of computing square roots § Continued fraction expansion
Continued fraction § Infinite continued fractions and convergents

Basically, what we do is this:

Get \$n\$ from standard input.
Find \$\lfloor\sqrt n\rfloor\$ by incrementing a counter until its square exceeds \$n\$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
Set up some variables for calculating \$x\$ and \$y\$ from the continued fraction of \$\sqrt n\$.
Check whether \$x\$ and \$y\$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)

I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.


Approximate square root from algorithm time complexity

C(++), 93 Bytes

My solution:

int s(int a){int b=0;for(int i=1<<15;i>0;i/=2){if((b+i)*(b+i)<=a)b+=i;else{for(int j=1;j<i;j*=2);}}return b;}

It is O(n) for a = 0xFFFF..., and O(n^2) for a = 0x1000...
And it returns floor(sqrt(x)), which is an approximation of sqrt(x)

However, If you want an algorithm that works in O(n) time, you can shave off 28 bytes.

For test cases, append:

int main()
{
    int a = 1024;
    return s(a); //returns sqrt(1024) = 32
}


Python 3, 140 133 124 123 bytes

d=*map(set,'AJK BCDEGPTVZ IY QU SXF MN H L O R W'.split()),
print([d[int(c,16)].pop()for c in'0111141620075581394131a421'])

Try it online!

-1 byte, thanks to Jo King

Python 2, 174 170 158 bytes

from random import*
s=''
for c in'abbbbebHcaaLffObdRebdbWecb':s+=choice(list(set(('AJK BCDEGPTVZ IY QU SXF MN '+c).split()['abcdef'.find(c)])-set(s)))
print s

Try it online!


Score: 382 * 1.12 = 462

Languages prone to change.

1. APL, 8 4

Thanks @marinus for shaving 4 chars off.

f←⍴~

Called with the strings as the left and right arguments, eg.

      'foobarbaz' f 'ao'
5

2. Ruby, 35 31

Thanks @DoorknobofSnow for shaving 4 chars off.

f=->s,r{s.gsub(/(?<=^)/,r+' ')}

3. Python, 48

f=lambda s,n,b:s.replace(*['\t',' '*n][::2*b-1])

4. GolfScript, 20

{@//zip{' '*}%n*}:f;

Assumes that the arguments are on the stack. Test online

5. J, 50

f=:({~[:(i.>./)+/"1@=@(}.~0-1{$))@|:@([$~],1+[:$[)

Called with the string as the left argument and the number as the right, eg.

   'abcdeabcfghiabc' f 3
abc

6. Ruby, 61

f=->s{s.gsub(/(?<!^| )[^ ]+(?!$| )/){[*$&.chars].shuffle*''}}

7. GolfScript, 39 35 34

{[.10,' '*-{{}/]' '*}{~]''+}if}:f;

Again, assumes the argument is on the stack. Test online

8. Perl, 98

sub f{$_=@_[0];s!\*\*(.+?)\*\*!$1!g;s!\*(.+?)\*!$1!g;s!`(.+?)`!$1!g;$_}

9. Haskell, 36

f s n r=[(x++cycle r)!!n|x<-words s]


Java (JDK), 131 124 110 84 64 bytes

Interestingly, "dot" is dash-heavy and "dash" is dot-heavy.

Takes input in all caps as an IntStream (scroll down for a version with an actual String for an extra 8 bytes). I've had quite a lot of help golfing this one: Thanks to Expired Data for golfing 20 bytes, to Neil for golfing 26 bytes, to Olivier Grégoire for golfing 18 bytes and to Kevin Cruijssen for golfing 2 bytes.

Contains 26 unprintable characters inside the double quotes.

c->c.map(a->"".charAt(a-65)-4).sum()>0

Try it online!

Ungolfed:

c -> // lambda taking input as an IntStream in upper case and returning a boolean
  c.map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here)
    .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A')
    - 4) // unprintables are > 0, this restores the proper values
  .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string

Java (JDK), 131 124 110 84 72 bytes

For purists; takes input as a String. Thanks to Expired Data for golfing 20 bytes, to Neil for golfing 26 bytes and to Olivier Grégoire for golfing 10 bytes.

s->s.chars().map(a->"".charAt(a-65)-4).sum()>0

Try it online.

Ungolfed:

s -> // lambda taking input as a String in upper case and returning a boolean
  s.chars() // convert to a stream of characters
  .map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here)
    .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A')
    - 4) // unprintables are > 0, this restores the proper values
  .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string


The Solar Eclipse Through a Pinhole Camera


Bash, 43 bytes

sed s/+/rdnFPrp+/g\;s/U/p2^/g|dc|tac|sed 4q

Try it online!
This prints the clipboard in the following format, note the usage of \x0F as the separator.
item_1\x0Fitem_2
item_3
.
.
item_m\x0Fitem_n

The key idea is to pass this into dc, a stack-based language, such that the required stack items will be printed.
The input is piped to sed where every + is replaced with rdnFPrp+, which in dc prints the second number on the stack followed by \x0F and then the top number before performing addition. sed also replaces every U with p2^, print the top stack element and square it.

The first substitution command s replaces all, as is denoted by the global flag g, +s with rdnFPrp+. In dc, r swaps the top two stack items, d duplicates the top item, n prints it without a newline, F pushes 15 onto the stack and P prints it as a character (which is the delimiter), r swaps again, p prints the top stack item and then + performs addition on the top two stack items.
We have another command, and in sed, commands are separated by either semicolons or newlines, of which the first option is chosen. Simply having ; will make bash interpret that as the end of the sed command, so it is escaped with a \.
In the last substitution command, U is replaced globally with p2^. In dc, p prints, and 2^ raises it to the second power.

The result of sed is eval'ed as dc code, printing the entire clipboard.

The pipe to dc makes dc interpret that as dc code. Now, the most recent calls are at the bottom and the older ones at the top.

Since the lines are in reverse order, tac (reverse cat) is used to fix that.
And finally, sed picks the first 4 lines from tac.

This is a shorter way of doing head -4. sed performs the commands to every line of the input one at a time. If there are no commands, nothing is done to the input, and it is returned as it is. 4q tells sed to perform the command q on line 4. When sed is processing line 4 of the input, the first three inputs have already been printed. The command q quits the program, so it prints the fourth line and quits, thus performing the equivalent of head -4.


Compute the Resistance of a 4 Band Color Coded Resistor

CJam, 59 58 56 50 bytes

r_W%e>"sgKNROYGBVAW"f#2f-~A*+A@#*" Ω ±"@[KA5]='%

Try it online in the CJam interpreter.


gawk, 316+377 = 693

First command line parameter is the lyrics' filename (375 bytes + 2 for invocation = 377). Rickrolls all other files. Prints to stdout.

BEGIN{FPAT="[^ ]+ *";OFS=""}func d(a){b=tolower(a);sub(/ *$/,"",b);return b}FNR==NR{for(s=$0;NF;$0=s=$0){for(i=1;i<NF;i++){k=k $i;$i="";v[d(k)]="["$0"] "}$0=s;k=$1=""}next}{for(s=$0;NF;$0=s=$0){for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)="");k=v[d($0)];if($0!~/ $/)k=" "k;printf($0 k);for($0=s;j-->=0;$(j+2)="");}print""}

Ungolfed

BEGIN{FPAT="[^ ]+ *";OFS=""}
func d(a){b=tolower(a);sub(/ *$/,"",b);return b}
FNR==NR{
  for(s=$0;NF;$0=s=$0){
    for(i=1;i<NF;i++)
    {
      k=k $i;
      $i="";
      v[d(k)]="["$0"] "
    }
    $0=s;
    k=$1=""
  }
  next
}
{
  for(s=$0;NF;$0=s=$0){
    for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)="");
    k=v[d($0)];
    if($0!~/ $/)k=" "k;
    printf($0 k);
    for($0=s;j-->=0;$(j+2)="");
  }
  print""
}

Test results

Input:

we're
We're
Does he know the answer?
I
how I'm thinking
I'm thinking
I don't know what I'm doing with my life.
Will someone please save me from these memes?
Two strangers walked into a bar.  One said "hello."  The other said "goodbye."
gonna run

Output:

we're [no strangers to love]
We're [no strangers to love]
Does he know the [rules and so do I] answer?
I [just wanna tell you how I'm feeling]
how I'm [feeling] thinking [of]
I'm thinking [of]
I [just wanna tell you how I'm feeling] don't know [the rules and so do I] what I'm [thinking of] doing with my life.
Will someone please save me from [any other guy] these memes?
Two strangers [to love] walked into a [lie and hurt you] bar.  One said "hello."  The [rules and so do I] other [guy] said "goodbye."
gonna run [around and desert you]


JavaScript (Node.js), 548 516 511 485 453 397 396 392 372 325 323 260 bytes

f=(i=!(b=20,p=10))=>b*p>0?`T:${++i} R:${(r=0|Math.random()*6)+1}
|   |Book|A |B |C |D |E |F |G |H |I |J |
|Stt${(d=(n,s)=>`|${n}`.padEnd(5)+`|${s}`.padEnd(3).repeat(10)+`|
`)(b,p)}|Bet${d('n/a',1)}|Chg${d(u=r?'+10':-40,v=r?-1:'+4')}|End`+d(b+=+u,p+=+v)+f(i):''

Try it online!

-32 something bytes by shortening row labels. Also fixed the dice roll being 0-5, not 1-6
-5 bytes by compacting output format
-26 bytes because padding
-32 bytes because whitespace is the devil
-56 bytes thanks to ASCII-only and Luis Felipe in chat
-1 byte because return x doesn't need to be on a new line
-4 bytes thanks to some small refactors from ASCII-only
-20 bytes thanks to more collaboration in chat and some changes by Kevin Cruijssen
-47 bytes because y was the devil and ASCII-only performed an exorcism
-2 bytes because ASCII-only is a golfing machine
-63 bytes thanks to the work of several people in the comments

The golf I took was calculated, but man am I bad at golf.

Almost looks like python rather than JS because where possible I used newlines in place of semicolons for readability.

All gamblers always bet on 1, so we only need to store 1 gambler balance (p), the bookie's balance is b.

Explanation time

I need to rewrite the explanation to match the 260 byte version, but check the revision history for the lengthy explanation of the 323 byte version.


Keg, 4x4 magic square

0601
7.92
3._.
8654

Try it online!

Outputs

 0601 - 1
 7.92 - 7
 3._. - 3
 8654 - 4
/||||\
98652 0

I can't believe this actually works! Programs need the -hr flag to properly output the required result.

Test suite. Uncomment each line to run it. The -in flag is purely to make the test suite a nicer experience, as otherwise, the newlines would interfere with the programs.

Programs

0601 - 1 (Push 0, 6, 0 and 1,then print the top of stack (TOS))
7.92 - 7 (Push 7 and print it. This makes the rest of the program a NOP)
3._. - 3 (Push 3 and print it. The _ will the try and pop from an empty stack, ending execution)
8654 - 4 (Push 8, 6, 5 and 4 and then print TOS)
0738 - 8 (Push 0, 7, 3 and 8 and then print TOS)
6..6 - 6 (Push 6 and print it. The . will try and print from an empty stack, end execution)
09_5 - 5 (Push 0 and 9, then pop the 9 and discard it then push 5. TOS is then printed)
12.4 - 2 (Push 1, then 2 and print TOS. The rest of the program is NOPs after that.)
0._4 - 0 (Like the program for 3, but with 0)
19.8 - 9 (Like the program for 2 but with 9)


Randomly pick one number that is different than two other random numbers

Ruby, 22 characters

([1,2,3]-[A,B]).sample

Still not sure if I understood the question correctly ...