Moving CSS rules from a CSS file to inline attributes

Python - 508, 501, 483

The idea is to read all the rules then apply them by using xpath functions, too bad it can't select nodes with multiple classes (I didn't find own to target class="code golf").

Golfed

import sys,xml.etree.ElementTree as E
r=E.parse(sys.argv[2])
def a(e,f):e.set('style',(e.attrib.get('style')or'')+f)
for l in open(sys.argv[1]):
 s=l.replace("\n",'').split(' ');b=s[0];c=s[1][1:-1]
 if(b[:1])=='#':
  for e in r.findall('.//*[@id=\''+b[1:]+'\']'):a(e,c);e.attrib.pop('id')
 else:
  for e in r.findall('.//*[@class]'):
   d=e.attrib.get('class').split(' ')
   if b[1:]in d:
    a(e,c);e.set('class',' '.join(d[1:]))
    if len(d) == 1: e.attrib.pop('class')
E.dump(r)

Usage

python script.py input.css input.html

Ungolfed code

import sys, xml.etree.ElementTree as ET
root = ET.parse(sys.argv[2])

# append rules to style="" attribute
def a(e,f):
    e.set('style',(e.attrib.get('style')or'') + f)

# CSS file
for l in open(sys.argv[1]):
    split = l.replace("\n", '').split(' ')
    selector = split[0]
    rules = split[1][1:-1]

    # #id
    if (b[0:1]) == '#':
        for e in root.findall('.//*[@id=\''+selector[1:]+'\']'):
            a(e,rules)
            # remove id
            e.attrib.pop('id')
    # .class
    else:
        for e in root.findall('.//*[@class]'):
            d=e.attrib.get('class').split(' ')
            if selector[1:] in d:
                a(e,rules)
                e.set('class', ' '.join(d[1:]))
                # remove class
                if len(d) == 1:
                    e.attrib.pop('class')

ET.dump(root)


Squarefinder – Locating regular tetragons

Python 2, 480 436 386 352 bytes

exec u"""s=sorted;H=[];V=[]
FRIinput():
 S=2*map(s,zip(*R))
 FiI0,1,2,3:
    c=S[i][i/2];a,b=S[~i]
    FeIs(H):
     C,(A,B)=e
     if a<C<b&A<c<B:e[:]=C,(A,c);H+=[C,(c,B)],;V+=[c,(a,C)],;a=C
    V+=[c,(a,b)],;H,V=V,H
print sum(a==A==(d,D)&c==C==(b,B)&B-b==D-d&1-any(d<X[0]<D&b<y<B Fy,XIH)Fb,aIH FB,AIH Fd,cIV FD,CIV)""".translate({70:u"for ",73:u" in ",38:u" and "})

Takes a list of coordinate pairs through STDIN in the format:

[  [(x, y), (x, y)],  [(x, y), (x, y)],  ...  ]

and prints the result to STDOUT.

The actual program, after string replacement, is:

s=sorted;H=[];V=[]
for R in input():
 S=2*map(s,zip(*R))
 for i in 0,1,2,3:
    c=S[i][i/2];a,b=S[~i]
    for e in s(H):
     C,(A,B)=e
     if a<C<b and A<c<B:e[:]=C,(A,c);H+=[C,(c,B)],;V+=[c,(a,C)],;a=C
    V+=[c,(a,b)],;H,V=V,H
print sum(a==A==(d,D) and c==C==(b,B) and B-b==D-d and 1-any(d<X[0]<D and b<y<B for y,X in H)for b,a in H for B,A in H for d,c in V for D,C in V)

Explanation

Instead of fiddling with complex polygons, this program deals with simple line segments.
For each input rectangle, we add each of its four edges to a collective segment list, individually.
Adding a segment to the list goes as follows:
we test each of the existing segments for intersection with the new segment;
if we find an intersection, we divide both segments at the point of intersection and continue.
To make things easier, we actually keep two separate segment lists: a horizonal one and a vertical one.
Since segments don't overlap, horizontal segments can only intersect vertical segments and vice versa.
Better yet, it means that all intersections (not considering the edges of the same rectangle) are "proper," i.e., we don't have T-shaped intersections, so "both sides" of each segment are truly divided.

Once we've constructed the segment list(s), we start counting squares.
For each combination of four segments (particularly, two horizontal segments and two vertical ones,) we test if they form a square.
Furthermore, we verify that no vertex lies within this square (which can happen if, for example, we have a small square inside a bigger one.)
This gives us the desired quantity. Note that even though the program tests each combination four times in different orders, the particular ordering of the segment coordinates guarantees that we count each square only once.


GNU sed with -r - 133 117 111 93 chars

Yes, sed is turing complete. GNU sed and -r (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.

:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs

Input format is

[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...

The delimiters @, # and head character > cannot be used as a symbol on the tape. State labels cannot contain @ > or #.

It will run all of the programs in the input, one per line

Examples:

Marco's anbn program

  Input

0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

  Output

5@    T>  #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

Marco's Hello! program

  Input

0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r

  Output

6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r


MATL, 11 10 bytes

5:)d|2e!sd

Input is a vector of four complex numbers. Output is 0 (which is falsy) if tangential, or nonzero (which is truthy) if not tangential.

Try it online! Or verify all test cases.

Explanation

The code computes the difference between sums of lengths of opposite sides. This difference is zero if and only if the quatrilateral is tangential.

5:   % Range [1 2 3 4 5]
)    % Implicit input: complex vector of length 4. Index into it modularly.
     % This repeats the first vertex after the last
d    % Consecutive differences
|    % Absolute value, element-wise
2e   % Reshape as a 2-column matrix, in column-major order
!    % Transpose
s    % Sum of each column. Gives a vector of length 2
d    % Consecutive difference


Jelly, 7 bytes
LŒṗịµ§Ṁ
L        length
 Œṗ      integer partitions
   ị     index
     §Ṁ  sum each and take the maximum

My first jelly answer, so there can probably be improvements made.
Try it online!


JavaScript (ES6), 93 88 bytes

f=
s=>s.replace(/force|first/gi,s=>s.replace(/./g,c=>s[s.search(c)^1]||c,s="oicsetOICSET"))
<textarea oninput=o.textContent=f(this.value)></textarea><pre id=o>

Edit: Saved 5 bytes by optimising the unchanged letter case.


How many ways to write N as a product of M integers?

Python 3, 59
f=lambda N,M,i=2:i<=N and f(N/i,M-1,i)+f(N,M,i+1)or-~M==N<2

We count up potential divisors i. With the additional argument i as the lowest allowed divisor, the core recursive relation is
f(N,M,i)=f(N/i,M-1,i)+f(N,M,i+1)

For each i, we either choose to include it (possible as a repeat), in which case we divide the required product N by i and decrement M. If we don't, we increase i by 1, but only if i<N, since there's no use checking divisors greater than N.
When the minimum divisor i exceeds N, there's no more potential divisors. So, we check if we've succeeded by seeing if M==0 and N==1, or, equivalently, M+1==N==1 or M+1==N<2, since when M+1==N, the mutual value is guaranteed to be a positive integer (thanks to FryAmTheEggman for this optimization).
This code will cause a stack overflow for N about 1000 on most systems, but you can run it in Stackless Python to avoid this. Moreover, it is extremely slow because of its exponential recursive branching.


Probability of All Combinations of Given Events

Haskell, 86 bytes

unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)])

Usage example:

Prelude> putStrLn $ unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)]) $ [0.55, 0.67, 0.13]
[0,0,0] = 0.12919499999999998
[0,0,1] = 1.9304999999999996e-2
[0,1,0] = 0.262305
[0,1,1] = 3.9195e-2
[1,0,0] = 0.157905
[1,0,1] = 2.3595e-2
[1,1,0] = 0.320595
[1,1,1] = 4.790500000000001e-2

Most of the bytes are spent for output formatting. If you are only interested in the probability vector it's only 29 bytes:

map product.mapM(\x->[1-x,x])

How it works:

                    mapM(\x->[(0,1-x),(1,x)])   -- for each number x in the input
                                                -- list make either the pair (0,1-x)
                                                -- or (1,x). Build a list with
                                                -- all combinations

    map(\p->                    )               -- for each such combination p
          show(fst<$>p)                         -- print the first elements
          ++" = "++                             -- then the string " = "
          show(product$snd<$>p)                 -- then the product of the second
                                                -- elements

unlines                                         -- joins with newlines


Perl, 52 bytes

Just a recursive subroutine. (unusual for a Perl answer, I know..)

sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}

Call it like that :

$ perl -E 'sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}f(1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9])'
1
2 3 9
4 7
5 6

8

Each line of the output corresponds to a depth level of the array (hence the empty line in the example above).

It can be turned into a full program for just a few more bytes : add -n flag and an eval (inside @{ } to transform the input into an array and not an arrayref) to transform the input into a Perl array :

perl -nE 'sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}f(@{+eval})' <<< "[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]"

My previous approach was slightly longer (65 bytes), but still interesting, so I'll let it here :

perl -nE '/\d/?push@{$;[$d-1]},$_:/]/?$d--:$d++for/\[|]|\d+/g;say"@$_"for@' <<< "[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]"


Mathematica, 151 122 characters

Expects the target resistance to be stored in r and the list of available resistors in l.

SortBy[Join[{#,#}&/@l,Join@@(#@@@Union[Sort/@N@l~Tuples~{2}]&/@{{"+",##,#+#2}&,{"|",##,#*#2/(#+#2)}&})],Abs[#[[-1]]/r-1]&]

Less golf:

SortBy[Join[{#, #} & /@ l,
  Join @@ (# @@@
       Union[Sort /@ N@l~Tuples~{2}] & /@ {{"+", ##, # + #2} &, {"|", ##,
        #*#2/(# + #2)} &})], Abs[#[[-1]]/r - 1] &]

The output format differs from the suggested one but configurations are easily determinable. The output is a list of configurations. Each configuration is of one of the following forms:

{R1, Total}
{"+", R1, R2, Total}
{"|", R1, R2, Total}

So the first three elements of the output read

{{"|", 680., 2200., 519.444}, {"|", 1000., 1000., 500.}, {"+", 150., 330., 480.}, ...}

If you're fine with rational numbers, I could save two characters from omitting N@. That is, the first element (for instance) would be returned as 4675/9 instead of 519.444.


Python 2, 674

exec u"""import sys
$ V#):%=V.c;V.c+=1
 c=97;p!,v,t:[s,t.u({})][v==s];r!:s;u!,d:d.get(s,s);s!:chr(%)
 def m(s,x):%=min(%,x);-(%==x)+x
$ A#,*x):%,&=x
 C='()';p!,x,y:s.__$__(%.p/,&.p/);m!,x:&.m(%.m(x));u!,d:A(%.u(d),&.u(d));s!:%.s()+s.C[0]+&.s()+s.C[1:]
 def r(s):x=%.r();y=&.r();-x.b.p(x.a,y).r()if'L'in`x`else s.__$__/
$ L(A):C='.';u!,d:L(d.setdefault(%,V()),&.u(d))
x=V();y=V();z=V()
I=L(x,x)
K=L(y,L/)
S=L(x,L(z,L(y,A(A/,A(z,y)))))
def E():
 t=I
 while 1:
    q=sys.stdin.read(1)
    if q in')\\n':-t
    t=A(t,eval(max(q,'E()')).u({}))
t=E().r()
t.m(97)
print t.s()""".translate({33:u'=lambda s',35:u':\n def __init__(s',36:u'class',37:u's.a',38:u's.b',45:u'return ',47:u'(x,y)'})

Note: after while 1:, 3 lines are indented with a tab character.

This is basically the code behind http://ski.aditsu.net/ , translated to python, greatly simplified and heavily golfed.

Reference: (this is probably less useful now that the code is compressed)

V = variable term
A = application term
L = lambda term
c = variable counter
p = replace variable with term
r = reduce
m = final variable renumbering
u = internal variable renumbering (for duplicated terms)
s = string conversion
(parameter s = self)
C = separator character(s) for string conversion
I,K,S: combinators
E = parse

Examples:

python ski.py <<< "KSK"
a.b.c.a(c)(b(c))
python ski.py <<< "SII"
a.a(a)
python ski.py <<< "SS(SS)(SS)"
a.b.a(b)(c.b(c)(a(b)(c)))(a(d.a(d)(e.d(e)(a(d)(e))))(b))
python ski.py <<< "S(K(SI))K"
a.b.b(a)
python ski.py <<< "S(S(KS)K)I"
a.b.a(a(b))
python ski.py <<< "S(S(KS)K)(S(S(KS)K)I)"
a.b.a(a(a(b)))
python ski.py <<< "K(K(K(KK)))"
a.b.c.d.e.f.e
python ski.py <<< "SII(SII)"
[...]
RuntimeError: maximum recursion depth exceeded

(this ↑ is expected because SII(SII) is irreducible)

Thanks Mauris and Sp3000 for helping to kill a bunch of bytes :)


C99 + sh + C11, 165 162 146 145 combined chars

Edit: using @flonk's trick I managed to put the "comment" in C (making use of C11's u"" Unicode literals).

Common characters are: acehinortu.

hello.c (106):

*a="\2+++++++++++++++++++++++++++++++++";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

hello.sh (39):

true
echo -n 'Hello, new world! again.'

hello-combined.c (145):

*tar=u"e\
2e+c+h+o+ +-+n+ +'+H+e+l+l+o+,+ +n+e+w+ +w+o+r+l+d+!+ +a+g+a+i+n+.+'";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

Here are some utilities that might prove useful for other participants.

combine.c:

#include <stdio.h>
int main(int argc, char *argv[]) {
  FILE *f1 = fopen(argv[1], "r"), *f2 = fopen(argv[2], "r");
  while (!feof(f1) || !feof(f2)) {
    int c1 = fgetc(f1), c2 = fgetc(f2);
    if (c1 != EOF) putchar(c1);
    if (c2 != EOF) putchar(c2);
  }
  return 0;
}

char-check.{ba,z}sh:

comm -12 <(grep -o . "$1" | sort | uniq) \
         <(grep -o . "$2" | sort | uniq) | tr -d '\n'

Here's a variation that unfortunately ended up (considerably) longer, but it's pretty cool in how it works.  (I didn't bother getting the intersection between the sets of characters down to 10, since it ended up longer anyway.)

hello.c (113):

*a="\5Lipps0$ri{${svph%$ekemr2+++++++++++",*b=&a,c=6;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

hello.sh (51):

true
echo -n 'Hello, new world! again.' #     tr  1

hello-combined.c (164):

*tar=u"e\
5eLcihpop s-0n$ r'iH{e$l{lsov,p hn%e$we kweomrrl2d+!+ +a+g+a+i+n+.+'+ +#" , * b = &tar, c =16;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

This one is fun, because it doesn't just "comment out" a bunch of characters, but actually stores the characters it prints inside the string literal and accounts for the extra characters in the for-loop of the generated program.


ruby - 3710 = 90 characters code + 3620 bytes data
require'zlib'
$><<$*[0].chars.map{|x|Zlib::Inflate.inflate File.open(x).read}.join(?0*5e3)

input: a single command line argument, the number to read
output: raw sound data, PCM 8bit/8kHz
This can read any input string, as long as

it only contains characters that are valid file names. for only four chars, you can enlarge that set to all characters.
you have the neccessary files.
why oh you space dee oh en apostrophe tee space em i en dee space tee aitch i es period

5e3 encodes the pause between two words. Here, 5ksamples ~= 0.6s. Tweak as desired.
Now, the tricky part is to get the sample files in 4K and yet be able to decompress them easily and in sufficient quality. Here is how I got them:

Take a Text-to-speech engine able to produce sound files. Wikipedia has one.
Feed it a text containing all digits, ideally close together. I used http://en.wikipedia.org/wiki/Base_13
Downsample.
Cut out each part in a sound editor.
Save as a raw file.
Decimate each sample (discard low-order bits).
Deflate.

Now, one has to choose a sample rate and decimation amount. Too much, and the sound won't be understandable. Too little, and you don't fit. I have settled for 8kHz/3b. There they are: https://github.com/honnza/drops/raw/master/digits.zip

8KHz * 4b/sample and higher quality - too big
8KHz * 3b/sample - low quality, but it fits into 4K
8KHz * 2b/sample - kch kchhhhhhhhh [not understandable]
2KHz * 8b/sample - too big
2KHz * 3b/sample - kch kchhhhhhhhh
1KHz * 8b/sample - kch kchhhhhhhhh

Here's the decimation script:
require'zlib'
Dir.glob "*.raw" do |fname|
  File.open fname[/\d/], "wb" do |out|
    File.open fname do |input|
      bytes = input.bytes.to_a
      bytes.map! {|x|x&0xE0}
      dfl = Zlib::Deflate.deflate(bytes.pack("C*"),9)
      dfl.each_byte do |byte|
        out.print byte.chr
      end
      puts "done #{fname}: #{dfl.size}"
    end
  end
end

As for the original challenge: there are 476 bytes of space for code and the file table. This might be slightly too much depending on how tiny we can get with a DEFLATE library. If neccessary, we can cut a few corners here and there by cropping the audio samples a bit more aggresively. [fo:r] or [o:] doesn't really matter but it saves bytes. I have been somewhat benevolent when cropping the numbers. Also, a different decimation scheme or sacrificing some decimation for downsampling might help - I'll toy with these later. Also, dropping the DEFLATE headers might save a tiny amount of space.
Concatenating sound samples is quite easy, but 4K is a little cramped. If you are not bound by 4k space, I suggest less decimation. 4 bits per sample actually fares quite well and is only slightly bigger.


Bash: 16 characters
echo -e "\u2665"

output (when unicode supported)
♥

Ah wait, it must be an image?
ImageMagick: 137 characters
w=99
h=199
convert -size ${w}x$w -gravity center -font WebDings -fill red label:Y h.gif
convert h.gif -resize ${w}x$h\! h2.gif

output (when WebDings font installed)


05AB1E, 40 27 bytes
.¡Ä}εDÄIåài{γζðδKë2ô]€`é.¡g

Inputs are in the order Pile, LR and outputs in the order Leftovers, Pairs in the format ([[1],[2],[3]], [[1,1], [-2,2], [3,3]]).
-13 bytes by porting @AZTECCO's Japt answer, so make sure to upvote him!
Try it online or verify all test cases.
Explanation:

.¡ }              # Group the (implicit) input integer-list `Pile` by:
  Ä               #  Their absolute values
    ε             # Then map each group to:
          i       #  If
       Iåà        #  any values of the second input-list `LR`
     DÄ           #  is in the current group's absolute values:
           {      #   Sort the values in the group
            γ     #   And then group it on subsequent equal values
             ζ    #   Zip/transpose to create pairs of positive & negative values,
                  #   with space as default filler if the lists are of unequal length
              ðδK #   And remove all those spaces
          ë       #  Else:
           2ô     #   Split split the group into parts of size 2
    ]             # Close the if-else statement and map
     €`           # Flatten each inner list once to remove the groups again
       é          # Sort each inner list by length
        .¡g       # And also group by length
                  # (after which this result is output implicitly as result)


Acronyms can really obviously narrow your message sensors

Python 3, 89

Saved a bunch of bytes thanks to SOPython.

a=input().lower()
d=input().lower().split()
h=tuple(a)==next(zip(*d))
print(h,h&(a in d))

The most complicated part of this solution is h=tuple(a)==next(zip(*d)).
This unpacks the list d into zip and then calls next to return a tuple of the first element of each iterable passed into zip which is then compared against a tuple of each letter in a (tuple(a)).


Perl 5, 17 bytes (+1?), full program

s//.*/g;$_=<>=~$_

Try it online!
Invoke with the p flag to the perl interpreter, as in perl -pe 's//.*/g;$_=<>=~$_'.  Per the established scoring rules when this challenge was originally posted, this flag costs one extra byte.  Under more recent rules, AFAICT, it may be free.
Either way, the input strings should be supplied on separate newline-terminated lines on stdin.  Output (to stdout) will be 1 if the first input string is a substring of the second, or nothing at all if it's not.
Note that both input lines must have a newline at the end, or the program won't work correctly.  Alternatively, you can add the l command line flag to the invocation to make perl strip the newlines; depending on the scoring rules in effect, this may or may not cost one extra byte. Note that using this flag will also append a newline to the output.
Original version (snippet, 18 bytes / chars)
$x=~s//.*/g,$y=~$x

Input is given in the variables $x and $y, result is the value of the expression (in scalar context).  Note that $x is modified in the process.
(Yes, I know using $_ instead of $x would let me save four chars, but doing that in a snippet that feels a bit too cheesy for me.)
How does it work?
The first part, $x=~s//.*/g, inserts the string .* between each character in $x.  The second part, $y=~$x, treats $x as a regexp and matches $y against it.  In Perl regexps, .* matches zero or more arbitrary characters, while all alphanumeric characters conveniently match themselves.


Perl 5, 81 bytes
A naive approach (just shuffling per the specs). Doubtless someone will find a shorter way to do it (even in Perl 5, I mean).
{while(@_){for(1..($.=pop)){push@{$a[$_]},pop}push@{$a[0]},$.}$,=$/;say@$_ for@a}

This is a subroutine, but what it prints (not returns) is the shuffled deck. It requires -M5.01 (which is free).
$ perl -M5.01 -e'sub{while(@_){for(1..($.=pop)){push@{$a[$_]},pop}push@{$a[0]},$.}$,=$/;say@$_ for@a}->(9,8,7,6,5,4,3,2,1,0)'
0
1
3
7
2
4
8
5
9
6

It also adds extra newlines in various places (depending on the deck), but there's… well, nothing technically in the specs forbidding that. :-)


Tips for restricted source in Powershell

Alternatives To Single And Double Quotes
{A}  #Normal Curly Braces; This makes a scriptblock, but the ToString prints the contents
‘B‘  # Left Single Quotation Mark              0x2018
’C’  # Right Single Quotation Mark             0x2019
‚D‚  # Single Low-9 Quotation Mark             0x201a
‛E‛  # Single High-Reversed-9 Quotation Mark   0x201b
“F“  # Left Double Quotation Mark              0x201c
”G”  # Right Double Quotation Mark             0x201d
„H„  # Double Low Quotation Mark               0x201E

PS C:\> {A}
A
PS C:\> ‘B‘
B
PS C:\> ’C’
C
PS C:\> ‚D‚
D
PS C:\> ‛E‛
E
PS C:\> “F“
F
PS C:\> ”G”
G
PS C:\> „H„
H

Yes, these work! But What's better? The quotes single quotes and double quotes act as their respective normal quotes, (') and ("), and {} behave like single quotes ('). Thus:
$x="A Variable"
‘$x‘
’$x’
‚$x‚
‛$x‛
“$x“
”$x”
„$x„
{$x}

outputs:
$x           # ‘$x‘
$x           # ’$x’
$x           # ‚$x‚
$x           # ‛$x‛
A Variable   # “$x“
A Variable   # ”$x”
A Variable   # „$x„
$x           # {$x}

As a final useful bit; you don't even have to match the starting and ending quotes, so long as they are of the same type (single/double). Meaning these:
‘$x‛
‚$x'
”$x“
„$x"

Are all perfectly valid, and output like so:
$x           # ‘$x‛
$x           # ‚$x'
A Variable   # ”$x“
A Variable   # „$x"

Alternative Dashes and Uncommon Whitespace
In addition to the additional quotes characters above, PowerShell recognizes some special dashes as equivalent to the hyphen (-):
5–4  # EN DASH          0x2013   [–]
3—2  # EM DASH          0x2014   [—]
1―1  # HORIZONTAL BAR   0x2015   [―]

Powershell also recognizes two other uncommon whitespace characters:
NoBreakSpace   0x00A0
NextLine       0x0085

These were found by @ZaelinGoodman's experiment here
If anything changes, or if you want to see the specifics of how these work, you can find the source code for this handling in the PowerShell Github
I made this community wiki, so this list can be freely updated.


05AB1E, 33 bytes (Fine on Empty Input)

Dg0Qiq}•ï“ë™µyê!•36BQi7ç“+30™‹“J,

Try it online!

05AB1E, 30 26 bytes (Fails on Empty Input)

-4 thanks to Adnan

•ï“ë™µyê!•36BQi7ç,“+30™‹“,

Try it online!

•ï“ë™µyê!•36B                  # UUDDLRLRBABA in base-214, converted back to base-36.
             Qi                # If implicit input is equal to...
               7ç,             # Print 7 converted to a character to the console (bell sound)...
                  “+30™‹“, # Print +30 lives.

Disclaimer: Bell sound does not play on TryItOnline, maybe ask Dennis if one of his servers somewhere is pinging when you run it.


JavaScript (ES6),  142 ... 122  121 bytes
Expects an array of characters, e.g. ['5','1','2']. Returns 0 or 1.
a=>a.map(n=>D=D.map((_,i)=>D['504405076067'[d*6+i>>1]^i],p+=[w=a.length,-w,1,-1][d=D.indexOf(n)]),p=0,D=[...'254316'])|!p

Try it online!
How?
The array D[] holds the face values in the following order:
 index |    0   |    1   |    2   |    3   |    4   |    5
-------+--------+--------+--------+--------+--------+--------
 face  |  front | behind |  left  |  right |   top  | bottom

We start with D = ['2','5','4','3','1','6'], which is the initial orientation of the die as described in the challenge, using this encoding.
The direction d of the next move is the 0-indexed position of the new top face in D[]:
 index (d) |   0   |   1   |   2   |   3
-----------+-------+-------+-------+-------
 direction |  up   |  down | right |  left

When moving towards direction d, the i-th face in the updated die is the face at the following position in the previous die:
   i = | 0 | 1 | 2 | 3 | 4 | 5
-------+---+---+---+---+---+---
 d = 0 | 5 | 4 | 2 | 3 | 0 | 1
 d = 1 | 4 | 5 | 2 | 3 | 1 | 0
 d = 2 | 0 | 1 | 5 | 4 | 2 | 3
 d = 3 | 0 | 1 | 4 | 5 | 3 | 2

This table is encoded with the following expression:
'504405076067'[d * 6 + i >> 1] ^ i

Try it online!
At each iteration, we update D[] and the position p. We add \$\pm 1\$ to \$p\$ when moving horizontally, or \$\pm w\$ when moving vertically, where \$w\$ is the length of the input array (an upper bound of the distance that can be traveled in a single direction). We test whether we're back to our starting point at the end of the process.


Pyth - 27 bytes
.wC+Kc3O^Cm,240O256 3 15_PK

Obviously doesn't work online, but you can have it print color codes here.


Mathematica
A Voronoi diagram looks like this drawing, from Wikipedia, showing 19 cells, each containing a single seed point.   A cell consists of the subregion of points which the respective generating point is closer to than any of the other seed points.

The code below generates a diagram from 80 random points (in the square region bound by (-1,-1) and (1,1)).
It uses the polygon primitives (in 2D) in the diagram to build polyhedra (in 3D).  Imagine that each polygon has, just under it, a translation (-.08 in z) of itself. Think of the two polygons as the upper and lower face of a polyhedron.  "Side faces" are then added to complete the polyhedron.
Each polyhedron is then translated outwards, from the center of the image, on the xy plane; it moves away from the middle. The magnitude of the translation varies directly with the distance between the polyhedron's original generating random point and the center of the screen. This "spreading out" of the polyhedra in the xy plane results in crevices.
crackedMud[1]

crackedMud[65535]

Code
ClearAll[polyhedronFromPolygon, voronoiPolygons, generatingPointFromPolygon, crackedMud]

(* polyhedronFromPolygon returns a single polyhedron from a polygon *)

polyhedronFromPolygon[polygon_] :=
 Module[{twoPolygons, verticesOfUpperPolygonCell, nVertices, n = 1},
 verticesOfUpperPolygonCell = Join @@ (polygon[[1]] /. {x_, y_} :> {{x, y, 0}, {x, y, -.08}});
 (* number of vertices in a single *Voronoi* cell *)
 nVertices = Length[verticesOfUpperPolygonCell]/2;

(*vertex indices of the upper and lower polygon faces *)
twoPolygons = Select[Range@(2*nVertices), #] & /@ {OddQ, EvenQ};

(*vertex indices of a rectangular face of the polyhedron *)
While[n < nVertices + 1, AppendTo[twoPolygons,
    {twoPolygons[[1, n]], twoPolygons[[2, n]],
     twoPolygons[[2, If[n + 1 < nVertices + 1, n + 1, 1]]],
     twoPolygons[[1, If[n + 1 < nVertices + 1, n + 1, 1]]]}]; n++];
(*the graphics complex returned is a polyhedron, even though it says Polygon *)
 GraphicsComplex[verticesOfUpperPolygonCell, Polygon[twoPolygons]] ]

(* takes two dimensional coordinates and returns all of the cells of a Voronoi diagram *)

voronoiPolygons[pts_] :=
Module[{voronoiRegion, data},
  voronoiRegion = VoronoiMesh[pts, ImageSize -> Medium,
  PlotTheme -> "Lines", Axes -> True, AxesOrigin -> {0, 0}];
  data = Join @@ (MeshPrimitives[voronoiRegion, 2][[All, 1]] /. {x_, y_} :> {{x, y, 0}, {x, y, .04}});
 (* the mesh primitives are the polygons *)
  MeshPrimitives[voronoiRegion, 2]]

(* Returns, in 3D, the point which was used to generate the nth Voronoi cell. *)
generatingPointFromPolygon[n_, points_, pgons_] :=
 FirstCase[points, {x_, y_} /; RegionMember[pgons[[n]], {x, y}] :> {x,y,0}]

crackedMud[seedNumber_] :-
 Module[{pts, pts3D, geometricImage, nPts, polygons, polyhedra, centerPtinImage},
  SeedRandom[seedNumber];
  nPts = 80;
  pts = RandomReal[{-1, 1}, {nPts, 2}];
  pts3D = pts /. {x_, y_} :> {x, y, .0};
  polygons = voronoiPolygons[pts];
  polyhedra = polyhedronFromPolygon /@ polygons;
  centerPtinImage =   (Mean /@ (PlotRange /.
        AbsoluteOptions[
         Graphics3D[{polyhedra, Blue, Point@pts3D}, Axes -> False,
         Boxed -> False]])) /. {x_Real, y_, _} :> {x, y, 0};
  geometricImage =
  Graphics3D[{RGBColor[0.75, 0.75, 0.8], EdgeForm[Darker@Gray],
        (* # is the nth polygon which yields the nth polyhedron *)
        (* generatingPointFromPolygon returns the point the generated the #th polygon *)

     GeometricTransformation[{polyhedronFromPolygon[polygons[[#]]]},
        TranslationTransform[(generatingPointFromPolygon[#, pts, polygons] - centerPtinImage)/5]] & /@ Range@nPts},
         Axes -> False,  Boxed -> False, ViewPoint -> {0., -1, 1.5},
         Background -> Black, ImageSize -> 1200];

     (*ImageTrim returns a 500 by 500 pixel clip from the center of the image *)
     ImageTrim[
        (*ImageEffect speckles the image *)
        ImageEffect[Rasterize[geometricImage], {"Noise", 1/5}],
     {{250, 250}, {750, 750}}]
  ]


Mathematica, 302 bytes

Golfed version:

Unprotect@Null;Null=0;f[1,_,_,_]={,,,,};f[r_,a_,n_,d_]:=(f[r,a,n,d]=l={∞,,,,};f[r,a,n,d]=#&@@MinimalBy[{If[r>74,{,,,,1}+f[r-50Min[⌈r/50⌉-1,10],a,n,d],l],If[r>124,{,,1,,}+f[r-1,a,n,d+1],l],If[d>0,{,,,1,}+f[r+1,a,n,d-1],l],If[a>0,{,1,,,}+f[r-2,a-1,n+1,d],l],If[n>0,{1,,,,}+f[r+2,a+1,n-1,d],l]},Tr])

Normal version:

Unprotect@Null; Null = 0;
f[1, _, _, _] = {, , , ,};
l = {\[Infinity], , , ,};
f[r_, a_, n_, d_] := (
  f[r, a, n, d] = l;
  f[r, a, n, d] = # & @@ MinimalBy[{
      If[r > 74, {, , , , 1} +
        f[r - 50 Min[\[LeftCeiling]r/50\[RightCeiling] - 1, 10], a, n,
          d], l],
      If[r > 124, {, , 1, ,} + f[r - 1, a, n, d + 1], l],(*
      downvote one more *)
      If[d > 0, {, , , 1,} + f[r + 1, a, n, d - 1], l],
      (* un-downvote *)
      If[a > 0, {, 1, , ,} + f[r - 2, a - 1, n + 1, d], l],
      (* un-accept. -2 rep *)
      If[n > 0, {1, , , ,} + f[r + 2, a + 1, n - 1, d], l]
      (* accept. +2 rep *)
      }, Tr]
  )

Note:

Test this on https://sandbox.open.wolframcloud.com/ - paste the code, press Shift+Enter, then enter f[101,3,2,10] for example for first test case, then press Shift+Enter.
Use Block[{Null=0}, ...] can save some bytes, but I haven't test that.
Sometimes $IterationLimit=$RecursionLimit=∞ is necessary to get correct result.
The function will return {∞,0,0,0,0} or similar (that is, the sum of elements in list is infinite) when it is impossible, and a list with format similar to that in the sample output when it is possible.


CJam, 25 bytes - 83 removed = -58

Since Java doesn't have multiline strings nor significant indentation, we can simply remove all leading spaces. Also, since there won't be any comments, and statements will not be split across lines (as per the OP's comments), I think I should be able to remove all newlines as well.

That makes for safe and short code with pretty decent savings for the test file:

q_,\N/{S\+e`1>e~}%_oNos,-

Test it here.

For the test case it yields

class Condition {public static void main(String[] args) {boolean learning = true;if (learning == true) {System.out.println("Java programmer");}else {System.out.println("What are you doing here?");}}}
83


Count the number of fields in each csv record

Stax, 19 12 bytes

èJ§3‼}vAà○L>

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

_'"/    split *all* of standard input by double quote characters
2::     keep only the even numbered elements
|j      split on newlines (implicitly concatenates array of "strings")
m       for each line, execute the rest of the program and output
  ',#^  count the number of commas occurring as substrings, and increment

Run this one


Mathematica, 42 bytes

0!=##&@@d&&##&@@((d=IntegerDigits@#)∣#)&

I think 0!=##&@@d&&##&@@ is a new low in readability for Mathematica...

Explanation

Some of the basic syntactic sugar used here:

& has very low precedence and turns everything left of it into an unnamed function.
&& is just the And operator.
# is the argument of the nearest enclosing unnamed function.
## is a sequence of all of the function's arguments.
@ is prefix notation for function calls, i.e. f@x == f[x].
@@ is Apply, which passes the elements of a list as individual arguments to a function, i.e. f@@{a,b,c} == f[a,b,c].

With that out of the way...

(d=IntegerDigits@#)

This should be fairly self-explanatory: this gives us a list of the input's decimal digits and stores the result in d.

(...∣#)

This tests the input for divisibility by each of its digits (because the divisibility operator is Listable). This gives us a list of Trues and Falses.

...&@@...

We apply the function on the left-hand side to the list of booleans, such that each boolean is a separate argument.

...&@@d

We apply another function to d, so that the individual digits are given as separate arguments. The function is 0!=##&, i.e. Unequal[0, d1, d2, ...]. It checks that all the digits are distinct (and that they are distinct from 0 but that's given by the challenge, and if it wasn't, it wouldn't be a divisor anyway). 0!=##& is really just a 1-byte saver on using Unequal itself, and it works because there's a 1-byte element (0) that we know is not present. So this first thing checks that the digits are unique. Let's call this result U

...&&##

Again, this is really just shorthand for And[U, ##]. With ## being a sequences, the individual booleans from the initial divisibility check are expanded into the And, so we get And[U, d1∣n, d2∣n, ...] which checks that both the digits are unique and each digit divides the input.


CJam, 67 58 bytes

' qN/';f/ff+z_.{[z,):TS*'|+f.e|T'-*'++:T\(T@~T]}z{s_W=\N}/

Try it online in the CJam interpreter.


Build an interpreter for "Goggle kids Code"

Python 2, 131 126 123 110 104 bytes
Saved 13 bytes thanks to @dingledooper's approach of flattening nested list using backtick.
Saved 2 bytes thanks to @l4m2

p,t=0,[0]*100
for i in`input()`:
 if"/"<i:i=int(i);p+=i/3-1
 if i<2:t[p:p+2]=cmp(*t[p:p+2])==i,0
print t

Try it online! or Verify all test cases
Takes input from STDIN, where /\>=x are replaced with 6210*
Big idea:
Python 2 input() implicitly evaluates the string read from STDIN. Thus, reading modified input like ((6,1)*4,2)*13 returns a nested tuple of integers, aka
((6, 1, 6, 1, 6, 1, 6, 1), 2, (6, 1, 6, 1, 6, 1, 6, 1), 2, ...)

Note that loops containing single instruction must be terminated with comma, e.g (1,)*10.
Now that all loops have been automatically unrolled for us, we just have to flatten the resulting tuple, and decode the instructions.
To flatten the nested tuple, we simply convert it to string, then takes all numerical characters.


05AB1E, 9 bytes

DLImDŠÖÏO

Try it online!

Explanation

Example input 46656, 3

D          # duplicate first input
           # STACK: 46656, 46656
 L         # range [1 ... first input]
           # STACK: 46656, [1 ... 46656]
  Im       # each to the power of second input
           # STACK: 46656, [1, 8, 27 ...]
    D      # duplicate
           # STACK: 46656, [1, 8, 27 ...], [1, 8, 27 ...]
     Š     # move down 2 spots on the stack
           # STACK: [1, 8, 27 ...], 46656, [1, 8, 27 ...]
      Ö    # a mod b == 0
           # STACK: [1, 8, 27 ...], [1,1,1,1,0 ...]
       Ï   # keep only items from first list which are true in second
           # STACK: [1, 8, 27, 64, 216, 729, 1728, 5832, 46656]
        O  # sum
           # OUTPUT: 55261


Pyth, 17 16 bytes

-1 byte thanks to isaacg!

hf!ff>Y>YZUYT+./

Try it online!

Explanation

hf!ff>Y>YZUYT+./
              ./    Take all possible disjoint substring sets of [the input]
             +      plus [the input] itself (for the null string case).
 f                  Filter for only those sets which
  !f        T       for none of the substrings
    f  >YZUY        is there a suffix of the substring
     >Y             lexographically smaller than the substring itself.
h                   Return the first (i.e. the shortest) such set of substrings.


Pyth, 13 bytes

L+]/bYyM-b]Yy

Test suite.

How it works

L+]/bYyM-b]Yy
L               define a function y with argument b:
   /bY              list 1: count how many [] can be found in b
  ]                         wrap into singleton
        -b]Y        list 2: filter out [] from b
      yM                    apply y (this function) to each
 +                  concatenate the two lists above
            y   apply y to the input


Python 2, 90 79 73 bytes

-6 bytes thanks to xnor

L=range(2,input()+1)
while L[0]*2<=L[-1]:L.remove(L[0]*2);L=L[1:]
print L

Takes the input number on stdin. Ideone it!

Explanation

We construct the initial list from the input number and store it in L. Next, loop while the last number is greater than or equal to 2 times the first number and remove 2 times the first number from the list. This will always be the next number divisible by L[0]. L=L[1:] takes off the first number as well. When the condition is no longer true, no further removals can be made, and the list is printed.


Python 3, sort by greatest number, n = 92 121
Thanks to Martin Büttner for a suggestion that unexpectedly improved the maximum n reached.
Last output:
[2, 3, 11, 12, 29, 30, 38, 39, 83, 84, 92, 93, 110, 111, 119, 120]
[1, 4, 10, 13, 28, 31, 37, 40, 82, 85, 91, 94, 109, 112, 118, 121]
[5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 86, 87, 88, 89, 90, 113, 114, 115, 116, 117]
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81]

The algorithm is the same as my previous answer, quoted below:

There are k bins that have both the numbers in it so far and the numbers that can't go in it anymore. At each depth in the iteration (it's basically a depth-first search), the bin ordering is shuffled and the next number (nextN) is (sequentially) put into the bins that can take it and then goes one step deeper. If there are none, it returns, backing up one step.

...with one exception: the bin ordering is not shuffled. Instead, it is sorted in such a way that the bins with the greatest number come first. This reached n = 121 in 8 seconds!
Code:
from copy import deepcopy
from random import shuffle, seed
from time import clock, time
global maxN
maxN = 0
clock()

def search(k,nextN=1,sets=None):
    global maxN
    if clock() > 600: return

    if nextN == 1: #first iteration
        sets = []
        for i in range(k):
            sets.append([[],[]])

    sets.sort(key=lambda x:max(x[0]or[0]), reverse=True)
    for i in range(k):
        if clock() > 600: return
        if nextN not in sets[i][1]:
            sets2 = deepcopy(sets)
            sets2[i][0].append(nextN)
            sets2[i][1].extend([nextN+j for j in sets2[i][0]])
            nextN2 = nextN + 1

            if nextN > maxN:
                maxN = nextN
                print("New maximum!",maxN)
                for s in sets2: print(s[0])
                print(time())
                print()

            search(k, nextN2, sets2)

search(5)


Husk, 2 bytes

πN

Try it online!

Explanation

N is the infinite list of natural numbers [1,2,3,4,...
π is Cartesian power.
Result is an infinite list of lists.
Each list of the desired length occurs exactly once because π is cool like that.
Input and output are implicit.


Print the fingering for the note on a saxophone

Python 3, 528 525 bytes (ouch!)

Not the prettiest code in the world, but I think it works. Calculates the shortest overall distance by trying all possible fingering combinations, so also not the most efficient.

from itertools import*
def f(x,y):a,b=x.split('|');c,d=y.split('|');return len(set(a)^set(c))+len(set(b)^set(d))
print(";".join(min(product(*["zd|zb zc|zb z|zb zb|zb z|z z|za z|12 z|1 z|2 z| za| 12| 12|g&1i|&1|1&1|2 1| 2|&1|f |&o3| oz|z oz|za oz|12 oz|1 oz|2 oz| oza| o12| o12|g&o1i|&o1|1&o1|2 o1| o2|&o1|f o| of| oef| oef|e oefg|".replace('z','123').split()["C D EF G A B".find(n[0])+" #".find(n[1:-1])+12*int(n[-1])-46].split('&') for n in input().split(';')]),key=lambda x:sum(f(x[i],x[i+1]) for i in range(len(x)-1)))))

Not many tricks. Saved a bit by a string-replace on "123". Simplified distance calculation by doing each half separately. Note name to pitch calculation is fairly tight but should be able to golf the rest down.


Cubically, 3 bytes

rp▦

Try it online! You can use this to print a random cube.

Explanation:

r    read cube from stdin
 p   set PRINTMOVES flag to display moves as they are performed on the cube
  ▦  insert moves to solve the cube at the current point in the program

Capitalize the P to see prettier output (e.g. RLD'U2 as opposed to R1L1D3U2).


T-SQL, 49 bytes

According to the FAQ the database will be updated on Sunday 0300 UTC so this is when you'll get your result. So I'm hoping you're a patient lazy (not really) narcissist (not really).

select Score,ViewCount
from Posts
where Id=111115

https://data.stackexchange.com/codegolf/query/632441/tell-me-about-my-question


Python 2, 35 Bytes

I decided to use the obvious sequence A000027, which essentially has the formula n ;) If you run the following code:

#print'n'
n=1
exec'print n;n+=1;'*8

You get the output:

1
2
3
4
5
6
7
8

And if you take the 8 characters from my source code (0-indexed), you get this:

print'n'

Which simply prints n.

If you were hoping for a more exciting answer, here's a Python 2 solution for n^2, i.e. A000290:

#p  r    i      n        t          '            n              ^                2                  '
n=1
exec'print n*n;n+=1;'*10


C++11

Excuse the variable names.

Calculates hamming distance between each pair of words then tries replacing characters in words with '-', and calculates hamming distance between the word with '-' and the words without (that had a low enough hamming distance). See comments for details.

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <fstream>
#include <ios>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

// Calculates hamming distance between a and b, both of which are length m
inline int fries(const std::string &a, const std::string &b, int m){
    int c = 0;
    for(int i = 0; i < m; ++i)
        a[i]==b[i] || ++c;
    return c;
}
using namespace std;

int main(int eggs, char **bagels){
    ios_base::sync_with_stdio(false);
    // make sure proper number of arguments are passed
    assert(eggs == 4);

    int m, k;
    // read in m (word length) and k (number of '-'s)
    sscanf(bagels[2], "%i", &m);
    sscanf(bagels[3], "%i", &k);

    // bacon will store all words that are of length m
    vector<string> bacon;
    bacon.reserve(500000);

    // Save only words that are of length m
    ifstream milk(bagels[1]);
    {
        string toast;
        while(getline(milk, toast))
            if(toast.length() == m)
                bacon.push_back(toast);
    }

    // ham[i] will store the indices of strings with a hamming distance from bacon[i] that is at most k
    vector<vector<int>> ham(bacon.size());

    // Calculate hamming distance, if <=k, add to ham.
    for(int i = 0, sz = bacon.size(); i < sz; ++i){
        // Uses i+1 to ensure each PAIR is only checked once
        for(int j = i+1; j < sz; ++j){
            unsigned strip = fries(bacon[i], bacon[j], m);
            if(strip && strip <= k)
                ham[i].push_back(j);
        }
    }

    // cereal[string], where string is the matching shape, and the vector is a vector of indices of strings that are matched by string
    map<string, vector<int>> cereal;
    for(int i = 0, sz = ham.size(); i < sz; ++i){
        // skip words that are not similar enough to other words
        if(ham[i].size() == 0) continue;

        // Iterate through all versions of bacon[i] with k '-'s
        // THIS ONLY ITERATES THROUGH COMBINATIONS NOT PERMUTATIONS
        vector<bool> cream(m);
        fill(cream.begin()+k,cream.end(),true);
        do{
            std::string juice = bacon[i];
            // Add in '-'s
            for(int i = 0; i < m; ++i){
                if(!cream[i]) juice[i] = '-';
            }
            // Ensure that this pattern has not yet been processed
            if(!cereal.count(juice)){
                // For each of the words with hamming distance<=k, check hamming distance with the matching shape
                // If hamming distance == k, then it matches, so save to cereal
                for(int j = 0, ssz = ham[i].size(); j < ssz; ++j){
                    if(fries(juice, bacon[ham[i][j]], m) == k)
                        cereal[juice].push_back(ham[i][j]);
                }
                // In the case that there ARE matches, put the index of the original string at the end
                if(cereal.count(juice))
                    cereal[juice].push_back(i);
            }
        }while(next_permutation(cream.begin(), cream.end()));
    }
    // Sorts all the matching shapes by number of matches
    vector<pair<string, vector<int>>> orange_juice;
    copy(cereal.begin(), cereal.end(), back_inserter(orange_juice));
    sort(orange_juice.begin(), orange_juice.end(), [](const pair<string, vector<int>> &a, const pair<string, vector<int>> &b){
        return a.second.size() > b.second.size();
    });
    // Iterate through sorted matching shapes, print
    for(auto cake:orange_juice){
        // bacon[cake.second.back()] is the original string from which the pattern was derived
        cout << cake.second.size() << ": " << cake.first << ": " << bacon[cake.second.back()];
        // do not print original string twice
        cake.second.pop_back();
        // print other strings
        for(auto coffee:cake.second){
            cout << "," << bacon[coffee];
        }
        cout << "\n";
    }
    return 0;
}


Python 2, 48 bytes

f=lambda l,z=5:z and max(l,f(zip(*l)[::-1],z-1))

Try it online!

Takes the largest of the four rotations in terms of list comparison. Based on FlipTack's solution.

The code uses Python 2's ability to compare objects of different types. The base case value of 0 is harmless for max because it's smaller than any list. Also, zip produces a list of tuples while the input is a list of lists, but tuples are bigger than lists so the input list-of-lists is never a contender. This is why we rotate 5 times rather than 4, so that we get back to a tuplified version of the initial list. (Taking a list of tuples would also work, if that's an allowed form of input.)


Python, 81

def f(L):
 if L:i=L.index(max(L));L=f(L[:i])+[~i*(i-len(L))]+f(L[i+1:])
 return L

A divide-and-conquer solution. The maximum element M seeps all the way down the pyramid, splitting it into a rectangle of M's and two subpyramids.

* * * M * *
 * * M M *
  * M M M
   M M M
    M M
     M

So, the overall result is the output for the left sublist, followed by the area of the rectangle, followed by the output for the right sublist.

The input variable L is reused to stored the result so that the empty list is mapped to the empty list.

The constructs in solution are wordy in Python. Maybe some language with pattern-matching can implement the following pseudocode?

def f(L):
 [] -> []
 A+[max(L)]+B -> f(A)+[(len(A)+1)*(len(B)+1)]+f(B)


Python, 429 chars - 10% bonus = 386.1

Numbers are kept in little endian order, which is stretching the rules a bit but makes for easier processing.  Maximum number size is 32 bits.  Addition is standard, subtraction is implemented by x-y = x+~y+1 (throwing away the carry out of the 32 bits), multiplication is done using the Russian Peasant algorithm, and division is done with repeated subtraction.

z,i='01'
P=z*32
def A(x,y):
 r='';c=z
 for a,b in zip(x+P,y+P):k=(a+b+c).count(i);r+='0101'[k];c='0011'[k]
 return r[:32]
S=lambda x,y:A(A(x,''.join(chr(ord(c)^1)for c in y+P)),i)
def M(x,y):
 r=''
 while y:
  if y[0]==i:r=A(r,x)
  x=z+x;y=y[1:]
 return r
def D(x,y):
 x=(x+P)[:32];y=(y+P)[:32];r=''
 while x[::-1]>=y[::-1]:r=A(r,i);x=S(x,y)
 return r
def B(x,y,o):r=[A,S,M,D][o](x,y).rstrip(z)[:len(x)+len(y)];return[r,z][r=='']

B is the function of interest, here is its result on the test cases:

print B('01010','10101',0)
11111
print B('01111','01010',1)
00101
print B('0100','0001',2)
00001
print B('0101101','1000100',3)
101


C (gcc)

Around 0.6 sec for 1,000,000.

int modpow(long b,int e,long n){
	long r=1;
	while(e){
		if(e&1) r=r*b%n;
		b=b*b%n;
		e>>=1;
	}
	return r;
}
float f(int a,int b){
	int ln=1;
	for(int p=2;p<=a;p*=ln,ln++);
	int* primes = malloc((a+1)*(sizeof(int)));
	int** factors = malloc((a+1)*sizeof(int*));
	primes[0] = 0;
	primes[1] = 0;
	for(int i=2;i<=a;i++){
		primes[i] = 1;
		factors[i] = malloc(ln*sizeof(int));
	}
	factors[1] = malloc(sizeof(int));
	factors[1][1] = 0;
	for(int p=2;p*p<=a;p++){
		if(primes[p]){
			for(int j=p*2;j<=a;j+=p){
				primes[j] = 0;
				factors[j][0]++;
				factors[j][factors[j][0]] = p;
			}
		}
	}
	int count1 = 0;
	int count2 = 0;
	for(int p=2;p<=a;p++){
		if(!primes[p]) continue;
		count2++;
		int n=p-1;
		int m=p-1;
		int prim=1;
		for(int j=1;j<=factors[n][0];j++){
			int q=factors[n][j];
			if(modpow(b,n/q,p)==1){
				prim=0;
				break;
			}
			while(m%q==0){
				m/=q;
			}
		}
		if(m>1){
			if(modpow(b,n/m,p)==1){
				prim=0;
			}
		}
		count1 += prim;
	}
	return (float)count1/count2;
}

Try it online!


This is impossible

Going through all of the languages in the langbox:

The tcl programming language consists of words separated by spaces. The space character is not in the toolbox, so no valid programs can be written.
Str programs by default transform input. In order for them to do anything when given no input, the ; character is required, which is not in the toolbox.
The only means for a program in scheme-chez to do anything is by calling a function using parentheses. All scheme-chez programs therefore need the ( character, which is not in the toolbox
Brain-Flak programs need balanced brackets. The only bracket character in the toolbox is ), so no programs containing balanced brackets are possible.
Similar to scheme, maxima programs require parentheses to do anything.
Java programs require the { or -> character sequences to declare a function (and all full programs need at least one function), none of which are in the toolbox.
Condit programs require the word when, which contains the "e" character, which is not in the toolbox.

Proofs of impossibility are allowed as answers


Smalltalk, 1098 primes

First off, nice hard question - as evidenced by the lack of non-trivial responses thus far.

I had a solution cooking at work, but had to wait for the long weekend to have time to clean it up a bit. Even so, it's quite "heavy", so excuse the length of this answer - thankfully this isn't a code-golf question. There were plenty of little gotchas along the way, but I'm pretty sure it's bug-free now, though there is plenty of room for improvement and fine-tuning.

Language

My language of choice for this sort of thing is Smalltalk - the superior debugging and the ability to test-as-you-code beats anything else I know. Plus, even non-coders can read it and understand the basics of what's going on. I've limited the code below to the interesting part, because I thought the approach and results would be more interesting than the boilerplate code, but a file-out of the full code is pasted here if anyone wants to try it out (just save as a *.st and file it in from a file browser in Pharo). I used Pharo 4.0, which is FOSS and can be downloaded from pharo.org for Win/Mac/Linux. Also happy to paste the full code here, but I took the "should include the output text and your code" as a suggestion - let me know if I'm wrong.

Approach

So, my thinking was, what if you could start in the middle, stuff as many long primes as you could in the box, and work your way outwards from there? Let's start with a Box object, containing a matrix of characters, and then use a Stuffer object to try to fill it up by finding the best Insertion (another object) for each point in the matrix and for each prime (starting with the long ones). Pharo has nice Matrix and Point classes with a bunch of useful methods (though the matrix way of using row-major notation versus using x-y-coordinates of points can get a little confusing if you're not careful).

The basic steps of my algorithm are:

Create a Stuffer instance for given dimensions.
Have the stuffer initialise its box to size 5x5 (unless dimensions
are smaller).
Ask the Stuffer to stuff its box.

Iterate over a list of primes from largest to smallest.
Iterate over all points in the matrix.
Find the best spot to insert the prime, and insert if possible.

While the box can "grow" (until the target dimensions are reached),
increase it by one row/column on each side and copy the old contents
into the middle of the bigger one, then go to step 3.

Configurable:

The dimensions
The largest prime to start from
The "rating" of insertions (when choosing from multiple possible places to insert a prime)

For the matrix below, I used 80x60, primes below 20,000 (since the combined length of those is just under 10,000 characters, i.e. the maximum for a stuffed, though invalid, 100x100 box), and, after some experimentation, the following rating for each insertion:

(each accidentalPrimes size * 1) + (each numberOfOverlaps * 2)

where accidentalPrimes are the perpendicular primes "accidentally" created when inserting between neighbouring primes, and numberOfOverlaps is how many characters are overwritten (e.g. when adding a 3 at the end of 11 to insert 113). I initially had it weighted more towards accidentalPrimes, but got a few more primes in the box by doing it this way - not entirely sure why (feel free to test/tweak).

Result

| 1  3449 8    19489 8 7 9277 2 7 419  6   9533   19211    19373 4  79379 9 6 1 1|
|8861 1 7 26701 6   19219 6  97577 6 319211  84631   3 9649  8  19207 6 7 10399 9|
| 7 8 98669    19469 5 0  19301 2 6997 4   9787   19441  7 18899 9  2 47297 1 0 0|
|8839 8 7  1613 5 6  149837  0 97213 319289  6 8291  915991 431  909113 1 3382373|
| 7 7607 1 9 9 19543  1 8  3779   5743  6 19813  1946981    19423  139 9 9431 1 1|
|  6911 8933 2 9  9 1 4198013  9497   19447    1093 9 1194899 8  569 4 487749433 |
|  1 1 1 3 0 5653 19583 5  101429 4691  4 119813 9923  9 5 9  1811 47293 3533 1 1|
| 8849 8 86959 0 1  0 4 195071 7589 19429 5 1  4    3863 219763  9 2 1 9391 87833|
|  9 813613 7  719 19471   6 19727 809 7 19759 619867 6 988069 1 5 11 191 9 1 9 8|
|541 0 7 3547 1  70919 93715816451 19609 3  6  3 41  757219717 9803 9 9 9283  4 7|
|  3 1 9  1  691 6 4 177493124562997 7 1 719483  152993 8 9 6173 7 4871 0 7 15797|
|5171 373 9 1 4  318191 263 19843  19919  8 19889953 4  169639 9679 6 8887  9    |
| 8 8 1  5449 2 9 9399647333  7907  8 8 677   2 6 6 9967 101 8111 7 7 3 7 1907 1 |
| 7 67901 2 2 757 8 5 9 119759 7499 19853 19751 19913  59879 0  6469 171179 6 487|
|8747 0 9 78167 4 8 78839  6 99317  1 3 9 9 9   9  16993 7 8117 3373 9 9  8093 9 |
| 3 913457  31193 9 107 7 198439   9 19861 19697  99125471 1   16979 2819 0  9 1 |
|9 1951 0 1879 1 7 1 1 6569 853 18397  83 8 656269159547193329 97871 7 2  1 4337 |
|14831 9157 6449 0 9 9613 8 15619 148436196977821 19597 9 9 6907 8 383 16573 1  1|
|7 9 8   4518803 15647 9 941 19661 19963 149 19937  43913 2393 1433   1 1 1 9 9 8|
|3 1 3613719596827 8 2 6 5163998629 467 6271    13967 29399 51673 9 15973 87473 9|
| 9127 9  927191 19157 0 8 66938969 176597 19949 5779513 1319 6 92779 14717 3 7 1|
| 1  98849 8  9  9  8  3371771169929  169937 4 65519 79769 9 906473 58699 9 78173|
| 8    0 6 9907 682771709 9  9 3319763 947387669 479978309 8597 35393 369731 5   |
| 6211 1823 1 318691 96918839 9 19 918481 1997911733 58271 6 2 9 1  1  92219 661 |
| 7 8 7349  9 369739 7297 1 8641 4 12983    6 61991 619793 7 3 8297  15791 0 3   |
| 9 8 1 1 1 5  619 8 510589 396932999 7 5897537 997379 6   39313 4 439 69911   1 |
|1  64969 9 54139 7069 739 99639719 58693 4951 977   9 9151 8 9 6689 257 4 37199 |
|8  9 0 37529 9 4 91193  6 6 9 7  6 8 11117 3970331  11969963 661911661 727  9 3 |
|3613 0 8 5   3 2 8 9 1 499787 9137 71 19997 971939 13999 787 0 9 9  701 7 151 8 |
|7 8 6961 97607 1 15569 9 8 1 1 1171 99929 99733 1759 9817931 3 8941  193  968819|
|9 8 0 6    0 99767 8 769 88969 9859 979871393 1733 9377113 95111 5  8 2 94033  1|
| 9041 6 14519   1063 6 937 8 8 8999 92993171 11519 313 89417 7 317 5233 4 3  9 8|
|433  8179 6113 8971  3191 7559 17 63313 939793919 971 198769 5693 9 7 14657  6 7|
| 9  1  725189 1 7591139 9 93911 3919 9257 33739 9293 29 1973 2  9161 9511  17239|
|349 87151 99349 57529 7 36637 6359 81999119371933 4 98573 7549 6317 6619 8 9 3 3|
| 3  8 99371 8 8 374718269 1144935789717977  83177 9 233  1499 8 1571 4 8 6803 9 |
| 9 15641  3 1607  3 8 761 393388937 9    3967  9 9719 13997 1259 7 9639079 0 443|
|  1 9 2 14969 1109 8313931 8  198174119963 5 997 9 9 991 8 1217 52579  1 3911 1 |
|5281 277    1979 32909 9 986983 19991  61399991 127997 9 82939 907 571847 4 9 3 |
|  7 8  9 617 8 4 21613 2 95792383  919979 4951997317 93719 4 641379379 1 12487  |
|1 9 66959 8  8 4 3339313613 5119963  189967 359 337361 25933 83891   8 8191 7  1|
|8 7 8 61516883 1619 839 799859 2 7 19927 5 19777 6737 9769 37799 9 19079 0 9 1 9|
|57331 2 4 9 1 1  7691 9697 61 19577 6 9949 9 9 31979399 1 1 8737 509 1 49871 8 8|
|9  1 6397 109 99133 3 313888397 59419699  1986133  8387 9 988319 5 47237 7 8 9 0|
|3  62131 1  38629 8699 9 8599 953 397   736903  1991933 877 3 4799 1 1     77171|
| 1 8 8 9091 7 86491  627673 593 1  19853377 9781  8  3 76919  7  49739 1511  9  |
| 8 76991 0 938747 9 924629743 193873 2 699823 8719801 907871 19181   4 9 9 93371|
|6959 7 88867 6 7757 792383  8 9  0  1981337 3947  3 3917 2089979 9 92831 0 4 2 8|
| 4  5953 1 3739   69473 7 19709 99016787  379 9619759 196991 6 56393 9 3 82373 9|
|273613  1163  13883 919531 8  7433 6337 8893 6917   9 9 1693 8 0 7 709 93199 9 1|
|631 97159 8  181 9 6   0 0 7819753 673  9    9  9901 19699   18119 7  1 1 111779|
|9 8 0 9 0 2 7919 4419559 98179  6  9  19553 9851 4 9 9067 9857 4957 14939 9397  |
| 8753 0 3631 4 4 18973 9 7  89923 19793 1 8  3491954199497 53 2969  9 0 0 0 0 6 |
|1 9 1 5 1    5 24337 9  19603 7 9 3  4 195312373619977 9 119489 8 96293 643 0 4 |
|8 3   18461  7577 1 19541 8 3929 19463 6  3 49937 3 9 98297 71347 3 4 7 9 1 9 1 |
|87541   9 92707 9817  2 58237 1 4 6  919423 5    19403 77383 194179 9601 1 1 1 1|
|6 9 38923 4 261631 61937389 19387 390739 9 19319 6 495617 9 5  9  7  93979 8 8 8|
|9 449 5 4658147899073 7  3   60293 5  7 8231 2641930937 7 1950139511 6 0 26993 7|
|  0 0 2 34789739 1 3619501   61930959767 7 19237 7 9 9829   7    7   27773 5 7 5|
|823 7211 7 3 3 919231     9631 337 1  3    7 9 3      1 3943 19141 653 3 15971 7|

This matrix contains 1098 primes, which is a "load" of about 70%.

These are the primes (box primesUsed asSortedCollection printString):

11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 107 109 113 127 131 137 139 149 151 163 167 173 179 181 191 193 197 199 233 257 263 269 271 277 283 293 307 311 313 317 331 337 347 349 359 367 373 379 383 389 397 419 431 433 439 443 449 467 479 487 491 499 509 541 547 557 563 569 571 577 587 593 599 601 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1063 1093 1109 1117 1153 1163 1171 1181 1217 1259 1319 1361 1399 1433 1499 1511 1571 1607 1613 1619 1637 1663 1667 1693 1697 1699 1733 1759 1811 1823 1879 1907 1913 1933 1949 1951 1973 1979 1987 1993 1997 1999 2393 2459 2617 2819 2927 2939 2969 3191 3229 3343 3373 3389 3449 3533 3539 3547 3613 3617 3631 3643 3733 3739 3769 3779 3793 3797 3821 3863 3911 3917 3919 3929 3931 3943 3947 3967 3989 4337 4409 4493 4691 4799 4871 4951 4957 4967 4999 5039 5099 5101 5171 5233 5281 5347 5399 5449 5479 5653 5693 5743 5939 5953 6079 6113 6131 6173 6197 6199 6211 6271 6317 6337 6359 6397 6449 6469 6569 6571 6599 6607 6619 6653 6661 6689 6737 6779 6781 6793 6803 6823 6829 6899 6907 6911 6917 6949 6959 6961 6967 6977 6997 7069 7079 7109 7193 7211 7219 7229 7297 7307 7349 7393 7433 7499 7549 7559 7577 7589 7607 7621 7691 7727 7757 7883 7907 7919 7949 7951 8093 8111 8117 8171 8179 8191 8219 8231 8291 8293 8297 8387 8419 8537 8539 8563 8597 8599 8641 8647 8681 8689 8693 8699 8719 8737 8747 8753 8779 8831 8839 8849 8861 8863 8887 8893 8929 8933 8941 8951 8963 8969 8971 8999 9007 9041 9067 9091 9109 9127 9137 9151 9157 9161 9173 9181 9187 9199 9257 9277 9281 9283 9293 9371 9377 9391 9397 9413 9419 9421 9431 9437 9461 9463 9467 9473 9479 9491 9497 9511 9521 9533 9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661 9677 9679 9689 9697 9719 9721 9733 9739 9743 9749 9767 9769 9781 9787 9791 9803 9811 9817 9829 9833 9839 9851 9857 9859 9871 9883 9887 9901 9907 9923 9929 9931 9941 9949 9967 9973 10399 10979 11117 11519 11939 11959 11981 12487 12983 13313 13339 13463 13499 13763 13877 13883 13907 13931 13963 13967 13997 13999 14519 14657 14717 14831 14939 14969 15091 15569 15619 15641 15647 15791 15797 15971 15973 16573 16699 16937 16979 16993 17239 17333 17519 17761 17891 18119 18371 18379 18397 18461 18593 18691 18719 18757 18773 18787 18803 18839 18859 18869 18899 18911 18913 18917 18919 18959 18973 18979 19001 19009 19013 19031 19037 19051 19069 19073 19079 19081 19087 19121 19139 19141 19157 19163 19181 19183 19207 19211 19213 19219 19231 19237 19249 19259 19267 19273 19289 19301 19309 19319 19333 19373 19379 19381 19387 19391 19403 19417 19421 19423 19427 19429 19433 19441 19447 19457 19463 19469 19471 19477 19483 19489 19501 19507 19531 19541 19543 19553 19559 19571 19577 19583 19597 19603 19609 19661 19681 19687 19697 19699 19709 19717 19727 19739 19751 19753 19759 19763 19777 19793 19801 19813 19819 19841 19843 19853 19861 19867 19889 19891 19913 19919 19927 19937 19949 19961 19963 19973 19979 19991 19993 19997 21613 24239 24337 25933 26449 26701 26959 26993 27773 27919 29399 31193 32909 33739 35393 36637 36761 37199 37529 37799 38333 38629 38839 38861 38923 39293 39313 39733 43913 43943 45281 47237 47293 47297 47933 47939 48311 48761 49123 49199 49739 49871 49937 49999 51193 51673 52379 52579 54139 55313 56393 56983 57173 57331 57529 58237 58271 58693 58699 59743 59879 60293 61979 61991 62131 62873 63313 64969 65519 66491 66959 67339 67901 67993 69337 69473 69623 69697 69911 69941 70919 71347 71777 71933 75347 76163 76733 76919 76991 77171 77213 77383 77591 78167 78173 78839 78941 79379 79613 79631 79769 79967 80933 81919 82373 82939 83177 83891 84631 86491 86959 87151 87473 87541 87833 88499 88867 88951 88969 89413 89417 89519 89923 91193 91813 91997 92219 92593 92647 92707 92779 92831 93199 93371 93719 93911 93913 93971 93979 94033 94397 94399 95111 96233 96293 96587 96911 96959 96979 97159 97213 97577 97607 97787 97871 97919 98179 98297 98299 98573 98669 98837 98849 99133 99233 99317 99349 99371 99497 99733 99767 99907 99929 101429 111149 111779 119489 119759 119813 127997 149837 152993 167747 168863 169639 169937 171179 176597 179099 179111 183797 187973 188693 189473 189967 190811 191837 193813 193873 194179 195071 195319 196817 196871 196991 197273 197599 198013 198017 198439 198673 198769 199373 199679 199739 219763 261631 273613 277793 316879 318191 318691 319031 319069 319211 319289 319427 319727 319973 337361 369731 369739 390739 391753 414347 419801 439883 495617 499787 510589 519031 571847 601189 615749 616367 618719 619543 619583 619753 619763 619793 619813 619867 627673 639631 669923 698339 699823 716987 719009 719441 719483 719801 719813 725189 736903 792383 796553 799859 809339 813613 815569 819373 819457 829733 906473 907871 909113 912797 913457 914813 915641 915991 917159 918481 918679 918793 919183 919231 919381 919421 919423 919531 919559 919913 919979 927191 935639 938747 939439 943913 962971 968819 971939 976777 986983 988069 988319 991733 997319 997379 1194899 1518379 1678739 1691189 1867993 1899907 1903703 1923151 1942771 1946981 1950149 1981337 1986133 1988999 1991933 2089979 2919031 3110651 3190871 3193913 3197633 3319763 3382373 3619501 3970331 4198013 4419559 4518803 5119963 5195077 5319289 5619139 5779513 5897537 6119801 6129587 6189137 6194891 6198139 6649871 7219427 7591139 7819753 7937939 7982969 8019727 8313931 8419381 8719801 8783371 9119909 9189797 9323173 9377113 9619759 9639079 9679799 9717317 9721301 9721991 9817931 9911789 9923369 9967759 11969963 15619867 16981331 19669931 19717099 19793479 19853377 19889953 21968773 27519469 31979399 34789739 40699733 59419699 61399991 61516883 61897937 61937389 63519427 66938969 69719801 74969767 91938191 92993171 93369931 95792383 96918839 99016787 99125471 99639719 126919421 179319979 199733981 199739717 313888397 342719753 374718269 393388937 396932999 439314797 479978309 487749433 577519913 613799299 631819381 641379379 661911661 682771709 689194217 757219717 924629743 936195479 939793919 947387669 979871393 991579637 1903149343 1921376857 1945706473 1950139511 1960317529 1997911733 2641930937 3339313613 4951997317 4952523041 5163998629 7017198679 7981707577 9013119991 9119993297 9399647333 9945519919 18919323977 19031318947 19919788793 31879359403 61930959767 61960309907 91734751987 92774649739 93715816451 95479219889 98371979359 99551395387 191830198139 198012194899 198017187931 198174119963 213963819763 419801418947 819853319867 1937327699987 3189735598139 3371771169929 3491954199497 3613719596827 4658147899073 81999119371933 148436196977821 177493124562997 195312373619977 1144935789717977 656269159547193329 735547997331319937 11572771955941937959

As you can see, some of the "accidental" primes get quite long... 20 digits for the longest one. :-)

Details

To understand how it works, here is the output from doing the first few steps - inserting 19997 first (if you look in the middle of the big matrix, you'll see 19997 there as well), then down the list where there's space in the 5x5 box (> means insert going right, v means going down; anything in {} are accidentally added primes:

Insertion at: (1@1) > {} of 19997
Box 5x5 (1 prime, load: 20%):
|19997|
|     |
|     |
|     |
|     |

Insertion at: (1@1) v {} of 19993
Box 5x5 (2 primes, load: 36%):
|19997|
|9    |
|9    |
|9    |
|3    |

Insertion at: (3@1) v {} of 9973
Box 5x5 (3 primes, load: 48%):
|19997|
|9 9  |
|9 7  |
|9 3  |
|3    |

Insertion at: (1@4) > {} of 9931
Box 5x5 (4 primes, load: 56%):
|19997|
|9 9  |
|9 7  |
|9931 |
|3    |

Insertion at: (1@3) > {89, 11} of 9871
Box 5x5 (7 primes, load: 64%):
|19997|
|9 9  |
|9871 |
|9931 |
|3    |

Insertion at: (5@1) v {98713, 99317} of 7937
Box 5x5 (10 primes, load: 76%):
|19997|
|9 9 9|
|98713|
|99317|
|3    |

Insertion at: (4@3) v {} of 113
Box 5x5 (11 primes, load: 80%):
|19997|
|9 9 9|
|98713|
|99317|
|3  3 |

11 old primes: 19997, 19993, 9973, 9931, 9871, 89, 11, 7937, 98713, 99317, 113
8 new primes: 19997, 98713, 99317, 19993, 89, 9973, 113, 7937
Insertion at: (4@1) v {} of 19973
Box 7x7 (9 primes, load: 42%):
|   1   |
| 19997 |
| 9 9 9 |
| 98713 |
| 99317 |
| 3  3  |
|       |

In the insertion immediately above, the box becomes a 7x7, and is filled with the 5x5 contents before the next insertion happens. I also re-calculate the primes used at this point, because some are "freed up" due to overwriting (11 was inserted, but then overwritten by 113).

Code

Here are the most relevant parts of the code:

Stuffer class

Class side

forDimensions: aPoint
    ^self new
        width: aPoint x;
        height: aPoint y;
        initializeBox;
        yourself

Instance side

initializeBox
    box := Box width: (width min: 5) height: (height min: 5)

stuffBox
    self stuffCurrentBox.
    [self canGrow] whileTrue: [
        box growMatrixByOneUpTo: width @ height.
        self stuffCurrentBox
        ]

canGrow
    ^width > box width or: [height > box height]

stuffCurrentBox
    self class primes reverseDo: [:eachPrime |
        | string insertion |
        (box primesUsed includes: eachPrime) ifFalse: [
            string := eachPrime asString.
            (insertion := box bestInsertionFor: string) ifNotNil: [
                Transcript crShow: insertion printString, ' of ', string.
                box doInsertion: insertion of: eachPrime.
                Transcript crShow: box
                ]
            ]
        ].
    box updatePrimesUsed.

Box class

Instance side

bestInsertionFor: aString
    | insertions |
    insertions := OrderedCollection new.
    self pointsDo: [:eachPoint |
        insertions
            addIfNotNil: (self insertionOf: aString at: eachPoint isHorizontal: true);
            addIfNotNil: (self insertionOf: aString at: eachPoint isHorizontal: false)
        ].
    insertions removeAllSuchThat: [:each |
        self isInsertion: each invalidWith: aString asInteger
        ].
    ^insertions detectMax: [:each |
        (each accidentalPrimes size * 1) + (each numberOfOverlaps * 2)
        ]

insertionOf: aString at: aPoint isHorizontal: isHorizontal
    | point insertion |
    point := aPoint.
    (self canFitEndsAt: point length: aString size isHorizontal: isHorizontal)
        ifFalse: [^nil].
    (self isAlreadyThere: aString at: aPoint isHorizontal: isHorizontal)
        ifTrue: [^nil].
    insertion := Insertion at: point isHorizontal: isHorizontal.
    1 to: aString size do: [:eachIndex |
        | eachCharacter |
        eachCharacter := aString at: eachIndex.
        (self canDoInsertion: insertion of: eachCharacter at: point)
            ifTrue: [
                (self at: point) == eachCharacter
                    ifTrue: [insertion increaseOverlaps].
                point := point + (self offset: isHorizontal)
                ]
            ifFalse: [^nil]
        ].
    ^insertion

isInsertion: anInsertion invalidWith: aPrime
    | otherPrimes |
    otherPrimes := anInsertion accidentalPrimes.
    ^(primesUsed includesAny: otherPrimes)
        or: [(otherPrimes includes: aPrime)
        or: [otherPrimes copy removeDuplicates size < otherPrimes size]]

canDoInsertion: anInsertion of: aCharacter at: aPoint
    "Answer whether anInsertion of aCharacter is valid at aPoint. If so,
    also update anInsertion with any accidental insertions."

    | perpendicularSequence offset front back |
    (self at: aPoint) == aCharacter
        ifTrue: [^true].
    (self isFreeAt: aPoint)
        ifFalse: [^false].
    perpendicularSequence := OrderedCollection with: aCharacter.
    offset := self offset: anInsertion isHorizontal not.
    front := aPoint - offset.
    back := aPoint + offset.
    [self isFreeOrBorder: front] whileFalse: [
        perpendicularSequence addFirst: (self at: front).
        front := front - offset
        ].
    [self isFreeOrBorder: back] whileFalse: [
        perpendicularSequence addLast: (self at: back).
        back := back + offset
        ].
    ^perpendicularSequence size == 1
        or: [
            | string number |
            string := String withAll: perpendicularSequence.
            number := string asInteger.
            (string first ~~ $0 and: [number isPrime])
                ifTrue: [anInsertion addAccidentalPrime: number. true]
                ifFalse: [false]
            ]

doInsertion: anInsertion of: aPrime
    self
        insert: aPrime printString
        at: anInsertion point
        horizontalIf: anInsertion isHorizontal.
    primesUsed
        add: aPrime;
        addAll: anInsertion accidentalPrimes

growMatrixByOneUpTo: aDimension
    | smallMatrix rowOffset columnOffset |
    smallMatrix := matrix copy.
    matrix := Matrix
        rows: (self height + 2 min: aDimension y)
        columns: (self width + 2 min: aDimension x)
        element: Character space.
    rowOffset := (self height - smallMatrix numberOfRows) min: 1.
    columnOffset := (self width - smallMatrix numberOfColumns) min: 1.
    self copy: smallMatrix to: (1 + columnOffset) @ (1 + rowOffset)

copy: aMatrix to: aPoint
    matrix
        atRows: aPoint y
        to: aPoint y + aMatrix numberOfRows - 1
        columns: aPoint x
        to: aPoint x + aMatrix numberOfColumns - 1
        put: aMatrix

Collection

Oh, and I added one method to the instance side of Collection, just for convenience:

addIfNotNil: anElement
    anElement ifNotNil: [self add: anElement]

Running it

To run my code, all I need to do is select the following code in a workspace ("playground" in Pharo) or in any text pane, and "do it" from the context menu:

(Stuffer forDimensions: 80@60)
    stuffBox

The rest of the code is relatively boring.

As I said, room for improvement, but at 80x60, each run takes over 3 minutes on my machine. Clearly, performance hasn't been my concern, but there are a LOT of primes flying around. This sure has been an interesting challenge. :-)


Compare four integers, return word based on maximum

Jelly, 2 bytes

Takes input as [d,c,b,a]. Returns a list of Booleans.

Ṁ=

Try it online!

Ṁ Maximum

= equal to (implies the other argument is the original argument; vectorises)


My array should equal this, but it doesn't!

Brachylog, 8 bytes
h⊇.+~t?∧

Try it online!
Monthly Brachylog answer. Returns false. if it is not possible.
Explanation
h⊇.           The output is a subset of the head of the input
  .+~t?       The sum of the elements of the output must equal the tail of the input
       ∧      (Avoid implicit unification between the output and the input)


Pick a random number between 0 and n using a constant source of randomness

x86 machines with rdrand instruction, 10 bytes

BITS 64

_try_again:

 rdrand eax
jnc _try_again

 cmp eax, edi
ja _try_again

 ret

machine code

0FC7F0 73FB 39F8 77F7 C3

The input is in the register rdi and the output in rax.
This respects the SYS V AMD64 ABI so the code effectively implement a C function

unsigned int foo(unsigned int max);

with 32-bit ints.

The instruction rdrand is described by Intel

  RDRAND returns random numbers that are supplied by a cryptographically secure, deterministic random bit generator DRBG. The DRBG is designed to meet the NIST SP 800-90A standard.

Dealing with CSRNG it is implicit that the distribution is uniform, anyway, quoting the NIST SP 800-90A:

  A random number is an instance of an unbiased random variable,
  that is, the output produced by a uniformly distributed random process.

The procedure generates a random number and if it is non-strictly greater than the input it is returned.
Otherwise, the process is reiterated.

Since eax is 32-bit, rdrand returns a number between 0 and 232-1, so for every n in [0, 232-1] the number of expected iterations is 232/(n+1) which is defined for all n in [0, 230).


Pyth, 43 - 40 = 3 bytes

?&K@J.HQG-JG"Mix"%"Only %sers"?K"lett""numb

Test suite

This achieves the bonus. Only numbers and Only letters fortunately only differ by 4 letters. printf-style formatting is used with %.

The selection system is done by both taking the intersection of the hex with G, the alphabet, and subtracting out G. If neither ends up falsy, it's a mix, while if the intersection is falsy, it's numbers, and if the subtraction is falsy, it's letters.


Python 2, 85 bytes

-1 byte thanks to Dead Possum

n=0,
exec"i=0\nwhile set(`i`)&set(`n[-1]`)or i in n:i+=1\nn+=i,;"*input()
print n[-1]

Try it online!


SOGL V0.12, 73 71 70 66 bytes

.”L7:±¹‘Ο4↕ooā.⁾ Y*¾(){"}^ņF⁵),WοΓy⅜¬κ8ΕL▓‚7m~Ε⅝Γ‘7n┼F (=f⁄2=+⁽{@┼

Try it Here!

-4 bytes by looping over a string like (YYY) like the Charcoal answer

63 bytes would work if 2 didn't need to be handled :/


APL (Dyalog Extended), 99 93 bytes

r←0∊0 0⍉⊢
R←r~
s←⊢≢⍉
S←1∊⊢∧⍉
t←0∊⊢≥∨.∧⍨
T←1∊⊢∧∨.∧⍨
{×⍵:+/∧⌿~(⍺,'0'){(⍎⍺)⊣⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}

Try it online!
-5 bytes thanks to @ovs for spotting R←r~, and -1 by taking the boolean negation of the intermediate results.
Takes the condition as a string, using the abbreviation as follows:
r: reflexive
R: irreflexive
s: symmetric
S: asymmetric
t: transitive
T: antitransitive

For example, reflexive + symmetric + transitive is given as 'rst' and "no condition" is given as ''.
How it works (before golfing)
⍝ Each of rRsStT takes an adjacency matrix and determines if the condition is met

⍝ reflexive: the diagonal is all ones
r←∧/0 0⍉⊢
⍝ irreflexive: the diagonal is all zeros
R←∧/0 0⍉~
⍝ symmetric: transpose is equal to self
s←⊢≡⍉
⍝ antisymmetric: each position in self and transpose cannot be both ones
S←~1∊⊢∧⍉
⍝ transitive: self includes the transitive square of self
t←~0∊⊢≥∨.∧⍨
⍝ antitransitive: each position in self and transitive square cannot be both ones
T←~1∊⊢∧∨.∧⍨

⍝ main function
{×⍵:+/∧⌿(⍺,'≡'){(⍎⍺)⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}  ⍝ ⍵: n, ⍺: conditions
{×⍵: ... ⋄1}  ⍝ Take 0 as a special case, always returning 1
,⍳⍵⍴2*⍵       ⍝ Generate all length-n vectors of 0..2^n-1
⍵-⍛↑∘⊤¨       ⍝ Convert them to n×n binary matrices
(⍺,'≡')       ⍝ Add a default function that always returns 1 to the list of conditions
{...}\        ⍝ Take outer product of conditions and matrices...
 (⍎⍺)⍵        ⍝ Eval the condition function and apply it to the matrix
+/∧⌿          ⍝ Count the matrices which satisfy all the conditions


MATLAB, 86 63 bytes
set(warndlg,'WindowButtonM',@(s,e)movegui(get(0,'Po')-[99,20]))

This solution takes advantage of MATLAB's (typically annoying) ability to use partial property names as long as the part that is provided is unique to only the property of interest.
This solution uses the builtin warndlg to create a warning dialog with an "OK" button. This function returns a figure handle which we can then use to set the WindowButtonMotionFcn callback (using the short name 'WindowButtonM').
The callback that is evaluated any time the cursor is moved within the window gets the current position of the cursor (using the PointerLocation property of the root graphics object, using it's short name 'Po'). We then update the Position of the figure using movegui and specifying the new location of the figure after applying an offset of [99, 20] so that the cursor is placed on the button.
When the button is finally clicked, the figure is deleted and all callbacks are automatically released.


Brainfuck, 5 bytes
+[,.]

This sentence circumvents the 30 char answer requirement.


Positioning a fake mirror for best effect

Charcoal, 91 bytes

≔⟦⟧θＷＳ⊞θＩ⪪ι ≔Ｌ§θ⁰η≔⊖⌊⟦Ｌθη⟧ζＦ⁻ＬθζＦ⁻ηζＦ²⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧Ｉ✂⌈υ¹

Try it online! Link is to verbose version of code. 0-indexed. Explanation:

≔⟦⟧θＷＳ⊞θＩ⪪ι

Input the mosaic. (These 12 bytes could be avoided by requiring the input to be in JSON format, but I was too lazy to punctuate the example.)

≔Ｌ§θ⁰η

Get the width of the mosaic.

≔⊖⌊⟦Ｌθη⟧ζ

Get the inner size of the mirror, i.e. the distance from the first to the last character of the mirror in terms of diagonal steps.

Ｆ⁻Ｌθζ

Loop over the possible row(s) of the top left corner of the mirror's enclosing square.

Ｆ⁻ηζ

Loop over the possible column(s) of the top left corner of the mirror's square.

Ｆ²

Loop over the possible rotations of the mirror.

⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧

Calculate the number of tiles it reflects exactly. Exact matches are counted twice and the diagonal is also counted but this doesn't affect the relative score. Push this number along with the potential solution to the predefined empty list.

Ｉ✂⌈υ¹

Output the solution with the highest number of exactly reflected tiles.


///, 1 byte
A

Try it online!
As it’s 1 byte, simply outputting the source code gives the average. /// just outputs the source code unchanged if it doesn’t contain any / characters, so almost any ASCII character works in place of A


Jelly, 21 19 bytes

DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ

Input is 1-indexed. Try it online!

How it works

DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ  Main link. No arguments.

                µ    Convert the chain to the left into a link.
                 #   Read n from STDIN and execute the link to the left for
                     k = 0, 1, 2, ... until n value return a truthy value.
D                      Convert D to base 10 (digit array).
 LR                    Construct the range from 1 to the length of the digit array.
   ©                   Copy the range to the register.
       ®               Yield the value of the register.
    œ^€                Take the multiset difference of each element of the range
                       and the range itself.
        ịD             Index into the digit array.
          Ḍ            Convert each list of digits to integer.
                       This yields all numbers with one suppressed digit.
           ḍ@D         Test each of these numbers for divisibility by the
                       suppressed digit from the digit array.
              P        Take the product of the resulting Booleans.
               ȧ       Logical AND with k (k would return 1).
                  Ṫ  Tail; extract the last (nth) element.


C, 134

The C preprocessor is pretty fun to abuse. Basically this macro defines the 3 functions, a, o, and x, for and, or, and xor respectively. The only difference in the algorithm for these operations is the criteria for setting the bit in the result.

not is the function n.

#define f(n,c)n(a,b){for(r=0,i=31;i+1;--i)if(((a>>i)%2+(b>>i)%2)c)r+=1<<i;return r;}
i,r;n(a){return 0xffffffff-a;}f(a,/2)f(o,)f(x,%2)

Tester program (takes a long time, I didn't spend any time optimizing it at all, but it does test every test case possible, beside MAX_INT related ones):

#define m_assert(expected, condition, actual)\
    if(!((expected) condition (actual)))\
        printf("assert fail @ line %i, expected: %x, actual %x, condition "#condition"\n", __LINE__, expected, actual);

int main()  {
    unsigned int j,k;
    for(j=0; j<0xffff; ++j)    {
        m_assert(~j, ==, n(j));
        for(k=0; k<0xffff; ++k)    {
            m_assert(j & k, ==, a(j,k));
            m_assert(j | k, ==, o(j,k));
            m_assert(j ^ k, ==, x(j,k));
        }
    }


Mathematica, 23 bytes
RegionCentroid@*Polygon

Take THAT, Jelly!
Edit: One does not simply beat Jelly...
Explanation
Polygon

Generate a polygon with vertices at the points specified.
RegionCentroid

Find the centroid of the polygon.


JavaScript (ES6), 141 122 134 bytes
a=>a.replace(/&([aeiouyAEIOUY](acute|uml)|[aeiouAEIOU](grave|circ)|[aoAO]tilde);/g,b=>b[1]+{g:"̀",a:"́",c:"̂",t:"̃",u:"̈"}[b[2]])

Followed daavko's example using diacritical marks, and I feel like an idiot for not thinking of using it sooner. Actually gets surprisingly short for JavaScript.
EDIT: Neil caught some bad cases of undefined, which are now fixed.


Python 2 - 111 108 119 144 140 136 135 134 - Try it

Ok, let's give it a try:

i=input()
n,b=[(i,5),i][i>[]]
o=b-1
a=[n,n%b][b>1]*' |'
m=(b>1)*n/b
s=(' |'*o+'  ')*m+a
print(s+'\n'+('-+'*o+'- ')*m+a+'\n'+s)*(b*n>0)

Edit: I've overlooked that there should be no output if n==0 or b==0. This costs me 11 characters. :(

Edit: Ok, after fixing the second issue mentioned in the comments my solution basically converged to the one from BeetDemGuise.


Identify the direction of lines in an ASCII-figure

Slip, 6 + 2 = 8 bytes

+2 bytes for the f flag.

^*`#`#

Try it here!

Prints one of the following:

##

#
#

#
 #

 #
#

Explanation

The ^* sets the IP's direction to any one of the eight octilinear directions. Then `#`# simply matches two hash symbols in that direction. The f flag limits Slip to looking only for the first match, and by default the bounding box of that match is printed to STDOUT.

The pattern itself would be two bytes shorter in Snails (z\#2), but I don't think Snails can print the match itself, it only has numeric output (and adapting the pattern to printing 4 different numbers based on the direction would most likely take a lot more bytes).


Jelly, 37 bytes

Ç,³OBU+0x8¤_/FAS,Ç
Ç;0ịÇƊ$⁺-ịn1ị$Ʋ¿LH

Try it online!

Try it online! - using full implementation of MD5

I'll comment it when I have time. Jelly doesn't have an MD5 built-in, so the header for the first TIO implements MD5 for a fixed length (32 bytes) input. I've also now extended this to a general purpose MD5 routine (second TIO link). For the purposes of the challenge, there is a monadic link just above the challenge code that takes a 32 character string and returns the MD5 hash. The remaining code (as displayed above here) calculates the hamming distance between the original input and sequential hashes until it matches the first one.


Golfscript 17 16

Since the form of the input isn't specified, this takes a string in Golfscript array format from stdin.

~0\{1$+.@+\}/])?

So run as e.g.

golfscript.ry eqindex.gs <<<"[-7 1 5 2 -4 3 0]"

The idea is very simple: it takes an array of A_i and maps to an array of A_i + 2 SUM_{j<i} A_j and then looks for the first index which is equal to the sum of the whole array.

For @mellamokb's challenge I offer:

~0\{1$+.@+\}/:S;]:A,,{A=S=},`

for 29 chars.


The least weird fact about the US presidency right now

Python 2, 179 175 173 bytes

lambda s:sum(any(s==X[:len(s)]for X in x.split())for x in[A,B,'A CL HAR M R '+B,'ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W M',s])
A='C H T';B='BU J '+A

Try it online!


List the combinations of elements in a set

Haskell - 57 46 bytes
Bring it on, golfscripters.
0%_=[[]]
n%(x:y)=map(x:)((n-1)%y)++n%y
_%_=[]

Use case (same function works polymorphicaly):

2%[1,2,3,4] ➔ [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
3%"cheat" ➔ ["che","cha","cht","cea","cet","cat","hea","het","hat","eat"]
2%["Charlie", "Alice", "Daniel", "Bob"] ➔
[["Charlie","Alice"],["Charlie","Daniel"],["Charlie","Bob"],["Alice","Daniel"],["Alice","Bob"],["Daniel","Bob"]]


Python 2, 60 bytes

n=input();l=len(n)
for i in range(l):print(l/2*' '+n)[i:l+i]

Try it online!


Jelly, 11 bytes

Œṙ'Œ!⁻ƝẠ$ƇX

Try it online!

Œṙ'Œ!⁻ƝẠ$ƇX Arguments: z
  '         Flat: Apply link directly to x, ignoring its left and right depth properties
Œṙ            Run-length decode
   Œ!       Permutations of x
         Ƈ  Filter; keep elements of x for which the link returns a truthy result
        $     ≥2-link monadic chain
      Ɲ         Apply link on overlapping pairs (non-wrapping)
     ⁻            x != y
       Ạ        Check if all elements of x have a truthy value (+vacuous truth)
          X Pick a random element of x; return 0 if the list is empty.


Pyth, 28 27 25 bytes

J"KTAZ"hxcz)eo_XN+@z1JJcz

Try it online: Demonstration or Test Suite (first 4 chars are the test suite construct)

Thanks to @isaacg for a trick, which saved 2 chars.

The main idea is to modify chars of each hand such a in way, that the winning hand has the maximal value.

The values of the hands 23456789TJQKA is already nearly sorted. I just have to replace T with A, K with T and A with Z, resulting with 23456789AJQSZ.

The order of suits CDHSare for the most not really important. S, the most powerful suit, which is already the maximal value. Important is to give the suit of the first hand the second most powerful value. So I translate this suit into K.

All hands also have to be read reverse, since the suit is more powerful than the value.

                           implicit: z = input string
J"KTAZ"                    J = "KTAZ"
             o         cz  orders the hands N of split(z) by:
              _              the reversed of
               XN+@z1JJ      N, where the values z[1]+J are replaced by J
            e              last element (winning hand)
        xcz)               index of the winning hand in split(z)
       h                   + 1


Python 3, 379 358 339 337 327 310 304 bytes

Conjecture: Is 13 the only number that will lead to a cycle? (There are no exceptions smaller than 106.)

Fixed a bug and -7 bytes thanks to Sherlock9.-3 byte thanks to Jonathan Frech.-16 bytes thanks to ovs.-6 bytes thanks to Mr. Xcoder.

If there is a cycle, it will repeat the whole cycle.

def p(a,x=0,n=1):
 while a:x+=1;a-=n%x;n*=x*x
 return x
def g(a):
 c=i=0
 for v in a:
  c+=int(v)*2-1
  if c<0:return 0,0
  if c<1:break
  i+=1
 if a:x=p(g(a[1:i])[0]);b,c=g(a[i+1:]);return(x>c>0)*(0,0)or(x*b,x)
 return 1,0
def f(a):
 x=a,
 while(x.count(a)<3)*a:a,t=g(bin(a-~a)[2:]);x+=a,
 return x[:-1]

Try it online!

Explanation:

def p(a,x=0,n=1):     # return the a-th prime
 while a:             # magical way to enumerate primes
  x+=1
  a-=n%x
  n*=x*x
 return x

def g(a):             # decode a 0/1 string
 c=i=0
 for v in a:
  c+=int(v)*2-1       # +1 if 1, -1 if 0
  if c<0: return(0,0) # c<0: unbalanced parentheses
  if c<1: break       # first outermost parentheses
  i+=1
 if a:
   x=p(g(a[1:i])[0])  # recursive solve those inside the parentheses ...
   b,c=g(a[i+1:])     # and the remaining
   if x>c and c:      # if not ascending
    return (0,0)
   return (x*b,x)     # return (result, value of first closed parentheses)
 return (1,0)         # empty string

def f(a):
 x=a,
 while a and x.count(a)<3: # detect non-decodable or cycle
  a,t=g(bin(a-~a)[2:])     # a-~a is a*2+1
  x+=a,
 return x[:-1]


Befunge, 17x4 = 68 characters

1-&00p&>:!#v_:00v
v-10<  ^/g00\%g <
< >:^@_.# #$v#:!`
"_^#`9::$  <<,+"W

Online interpreter: http://www.bedroomlan.org/tools/befunge-93-playground

First input is base, second is number.

Similar to other solutions here this does not output anything when the number is 0.  I may look at fixing this at some point.


Ruby, 105 characters
Unfortunately I didn't get it below the 100 mark. It just brute forces all possible tuples and checks afterwards. Nevertheless it still finishes in finite time.
(1..m=711).map{|a|(a..m).map{|b|(b..m).map{|c|d=m-a-b-c;p [a/u=1e2,b/u,c/u,d/u]if d>=c&&a*b*c*d==m*1e6}}}

The formatted version looks like this:
(1..m=711).map{ |a|
  (a..m).map{ |b|
    (b..m).map{ |c|
      d=m-a-b-c
      p [a/u=1e2,b/u,c/u,d/u] if d>=c && a*b*c*d==m*1e6
    }
  }
}


05AB1E, 5 bytes

l#€нË

Try it online!

l      # Lowercase input.
 #     # Split on spaces.
  €н   # a[0] of each.
    Ë  # All equal?

Did this on mobile excuse the no explanation.


Write a Rectangular Program that Outputs the Number of Times it was Rotated

APL (1x3 = 3)

5!3

This solution uses the extra rule that any output that is correct mod 4 works.

In APL, x!y is the number of way to choose x elements from y, commonly known as binom(y,x) or choose(y,x). Let's check that each rotation gives the right answer.

0 rotations

5!3

There's no way to choose 5 elements from 3, so we get 0, which is automatically printed.

1 CCW rotation

3
!
5

APL happily evaluates each line, getting the number 3, the operator !, and then the number 5, printing only the last of these (5), which is 1 mod 4.

2 CCW rotations

3!5

This is binom(5,3), which is (5*4*3*2*1)/(3*2*1)/(2*1) = 10, which is 2 mod 4.

3 CCW rotations

5
!
3

As before, only the last-evaluated value of 3 is printer.

I don't actually know APL, so please tell me if I got any of the explanation wrong. I found it by trial and error as the first language on this site that:

Automatically prints the result of an expression
Given multiple lines of expressions, only outputs the last one
Has no issue with an operator standing alone on a line
Takes operators infix
Has a single-character arithmetic binary operator that is asymmetric (aRb != bRa), and flexible enough to return a variety of numbers.

For (5), I went down the list of APL dyadic functions. My first candidate operation was the integer division / of C and Python 2, but APL division ÷ gives floats. Exponentiation is tempting, but fails because a and a^b have the same parity but are gotten by consecutive rotations (unless b=0, but then b^a=0). Boolean operators like < give 0 and 1 180 degrees apart, which doesn't work. Finally, I found the binomial operator ! and tried numbers until I got some that work.

Thanks to Quincunx for his confidence that there exists a smaller solution than 2x2.


Pyth 190 character - 30 - 70 = 90

=Q{cQdL+x"C D EF G A B"hb&tlbt%hx" #b"eb3FZQJx[188 212 199 213 200 224 2555 2411 2412 2556 2567 2398)u+*G12hHSm%-dyZ12mykQ0IhJ+Z@c"sus2 maj dim aug m sus4 7 m7 mmaj7 maj7 aug7 dim7"dJ=T0;ITQ

Not really happy with it. Used hard-coded chords.

Usage:

Try it here: Pyth Compiler/Executor. Disable debug mode and use "C D# G" as input.

Explanation:

First some preparation:

=Q{cQd
   cQd  split chord into notes "C D# G" -> ["C", "D#", "G"]
  {     set (eliminate duplicates)
=Q      Q = ...

Then a function that converts notes into integer

L+x"C D EF G A B"hb&tlbt%hx" #b"eb3
defines a function g(b),
  returns the sum of
     index of "D" in "C D EF G A B"
     and the index of "#" in " #b"
       (if b than use -1 instead of 2)

Then for each note, shift the coord and look it up in a table

FZQJx[188 ...)u+*G12hHSm%-dyZ12mykQ0IhJ+Z@c"sus2 ..."dJ=T0;ITQ
               implicit T=10
FZQ            for note Z in chord Q:
   mykQ         map each note of Q to it's integer value
   m%-dyZ12     shift it by the integer value of Z modulo 12
   S            sort it
   u+*G12hH 0   convert it to an integer in base 12
   x[188 ...)   look it up in the list (-1 if not in list)
   J            and store the value in J

   IhJ               if J>=0:
   +Z@c"sus2 ..."dJ   print the note Z and the chord in the list
=T0                   and set T=0
;            end loop
ITQ          if T:print chord (chord not in list)


Print an ascii spiral in O(log n) memory

C, 125 121 bytes
Golfed version This has no variable k. The variable k is used in the ungolfed version just to aid readability. Also for loop conditionals are rearranged and one set of unnecessary {} removed. Another set of {} can be removed by migrating puts("") inside the brackets of the j loop in the initialization position, but this would mean a newline at the beginning of the output, so I haven't done it.
f(n){int i,j;n/=2;for(i=-n-2;i++-n-1;){if(i){for(j=-n-1;j++-n;)putchar(32+10*(n+(j*j<i*i?i:j+(i!=j|i>0))&1));puts("");}}}

Prints an n wide by n+1 high spiral like the example.
Explanation
Basically I halve the value of n (rounding down) and run two loops: an outer one i from -n/2-1 to n/2+1 to print the rows (i=0 is suppressed so we get n+1 rows) and an inner one j from (-n/2 to n/2 to print the characters.) We use expression & 1 to print stripes, and the condition j*j<i*i to decide whether to print vertical or horizontal stripes (vertical at the sides where absolute magnitude of i is larger, and horizontal at the top and bottom.) An adjustment +n is required to help with the correct termination depending on whether n/2 is odd or even.
k is normally 1, and provides an adjustment for the fact that the absolute values of i range from 1 to n/2+1 while the absolute values of j range from 0 to n/2. If k was always 1 we would get concentric rectangles, but it is inverted to 0 when i==j&i<=0 so that a diagonal row of cells is inverted, producing the spiral.
ungolfed in test program
f(n){
  int i,j,k;
  n/=2;
  for(i=-n-1;i<=n+1;i++){
    if(i){
       for(j=-n;j<=n;j++){
           k=i!=j|i>0;
           putchar(32+10*(n+(j*j<i*i?i:k+j)&1));
         }
       puts("");
     }
  }
}

int m;
main(){
  scanf("%d",&m);
  f(m);
}

Output
11
***********
          *
********* *
*       * *
* ***** * *
* *   * * *
* * * * * *
* * *** * *
* *     * *
* ******* *
*         *
***********

9
*********
        *
******* *
*     * *
* *** * *
* * * * *
* *   * *
* ***** *
*       *
*********

3
***
  *
* *
***

1
*
*


Symmetric boolean functions as Zhegalkin polynomials

Dyalog APL, 15 bytes
{2|⍺⌹⍉∘.!⍨0,⍳⍵}

Matrix division, basically. Takes input like 0 0 1 1 1 {2|⍺⌹⍉∘.!⍨0,⍳⍵} 4 for T4({2,3,4}).
{              }        Dyadic function:
              ⍵         Right argument          4
             ⍳          Index vector            1 2 3 4
           0,           Append 0                0 1 2 3 4
      ∘.                Outer product           ——————————
          ⍨             |With itself              1 0 0 0
        !               |By binomial coeff.       2 1 0 0
     ⍉                  Matrix transpose          3 3 1 0
                        Result at this step: ->   4 6 4 1
   ⍺                    Left argument
    ⌹                   Matrix division (A⌹B is A^-1 B, not A B^-1)
                        (implicitly converts ⍺ to column vector)
 2|                     Modulo 2

Since the transposed matrix of binomial coefficients is lower triangular with determinant 1, its inverse will only contain integers. So to matrix-divide over F2 we can just matrix-divide over the reals, then mod by 2.
Matrix division is an O(n^3) operation, and calculating each of the O(N^2) binomial coefficients is well below O(n^3), so this runs in O(N^5).
Try it on TryAPL.


C 64,643 bytes, Score: ~6.5 million
The following Stack Snippet (courtesy of Mego) outputs all of the code as a single standalone C file:

$("#a").text(pako.inflate(atob('[encoded data, 7512 characters]'), {to: 'string'}));
<script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="a">

</pre>

Download the original source here.
Use GCC and run make then using the guideline in the readme.
My formatting is bad (all the different files are in one code block) and this could be golfed more (12k bytes tho). Any help would be loved!
Some of the code is not mine. I used it from a un-copyrighted source. I however fixed the input/output method to be within the challenge (a long task since I am horrible at C (5ish hours)). I also had to re-write much of the code and debug everything. Many thanks to my Dad for helping out and being a rubber duck (and pointing out my memory management errors) and for everyone on TNB who dealt with my angry rants about segfaults and C.