APL (Dyalog Unicode), 7 bytes (SBCS)

Anonymous tacit prefix function.

,,∘⍕∘≢⌸

Try it online!

⌸ apply the following function between each unique character and the indices where it occurs:

 , concatenate the character

  ∘ to

   ⍕ the stringification

    ∘ of

     ≢ the indices' count

, flatten


JavaScript (ES6), 237 bytes

f=(n)=>(t=new Date('201'+n[3],n[4]+n[5],n[6]+n[7])/864e5-403805/24,r=484/(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r?r>30.25&!~i&&'(^_^)'[j+3]||'#':~'p-3-5p62p-56p21p7-2'.indexOf('p'+j+i)?'.':' ')+(++j<8?h(j):''))(-7)+'\n'+g(i):''))(-8))

Live demo. Run in Firefox.

Original version

f=function(n) {
    t = (new Date('201'+n[3],''+n[4]+n[5],''+n[6]+n[7]) // Find the time difference in milliseconds,
    - new Date(2015,12,25)) / 864e5;                    // then divide by 86400000 to convert to days.

    r=22 / Math.sqrt(t*t+10);                           // Calculate the radius.

    s=[]; // s is the array that contains each line as a string.

    for(i=-7;i<8;i++)               // Loop through rows.
        for(j=-7,s[i+7]='';j<8;j++) // Loop through columns, appending one character per column.
                                    // s is zero based, so add 7 to the row.
            s[i+7]+=i*i+j*j<=r*r ?  // Choose which character to add to s.
            (r>5.5&i==-1&&'(^_^)'[j+3]||'#') :  // Add a '#' if the position is inside the radius.
                                                // If distance < 4, then the radius > 5.5
                                                // Then add the face at the right position.
            {'-3-5':1,'62':1,'-56':1,'21':1,'7-2':1} // Add the stars if outside. Create an associative array.
            [j+''+i]?'.':' ';                        // If i concat j is in the array, the expression will be 1,
                                                     // which is truthy, else it will be undefined, which is falsey.
    return s.join`\n` // Join all the rows with a new-line.
}

Golfing

This was fun to golf.

I don't need to create a Date object, so I hardcoded the value in milliseconds to save 13 bytes:

t=(new Date('201'+n[3],n[4]+n[5],n[6]+n[7])-new Date(2015,12,25))/864e5 // Before
t=new Date('201'+n[3],n[4]+n[5],n[6]+n[7])/864e5-403805/24 // After

Replace the associative array with a delimited string to eliminate 9 bytes:

{'-3-5':1,'62':1,'-56':1,'21':1,'7-2':1}[j+''+i]?'.':' ' // Before
~'p-3-5p62p-56p21p7-2'.indexOf('p'+j+i)?'.':' ' // After

The biggest refactor was replacing the for loops with nested, recursive IIFEs to knock off 10 bytes:

s=[];for(i=-7;i<8;i++)for(j=-7,s[i+7]='';j<8;j++)s[i+7]+= /* Chooses char at i,j */ ;return s.join`\n` // Before
(g=(i)=>(++i<8?(h=(j)=>( /* Chooses char at i,j */ )+(++j<8?h(j):''))(-7)+'\n'+g(i):''))(-8) // After

I also got rid of Math.sqrt for 8 more bytes.

r=22/Math.sqrt(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r*r?r>5.5 // Before
r=484/(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r?r>30.25 // After

Issues

I could only get the correct photograph for the test cases by changing the closest date to 2015/12/24, and I don't know if the problem lies in my code or the question. Please clarify and I will update my answer.

Here is my output using the differences from 2015/12/25.

Edit: Updated answer to use Christmas as the closest date.

Photograph for "20151215":

        .

           #      .
          ###
         #####
          ###.
           #     .

      .

Photograph for "20151225":

        #######
       #########
      ###########
     #############
     #############.
     ###(^_^)#####
     #############
     #############
     #############
     #############
      ###########
       #########
      . #######


Jelly, 9 6 bytes

ṗ6ḅ-ċ0

O(n6) solution.

Try it online!

How it works

ṗ6ḅ-ċ0  Main link. Argument: n

ṗ6      Cartesian power 6; build all 6-tuples (a, x, b, y, c, z) of integers in
        [1, ..., n]. The challenge spec mentions [0, ..., n-1], but since there
        are three summands on each side, this doesn't matter.
  ḅ-    Unbase -1; convert each tuple from base -1 to integer, mapping (a, ..., z)
        to a(-1)**5 + x(-1)**4 + b(-1)**3 + y(-1)**2 + c(-1)**1 + z(-1)**0, i.e.,
        to -a + x - b + y - c + z = (x + y + z) - (a + b + c). This yields 0 if and
        only if the 6-tuple is a match.
    ċ0  Count the number of zeroes.


Is it an integer, a string, or a decimal?

Pyth, 33 bytes (39 without packed string)

@_c."at%¸Ã`9hàãáÊ"7.x/`MsB+vz0z0

Some bytes are stripped due to Markdown. Official code and test suite.

Without packed string:

@_c"integerdecimalstring"7.x/`MsB+vz0z0

It passes all of above test cases. Basically, to check if a string is a integer or decimal, it checks whether the string can be evaluated as a python literal (v), and if so, if you can add 0 to it and covert it back to its string representation, and get the input string. If so, it's an integer or a decimal. If you can also cast it to an int and still get the original string back, it's an integer.


JavaScript (ES6), 192 188 185 bytes

document.write('<pre id=o>')
s='ABCDEFGHIJQRSTUVWXYZ'
a=[0,...123456789+s.toLowerCase()+s]
setInterval('o.innerText=a.join``;a.splice(Math.random(s^=1)*48+1,0,s?a.pop():a.shift())',250)

Edit: Saved 4 bytes thanks to @L.Serné. Saved 3 bytes thanks to @Arnauld.


Ruby, 302 306 322 327 bytes

+4 bytes to fix the edge case with the \$-i\$ direction (its angle is negative so we need to mod 4)
+16 bytes for even more edge case fixes in the stepping algorithm...
+5 bytes to fix the edge case where no inputs from 1-4 are present.

P=Math::PI/2
b=0i;f=d=p
c={b=>?:}
gsub(/[1-4]/){x=$&.to_i;d||=1
c[b+=d]="╗╝╚╔╗"[d.arg/P%4+x%2]if x[1]>0
d*=[0,1,1i,-1i,-1][x]
c[b+=d]="═║"[d.imag.abs]if x<4||!f
f=1}
c[b+=d]=">V<^"[d.arg/P]if d
q=c.keys.map &:rect
q=q.pop.zip *q
i,j=q[0].minmax
k,l=q[1].minmax
puts (k..l).map{|y|(i..j).map{|x|c[x+y*1i]||' '}*''}

Try it online!
Explanation
We initiate the grid as a hash table where the keys are complex numbers (real is the X-axis, imaginary is the Y-axis, lower numbers are closer to the top-left corner). This is convenient because we can initialize the direction variable as \$1\$, multiply by \$i\$ to turn right, and multiply by \$-i\$ to turn left. Also, we can quickly determine which way we're facing by dividing the direction's angle by \$\pi/2\$ and use that in our lookup tables.
Our algorithm, then, is roughly as follows:

Get the next number from the input in the range 1-4.
If the number is 2-3, step once and add the correct corner piece.
Look up the corresponding direction change and multiply.
Step once and add the correct straight piece. (Don't need to step if we turn around.)
Repeat until done.
Step and add the arrow piece.
Print the grid.

Code explanation (out of date, will fix later)
P=Math::PI/2                            # Save PI/2
b=0i;d=1                                # Set initial coordinates and direction
c={b=>?:}                               # Create grid with starting `:`
gsub(/[1-4]/){x=$&.to_i                 # For each number 1-4
c[b+=d]="╗╝╚╔╗"[d.arg/P+x%2]if x[1]>0   # If 2-3 (second bit is a 1), step and write the corner piece
                                        # If turning left (3), +1 to the index
d*=[0,1,1i,-1i,-1][x]                   # Multiply direction to turn accordingly
c[b+=d]="═‖"[d.imag.abs]                # Step and write the straight piece
}                                       # (end the loop)
c[b]=">V<^"[d.arg/P]                    # Write the corresponding arrow piece
q=c.keys.map &:rect                     # Get the filled-in grid spaces as X,Y coordinates
i,*_,j=q.map(&:first).sort              # Find the min and max X coordinate
k,*_,l=q.map(&:last).sort               # Find the min and max Y coordinate
puts (k..l).map{|y|                     # For each Y coordinate in range
      (i..j).map{|x|                    # For each X coordinate in range
                    c[x+y*1i]||' '      # Get the character, or space if not present
                }*''                    # Join characters on that Y coordinate and print
        }


Haskell function, 35 34 characters

f[]="{}";f(_:x)='{':f x++tail(f x)

Haskell program with hardcoded input, 48 or 49 47 or 48 characters

 f[]="{}";f(_:x)='{':f x++tail(f x);main=print$f"aaaa"

(47 characters if you don't mind extra quotes around the output; if you do, use putStr instead of print for a total of 48 characters)

Haskell program, 51 50 characters

f[]="{}";f(_:x)='{':f x++tail(f x);main=interact f


Python 2, 47 ... 36 bytes

-3 bytes thanks to @JungHwanMin
-1 byte thanks to @HyperNeutrino
-2 bytes thanks to @JonathanFrech
-3 bytes thanks to @OlivierGrégoire

def f(x):s=int(x**.5);print(x/s+s)/2

Try it online!


The edited sequence (the first version was mangled).

2 A 2 A Esc 2 A 2 A Esc 2 A 2 A Esc

2 A 2 A Esc  2 A 2 A Esc 2 A 2 A Esc

2 A 2 A Esc 2 A 2 A Esc  A : w q Enter

Esc Backspace Backspace Backspace
Backspace Backspace : w q Enter

Should do the trick, if I'm counting my keystrokes correctly. No wait, is the escape key allowed?


Counting King's Hamiltonian Paths through 3-by-N grid

Wolfram Language (Mathematica), 76 72 bytes
LinearRecurrence[{6,12,-27,2,30,4,-6},{0,0,1,2,3,29,155}-6/5,{#+4}]+1/5&

Try it online!
The non-homogeneous linear recurrence equation is so much shorter to express that it saves a few bytes to modify the code to handle non-homogeneous linear recurrence.
More info: In this case, it cannot be represented as a polynomial. I tried to put the recurrence into RSolve, but it takes a long time to figure out the exact symbolic form (I terminate it before it completes), and I'm pretty sure that the required coefficients are irrational (approximate numerical formula can be obtained).
Returns a singleton list containing the result.


PHP, 38 40 30 28 bytes

<?=date("jS F",86399*$argn);

Try it online!

Run with php -nF input is from STDIN. Example (above script named y.php):

$ echo 1|php -nF y.php
1st January
$ echo 2| php -nF y.php
2nd January
$ echo 3| php -nF y.php
3rd January
$ echo 11|php -nF y.php
11th January
$ echo 21|php -nF y.php
21st January
$ echo 60|php -nF y.php
1st March
$ echo 365|php -nF y.php
31st December

Explanation

Construct an epoch timestamp for the desired day in 1970 (conveniently not a leap year) by multiplying the day number * number of seconds per day (86400).  However, this would yield one day higher so instead multiply by number of seconds in a day - 1 (86399) which for the range of input numbers (1≤n≤365) will result with the timestamp of the end of each correct day. Then just use PHP's built-in date formatting for output.


CJam, 57 53 49

{"NESW""FRBL"_3$&!!:Q$:R^^f#0\{{+0\}Q*_@-R=\}%);}

Previous version

{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}

Example:

{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}:T;
"NNWEESEE"T
N
"FFLBFRLF"T

Output:

FFLBFRLF
NNWEESEE

How it works

{
  "NESW""FRBL"             " Push the two strings. ";
  _3$0=#W>                 " Check if the first character is in FRBL. ";
  :Q                       " Assign the result to Q. ";
  {\}*                     " Swap the two strings if true. ";
  :R;                      " Assign the top string to R and discard it. ";
  f#                       " Find each character of the input in the string. ";
  0\                       " Push a 0 under the top of the stack. ";
  {                        " For each item (index of character): ";
    {                      " If Q: ";
      +0\                  " A B -> 0 (A+B) ";
    }Q*
    _@-                    " C D -> D (D-C) ";
    R=                     " E -> E-th character in R ";
    \                      " Swap the top two items. ";
  }%
  );                       " Discard the last item in the list. ";
}


Predict a Collision: Will the robber get away?

Python 3, 29 bytes

lambda s,p,a:(a-2*s)**2<8*a*p

Try it online!

Explanation

The cop's position at time t is st.

The robber's position at time t is a(t)(t+1)/2 + p.

The signed distance from the cop to the robber is (a/2)t^2 + (a/2-s)t + p.

It never reaches zero if the discriminant is negative, the discriminant being (a/2 - s)^2 - 4(a/2)(p) = [(a-2s)^2-8ap]/4, which has the same sign as (a-2s)^2-8ap.


JavaScript, 64 57 bytes
4 bytes removed thanks to Martin Ender.
^(?!.*([^])(.*\1){3}]?)[$$[-^?!!.'''-*11{33}5577\\-]{57}$

Try it here.
Explanations (outdated)
^                                  # Beginning of the string.
(?!.*                              # Match only the strings that don't contain...
  (.)(.*\1){4}                     #     5 occurrences of the same character.
  [^1]?[^1]?                       #     Something that doesn't matter.
)
[]zzz^(?!!!.**[)\\1{{44}}666]{64}  # 64 occurrences of these 16 characters.
                                   # Some are duplicated to make sure the regex
                                   # contains 4 occurrences of each character.
\z                                 # End of the string.


Mathematica, 211 210 bytes

i=Import;FileNameTake@#~Export~i@#&/@ImportString["body"/.("items"/.i["http://api.stackexchange.com/2.2/questions/"<>InputString[]<>"?site=codegolf&filter=!*Lgp.gEWHA6BNP.l","JSON"])[[1]],{"HTML","ImageLinks"}]

Ungolfed:

i = Import;
FileNameTake@#~Export~i@# & /@
 ImportString[
  "body" /. (
    "items" /.
      i["http://api.stackexchange.com/2.2/questions/" <>
        InputString[] <> "?site=codegolf&filter=!*Lgp.gEWHA6BNP.l",
       "JSON"]
  )[[1]],
  {"HTML", "ImageLinks"}
 ]

It's pretty straightforward. I've set up a filter for the StackExchange API, which returns only the body of a question. The code retrieves the question information with that filter and parses it as JSON. I select the correct element (the body), and use ImportString to parse the HTML and filter out all image URLs. FileNameTake@#~Export~Import@# then downloads each of the images and stores it in the current working directory with the same file name as that in the URL.

You can find out the current working directory with Directory[].

In principle, there's a much shorter version, because ImportString can actually download all the files right away, instead of just giving me the URLs. But then I lose information about the original file type (since they are converted to Image objects upon download), so I can only save them all as the same type (PNG, say).


Bash + coreutils, 13

truncate -s$@

Input from the command-line - the first parameter is the file size and the second is the filename.
From man truncate:

If a FILE is shorter, it is extended and the extended part (hole) reads as zero bytes.

Try it online.


CJam

{"_~"}_~

Well, whether this looks like a real quine to you depends on whether you're used to CJam or GolfScript, but anyway, it looks like and prints the standard quine:

{"_~"}_~

Wait, isn't that the same thing?

   Nope, there's a space at the end of the first code. I believe the same thing would work in almost any language with almost any quine.

Test it here.


275 bytes

\.?([cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x|[bcgkmp][ghmnrwy]|[psu][agksy]|[aen][cegru]|[abcn][fioz]|l[abcikr-vy]|[bdjkprsvy]e|[bcgmnqvz]a|[behpsty]t|[cghmrv]u|[fgksv]i|[gjkmn]p|b[bdjs]|h[kmnr]|[gptw]f|[artz]w|v[cgn]|[joz]m|[ijr]o|[erw]s|[dku]z|[np]l|fr|in|sb)

(277 bytes including ^$.) A Python program was used to autogenerate part of this regular expression. Here is the first version of the program:

def makeregex(list):
  if len(list) == 1:
    return alpha[list[0]]
  regex = "["
  j = list[0]
  while j < 26:
    if j in list:
      if j + 1 in list and j + 2 in list and j + 3 in list:
        regex += alpha[j] + "-"
        while j + 1 in list:
          j += 1
      regex += alpha[j]
    j += 1
  return regex + "]"

def perform(rows, cols):
  replaced = '|'.join([alpha[j] + alpha[k] for j in rows for k in cols if array[j][k] > 0])
  regex = makeregex(rows) + makeregex(cols)
  print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'
  for j in rows:
    for k in cols:
      if (array[j][k]):
        array[j][k] = -1
      else:
        raise Exception("filling illegal entry")

all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
       'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
       'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
       'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
       'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
       'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
       'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
       'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
       'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
       'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
       'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
       'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
       'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
       'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
       'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
       'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
       'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
       'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
       'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
       'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
       'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]

#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])

while max(max(row) for row in array) > 0:
  best = 0
  i = 1
  while i < 1 << 26:
    row = [-1 for j in range(26)]
    for j in range(26):
      if (i & 1 << j):
        for k in range(26):
          if array[j][k] == 0:
            row[k] = 0
          elif array[j][k] == 1 and row[k]:
            row[k] = max(row[k], 0) + 1
        if max(row) < 1:
          break;
    if max(row) > 0:
      total = 3 * sum(max(j, 0) for j in row)
      if total > best:
        rows = [j for j in range(26) if i & 1 << j]
        cols = [j for j in range(26) if row[j] > 0]
        total -= len(makeregex(rows)) + len(makeregex(cols)) + 1
        if total > best:
          best = total
          bestrows = rows
          bestcols = cols
      i += 1
    else:
      i += i & -i
  if best:
    perform(bestrows, bestcols)
  else:
    print '|'.join([alpha[j] + alpha[k] for j in range(26) for k in range(26) if array[j][k] > 0])
    break

This 282-byte regex results from its output:

\.?([bgmps][aeghmnrsty]|[cmst][cdghk-orvz]|[acn][cfgiloruz]|[agim][delmq-t]|[bck][ghimnrwyz]|[elm][cr-u]|[dft][jkmo]|[agpt][fltw]|[gnv][aegiu]|[lpu][aksy]|[gjkm][emp]|h[kmnrtu]|b[bdfjo]|r[eosuw]|[ls][biv]|[acms]x|[cmz][amw]|[dey]e|dz|eg|fi|fr|in|io|jo|np|om|qa|ug|uz|vc|vn|wf|ws|yt)

The program can also be seeded by adding calls to perform, so I tried seeding it with [cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x but that just resulted in a rearranged regex. Obviously this wasn't good enough. The problem seemed to be that I was comparing the performance against a simple alternation. I therefore developed a slower but more accurate scoring function, which works by assuming that all of the remaining matches should be either x[yz] or [xy]z alternations, generating the largest alternations first, and compares the result with and without the trial regex.

def makeregex(list):
  if len(list) == 1:
    return alpha[list[0]]
  regex = "["
  j = list[0]
  while j < 26:
    if j in list:
      if j + 1 in list and j + 2 in list and j + 3 in list:
        regex += alpha[j] + "-"
        while j + 1 in list:
          j += 1
      regex += alpha[j]
    j += 1
  return regex + "]"

def simple(array):
  unused = [[j > 0 for j in row] for row in array]
  regex = ""
  while max(max(row) for row in unused):
    rowcount = [sum(row) for row in unused]
    colcount = [sum(col) for col in zip(*unused)]
    if max(colcount) > max(rowcount):
      colindex = colcount.index(max(colcount))
      col = zip(*unused)[colindex]
      regex += "|" + makeregex([j for j in range(26) if col[j]]) + alpha[colindex]
      for j in range(26):
        unused[j][colindex] = 0
    else:
      rowindex = rowcount.index(max(rowcount))
      row = unused[rowindex]
      regex += "|" + alpha[rowindex] + makeregex([j for j in range(26) if row[j]])
      unused[rowindex] = [0 for j in range(26)]
  return regex

def perform(rows, cols):
  previous = simple(array)[1:].split('|')
  for j in rows:
    for k in cols:
      if (array[j][k]):
        array[j][k] = -1
      else:
        raise Exception("filling illegal entry")
  regex = (makeregex(rows) + makeregex(cols) + simple(array)).split('|')
  replaced = '|'.join(j for j in previous if not j in regex)
  regex = '|'.join(j for j in regex if not j in previous)
  print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'

all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
       'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
       'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
       'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
       'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
       'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
       'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
       'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
       'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
       'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
       'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
       'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
       'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
       'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
       'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
       'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
       'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
       'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
       'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
       'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
       'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]

#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])

while max(max(row) for row in array) > 0:
  best = simple(array)[1:]
  bestrows = []
  bestcols = []
  i = 1
  while i < 1 << 26:
    row = [-1 for j in range(26)]
    for j in range(26):
      if (i & 1 << j):
        for k in range(26):
          if array[j][k] == 0:
            row[k] = 0
          elif array[j][k] == 1 and row[k]:
            row[k] = max(row[k], 0) + 1
        if max(row) < 1:
          break;
    if max(row) > 0:
      rows = [j for j in range(26) if i & 1 << j]
      cols = [j for j in range(26) if row[j] > 0]
      unused = [row[:] for row in array]
      for j in rows:
        for k in cols:
          unused[j][k] = 0
      total = makeregex(rows) + makeregex(cols) + simple(unused)
      if len(total) < len(best):
        best = total
        bestrows = rows
        bestcols = cols
      i += 1
    else:
      i += i & -i
  if bestrows:
    perform(bestrows, bestcols)
  else:
    print best
    break

Now without seeding, this actually produces the worse 286-byte regex:

\.?([bgp][ae-hmnrstwy]|[cst][cdghk-orvz]|[nv][acegiu]|m[acdeghk-z]|a[c-gilmoq-uwxz]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|s[abeistxy]|c[afiuwxy]|e[cegr-u]|b[bdijoz]|d[ejkmoz]|f[ijkmor]|g[dilpqu]|h[kmnrtu]|n[floprz]|u[agksyz]|r[eosuw]|j[emop]|t[fjtw]|z[amw]|p[kl]|w[fs]|y[et]|om|qa|vn)

When seeded with [cmst][cdghk-orvz] (which I had independently discovered manually before writing the first program) this improves to this 282-byte regex, thus equalling the first program:

\.?([cmst][cdghk-orvz]|[bgmps][aeghmnrsty]|[ag][d-gilmq-uw]|[pt][fkltw]|[acs][cioxz]|[nv][acegiu]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|b[bdfijowz]|e[cegr-u]|d[ejkmoz]|f[ijkmor]|h[kmnrtu]|n[floprz]|u[agksyz]|c[afuwy]|m[pquwx]|r[eosuw]|j[emop]|z[amw]|w[fs]|y[et]|gp|om|qa|sb|tj|vn)

After some experimentation I discovered that when seeded with [cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x (selected from the output of the first version), it results in the given 275-byte regex.

For completeness, I think the best I achieved manually was the following 282-byte regex:

\.?(a[c-gilmoq-uwxz]|b[abd-jostz]|c[afiuwxy]|d[ejkmoz]|e[cegr-u]|f[ijkmor]|g[ad-ilp-u]|h[kmnrtu]|i[del-oq-t]|j[emop]|k[ipz]|l[abcikr-vy]|m[aep-y]|n[acefgilopruz]|om|p[aflst]|qa|r[eosuw]|s[abeistxy]|t[fjtw]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]|[cmst][cdghk-orvz]|[bgkp][eghmnrwy])


Rust, n ≈ 30 or 31 or 32

On my laptop (two cores, i5-6200U), this gets through n = 1, …, 31 in 53 seconds, using about 2.5 GiB of memory, or through n = 1, …, 32 in 105 seconds, using about 5 GiB of memory.  Compile with cargo build --release and run target/release/correlations.

src/main.rs

extern crate rayon;

type S = u32;
const S_BITS: u32 = 32;

fn cat(mut a: Vec<S>, mut b: Vec<S>) -> Vec<S> {
    if a.capacity() >= b.capacity() {
        a.append(&mut b);
        a
    } else {
        b.append(&mut a);
        b
    }
}

fn search(n: u32, i: u32, ss: Vec<S>) -> u32 {
    if ss.is_empty() {
        0
    } else if 2 * i + 1 > n {
        search_end(n, i, ss)
    } else if 2 * i + 1 == n {
        search2(n, i, ss.into_iter().flat_map(|s| vec![s, s | 1 << i]))
    } else {
        search2(n,
                i,
                ss.into_iter()
                    .flat_map(|s| {
                                  vec![s,
                                       s | 1 << i,
                                       s | 1 << n - i - 1,
                                       s | 1 << i | 1 << n - i - 1]
                              }))
    }
}

fn search2<SS: Iterator<Item = S>>(n: u32, i: u32, ss: SS) -> u32 {
    let (shift, mask) = (n - i - 1, !(!(0 as S) << i + 1));
    let close = |s: S| {
        let x = (s ^ s >> shift) & mask;
        x & x.wrapping_sub(1) == 0
    };
    let (ssy, ssn) = ss.partition(|&s| close(s));
    let (cy, cn) = rayon::join(|| search(n, i + 1, ssy), || search(n, i + 1, ssn));
    cy + cn
}

fn search_end(n: u32, i: u32, ss: Vec<S>) -> u32 {
    if i >= n - 1 { 1 } else { search_end2(n, i, ss) }
}

fn search_end2(n: u32, i: u32, mut ss: Vec<S>) -> u32 {
    let (shift, mask) = (n - i - 1, !(!(0 as S) << i + 1));
    let close = |s: S| {
        let x = (s ^ s >> shift) & mask;
        x & x.wrapping_sub(1) == 0
    };
    match ss.iter().position(|&s| close(s)) {
        Some(0) => {
            match ss.iter().position(|&s| !close(s)) {
                Some(p) => {
                    let (ssy, ssn) = ss.drain(p..).partition(|&s| close(s));
                    let (cy, cn) = rayon::join(|| search_end(n, i + 1, cat(ss, ssy)),
                                               || search_end(n, i + 1, ssn));
                    cy + cn
                }
                None => search_end(n, i + 1, ss),
            }
        }
        Some(p) => {
            let (ssy, ssn) = ss.drain(p..).partition(|&s| close(s));
            let (cy, cn) = rayon::join(|| search_end(n, i + 1, ssy),
                                       || search_end(n, i + 1, cat(ss, ssn)));
            cy + cn
        }
        None => search_end(n, i + 1, ss),
    }
}

fn main() {
    for n in 1..S_BITS + 1 {
        println!("{}: {}", n, search(n, 1, vec![0, 1]));
    }
}

Cargo.toml

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

[dependencies]
rayon = "0.7.0"

Try it online!

I also have a slightly slower variant using very much less memory.


05AB1E, 9 bytes

5Ý3ãʒÇƶOQ

Try it online!

Returns list of lists of digits.


JavaScript (ES7), 41 bytes

Returns the n-th term of the sequence, 0-indexed.

n=>(d=(n--*8-23)**.5)%1?n:'121'[n]^n-~d/2

Try it online!

How?

Main case: \$n > 3\$

The first four terms of the sequence are special, so let's put them aside for now.

For \$n > 3\$, the sequence looks like that:

 n  | [4] 5 [6] 7 8 [ 9] 10 11 12 [13] 14 15 16 17 [18] 19 20 21 22 23 [24] 25 26 27 ...
----+------------------------------------------------------------------------------------
a(n)| [5] 4 [8] 6 7 [12]  9 10 11 [17] 13 14 15 16 [23] 18 19 20 21 22 [30] 24 25 26 ...
----+------------------------------------------------------------------------------------
 k  |  2  -  3  - -   4   -  -  -   5   -  -  -  -   6   -  -  -  -  -   7   -  -  - ...

We can notice that there are in fact two interleaved sub-sequences:

Most values belong to the sub-sequence \$A\$ for which we simply have:

$$A(n) = n - 1$$
Some other values belong to the sub-sequence \$B\$ (highlighted with brackets in the above diagram) whose indices follow the arithmetic sequence 3, 3, 4, 6, 9, 13, 18, 24 ... and for which we have:

$$B(n,k) = n + k - 1$$

where \$n\$ is the index in the main sequence and \$k\$ is the index in the sub-sequence \$B\$.

The indices of \$B\$ in the main sequence are given by:

$$n_k = \frac{k^2 - k + 6}{2}$$

Given \$n\$, we know that the corresponding term in the main sequence belongs to \$B\$ if \$n\$ is an integer solution of the quadratic equation:

$$x^2 - x + 6 - 2n = 0$$

whose discriminant is:

$$\Delta = 1 - 4(6 - 2n) = 8n - 23$$

and whose positive solution is:

$$x = \frac{1 + \sqrt{\Delta}}{2}$$

We expect \$\sqrt{\Delta}\$ to be an integer. Hence the test:

(d = (n-- * 8 - 23) ** .5) % 1

Special cases: \$0 \le n \le 3\$

For \$n < 3\$, the discriminant is negative and taking its square root results in NaN. For \$n = 3\$, the discriminant is \$1\$. Therefore, these first four terms of the sequence are considered to belong to the sub-sequence \$B\$.

Should we just apply our standard formula n - ~d / 2, we'd get:

$$-\frac 1 2, \frac 1 2, \frac 3 2, 3$$

instead of:

$$0, 1, 3, 2$$

Which is why we XOR these results with \$0,1,2\text{ and }1\$ respectively.


Applescript, 20 (100%)
I believe I can claim a perfect score here:

The Applescript Editor (my IDE) automatically converts all keywords to lower case upon compiling/running
Furthermore, defined variable and handler names are case insensitive - For example if a handler myFunc is defined, then the IDE will automatically convert MYFUNC, myfunc, MyFuNc, etc references to myFunc
I have only used alphabetic characters, spaces and newlines, so I don't need to worry about shifted numbers and punctuation characters.

Here is is:
global f
on j at a
set end of a to j
end
on c at a
j at a
j at a
end
on k at a
repeat with q in system info
j at a
end
end
on w at a
set d to count a
j at a
return string id d
end
on z at a
set end of f to a
end
set h to space
set y to h as list
k at y
k at y
set x to w at y
c at y
c at y
c at y
c at y
c at y
set q to w at y
k at y
c at y
c at y
copy y to b
c at y
set s to w at y
set d to w at y
set f to d as list
k at b
k at b
set a to w at b
c at b
j at b
set e to w at b
set y to w at b
set g to w at b
set d to w at b
set i to w at b
c at b
set l to w at b
set m to w at b
set n to w at b
set o to w at b
set p to w at b
j at b
set r to w at b
z at e
z at a
z at r
z at h
z at s
set s to w at b
set t to w at b
set u to w at b
set v to w at b
z at o
z at m
z at p
z at u
z at t
z at e
z at r
z at q
z at h
z at p
z at l
z at e
z at a
z at s
z at e
z at h
z at s
z at t
z at o
z at p
z at h
z at g
z at i
z at v
z at i
z at n
z at g
z at h
z at m
z at e
z at h
z at s
z at d
z at i
z at y
z at t
z at x
f as text

Thanks to the help of @kernigh and @paradigmsort, this is now 1020 bytes, just squeaking in under the 1024 byte limit!
Explanation:

The characters for output string are generated using string id <n>, which returns the character corresponding to the ascii value n
Because we are avoiding digits, each n has has to be generated by more fundamental means.  Specifically we generate each n by counting a list, and then adding another item to that list.  The repeat with q in system info allows us to do this 16 times, as system info always returns a 16-item list.
Using a similar technique, we add each character of the final string in turn to a list.
Finally that last list is coerced to text and printed.

Output:
Using the osascript interpreter, but the Applescript Editor works just as well:
$ # Interpret as-is:
$ osascript dearcase.scpt
Dear Computer, please stop giving me shift!
$
$ # Interpret all lower case:
$ tr A-Z a-z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret all upper case:
$ tr a-z A-Z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret random case for each letter:
$ while read; do for ((i=0;i<${#REPLY};i++)); do c="${REPLY:i:1}"; if ((RANDOM%2)); then printf "%s" "$(tr a-z A-Z <<< "$c")"; else printf "%s" "$(tr A-Z a-z <<< "$c")"; fi; done; echo; done < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$


Determine if a number is less than another

APL (Dyalog Unicode), 2 bytesSBCS

Anonymous tacit prefix function. Requires ⎕IO←0

⊃⍒

Try it online!

⍒ gives the "grade". The indices into the argument that would stably sort it in descending order

If the first element is less than the second, it gives [1,0]
If the the elements are equal, it gives [0,1]
If the second element is less than the second, it gives [0,1]

⊃ picks the first element of that

If the first element is less than the second, it gives 1
If the the elements are equal, it gives 0
If the second element is less than the second, it gives 0


JavaScript (ES6), 114
Using  template strings, the 5 linefeeds are significant are must be counted.
f=s=>(b=(s=s.replace(/(\d+)(.)/g,(x,n,b)=>(b<'P'?'=':'- ').repeat(n).slice(0,n))).replace(/./g,'_'))+`

${s}

`+b


Ruby, 373 bytes

i=gets.chomp
b=[*(i.chars.group_by{|x|x}.group_by{|x,y|y.size}.map{|x|s=x[1].size
x[1][0...s-s%2].map{|x|x[0]}*''}*'').chars.each_slice(2)]
puts [*[*b.size.downto(1).map{|n|b.combination(n).map{|t|[t*'',(h=Hash[t]
s=[]
o=1
i.each_char{|c|s.push(c)if h.keys.include?c
(o=false if s.empty?||!h[s.pop].eql?(c))if h.values.include?c}
o ?s.empty?: o)]}}.find{|x|x[0][1]}][0]][0]

This uses a golfed version of the stack parser here.

It can probably be simplified further, but I don't think my brain can handle any more.

All test cases: http://ideone.com/gcqDkK

With whitespace: http://ideone.com/pLrsHg

Ungolfed (mostly): http://ideone.com/oM5gKX


Ruby, 202 bytes

->n{(r=[*0..n]).product(r,r,r).map{|i|p,b,c,d=i;b>c||c>d||b+c+d>p||p*p-b*b-c*c-d*d!=n||0.upto(p-d<<1){|j|s=" "*j+"*---\\ / "[j%2*4,4]*p*2;(k=b*4-j)>0&&s[0,k]=" "*k;puts s[0,[p*4+1-j,p*4+1-c*4+j].min]}}}

Try it online!

Uses formula per the OEIS sequence: search for solutions where n = p**2 - b**2 -c**2 - d**2.

n =the number of triangular tiles

p =the side length of a large equilateral triangle (pointing downwards)

b,c,d =the side length of three smaller equilateral triangles, which are removed from the corners of the large equilateral triangle to get the required shape.

Some additional conditions (per OEIS) are needed to avoid duplicates:
b<=c<=d and b+c+d<=p


GolfScript (41 chars)

'QZENRPMALHIFKSXJTUVWYGC'8/{' '*n' '+:n}/

Online demo

Connectivity graph:

Q   Z   E   N   R   P   M   A
 \   \   \ /   / \ /   / \ / \
  L   H   I   F   K   S   X   J
   \ / \ / \ /   / \ /   /   /
    T   U   V   W   Y   G   C


Python 3.6, 88 74 bytes

-2 bytes thanks to Dada (use ~)
-5 bytes thanks to Erwan (use f-strings from Python 3.6)

lambda a,b:f"{a}^{b}={a}{f'*{a}'*~-b}={a}{f'+{a}'*~-a**~-b}=1"+"+1"*~-a**b

online ide anyone?

How?

This is an unnamed function taking the two integer inputs a and b each greater than 0 (even though the specification is only for those greater than 1).

In Python 3.6 a new feature is available, namely formatted string literals or "f-strings". These allow run-time evaluated string construction. A leading f (or F) creates such a construct, e.g. f"blah" or f'blah'. Inside an f-string anything between a pair of braces, {...}, is an expression to be evaluated.

As such f"{a}^{b}={a}{f'*{a}'*~-b}={a}{f'+{a}'*~-a**~-b}=1" evaluates each of a, b, a, f'*{a}'*~-b, a, and f'+{a}'*~-a**~-b} as expressions, keeping the ^, =, =, and =1 as strings,all of which gets concatenated together.

The a and b expressions evaluate to the representations of a and b respectively.

The f'*{a}' and f'+{a}' in turn are also f-strings inside these expressions, which evaluate to a with a leading '*' and a leading '+' respectively

To create the required number of as and operations for the * and + portions note that there will be b as multiplied together and a**(b-1) as added together. Each case then requires one less operator sign than the number of as. So we can repeat the f-strings f'*{a}and f'+{a}' (using *) as many times as there are operators and prepend each with a single a. (b-1) is ~-b and (a**(b-1))-1 is ~-a**~-b.

The same  is done for the 1s using (a**b)-1 being ~-**b, but we don't need the overhead of f-strings since 1 is constant, so a standard string repeated is concatenated with +.

Prior Python versions, 81:

lambda a,b:'%s^%s=%s=%s=1'%(a,b,('*%s'%a*b)[1:],('+%s'%a*a**~-b)[1:])+'+1'*~-a**b

Try it online!


Wolfram Language (Mathematica), 45 bytes

CompositeQ@#&&Binomial~Array~{#-1,#}~FreeQ~#&

Try it online!

Every composite number n appears exactly twice on row n and cannot appear afterwards. So the condition for Pascal primes is that they don't appear at all within the first n-1 rows.

As far as I can tell, this is shorter than checking that it appears exactly twice within the first n rows and being able to use !PrimeQ instead.


Ruby 140

->s{r=[1.0]
s.lines.map{|l|n=[i=0.0]*(r.size+1)
l.scan(/\S/).map{|e|a,b=e>?/?e>?]?[0.5]*2:[0,1]:[1,0]
z=r[i]
n[i]+=z*a
n[i+=1]+=z*b}
r=n}
r}

Function that takes as input the string (can be nicely formatted as a pyramid) and returns an array of floats.

Test it online: http://ideone.com/kmsZMe

Pretty straightforward implementation. Here it is ungolfed:

F = -> input {
  probabilities = [1.0]

  input.lines.each { |line|

    new_probabilities = [0.0] * (probabilities.size+1)
    elements = line.scan /\S/
    elements.map.with_index{|el, i|
      deltas = el > '/' ? (el > ']' ? [0.5,0.5] : [0,1]) : [1,0]

      d1, d2 = deltas

      new_probabilities[i] += probabilities[i] * d1
      new_probabilities[i + 1] += probabilities[i] * d2
    }
    probabilities = new_probabilities
  }
  return probabilities
}


Haskell, 39 45 50 52 60 bytes

main=do{(\	陸 ⵙ�商ߜ 新->pure fst)LT
EQ[]3
2$1}

Identifier main has to have type IO a for some type a. When the program is executed, the computation main is performed, and its result is discarded. In this case its type is IO ((a,b)->a).

The result is an application of the function (λ a b c d e f → return fst),
a six-argument constant function returning the function fst (which gives the first element of a 2-tuple), injected into the IO monad. The six arguments are LT (enum for less than), EQ (enum for equality), empty list [], 3, 2 and 1.

What would be spaces are replaced with unique characters that count as spaces: a tab, a non-breaking space, a formfeed, vertical tab, OGHAM SPACE MARK, regular space, newline and carriage return. If any of these are missing, there will be a mismatch in the number of arguments. The parameter names are chosen as three or four byte UTF-8 characters, 陸ⵙ商ߜ新, carefully choosing characters that don't result in duplicate bytes.

Thanks to @BMO for his valuable contributions.

Hex dump:

00000000: 6d61 696e 3d64 6f7b 285c f0a4 b6b8 09ef  main=do{(\......
00000010: a793 c2a0 e2b5 990c e595 860b df9c e19a  ................
00000020: 80e6 96b0 2d3e 7075 7265 2066 7374 294c  ....->pure fst)L
00000030: 540a 4551 5b5d 330d 3224 317d            T.EQ[]3.2$1}

Try it online!


05AB1E, 9 8 bytes

-1 bytes thanks to Magic Octopus Urn

ηOO¹g/‹Ï

Try it online!

η        # Get prefixes
 O       # Sum each
  O¹g/   # Get the mean ( length(prefix list) equals length(original list) )
      ‹Ï # Keep only the value that are less than the mean

05AB1E, 6 bytes

Using the new ÅA command.

ηOÅA‹Ï

Try it online!

η      # Get prefixes
 O     # Sum each
  ÅA   # Get the mean
    ‹Ï #  Keep only the value that are less than the mean


Output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo


Three polyglots, two period-two quines, and one code-golf challenge

JavaScript (ES6) / Python 3, 264 + 258 = 522 bytes

Program A:

a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;print(c);'''
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;'''
print=_=>console.log(c)//'''
print(a%(a,b,c))

Program C:

1//2;alert=print
alert('Wrong language!')

Probably golfable...

JavaScript explanation

Program A:

// Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

// Ignore this line:
1//2;print(c);'''

// Print the Python program (b), replacing the "%s"s with the raw forms of a, b, and c:
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

// Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

// Ignore this line:
1//2;'''

// Define a function `print` which prints `c` (the "Wrong language!" program):
print=_=>console.log(c)//'''

// Call `print`, ignoring the argument (which is NaN):
print(a%(a,b,c))

Program C:

// Ignore this line:
1//2;alert=print

// Alert "Wrong language!":
alert('Wrong language!')

Python explanation

Program A:

# Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

# Print `c` (the "Wrong language!" program):
1//2;print(c);

# Ignore this part:
'''
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

# Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

# Ignore this part:
1//2;'''
print=_=>console.log(c)//'''

# Print the JS program (a), replacing the "%r"s with the raw forms of a, b, and c:
print(a%(a,b,c))

Program C:

# Set `alert` to the function `print`:
1//2;alert=print

# Call this function on "Wrong language!":
alert('Wrong language!')


Haskell, 224 bytes

Not fully tested, because it's so slow (at least O(n*2^n^2)).

t=1<2
x!p|p<0=0|t=mod(div x$2^p)2
l#x=[[sum$map(p&)[-1,1,l+1,-l-1]|p<-[q..q+l]]|q<-[0,l..l*l],let i&v|x!i<1=0|t=x!(i+v)+(i+v)&v]
b%v|b<1=t|t=b==v
s b|l<-length b-1=[l#x|x<-[0..2^l^2],and.map and$zipWith(zipWith(%))b(l#x)]!!0

Explanation:

Basic idea is to represent a board of Red, Blue pieces as a list of lists of 0, 1, where the list of lists is packed into a single integer for easier enumeration. All such integers for the board size are generated and converted to a form with neighbor counts. The first such board that is a valid solution of the input is returned.

-- integer x at position p with out of bounds defined to be 0 (so no bounds checking)
(!) :: (Integral b, Integral r) => r -> b -> r
x ! p | p < 0     = 0
      | otherwise = mod (div x (2^p)) 2

-- Sum of values from position p along vector v (x is implicit)
-- Note that a cartesian vector (x,y) in this representation is (l*x + y)
(&) :: (Integral a, Integral b) => b -> b -> a
p & v | x ! p == 0 = 0
      | otherwise  = x ! (p+v)  +  (p+v) & v

-- Value of board at position p (implicit x, l)
value :: Integral a => a -> a
value p = sum $ map (p&) [-1, 1, l+1, -l-1]

-- Integer to board, where l is length, x is input integer
(#) :: (Integral t, Integral a) => a -> t -> [[t]]
l # x = [[sum $ map (p&) [-1,1,l+1,-l-1] | p <- [q..q+l-1]] | q <- [0,l..l*l]]

-- Comparison operator, to see whether a solved board is a solution of the input
(%) :: (Num a, Ord a) => a -> a -> Bool
b % v | b == 0    = True
      | otherwise = b == v

-- Check one possible solution
check :: Integral a => [[a]] -> Int -> [[a]] -> Bool
check b l x = (and . (map and)) zipWith(zipWith (%)) b (l # x)

-- Solver
solve :: Integral t => [[t]] -> [[t]]
solve b = [l # x | x <- [0..2^l^2], check b l x]
  where
    l = length b

The part that could probably be most golfed is: and.map and$zipWith(zipWith(%)). Otherwise, I caught a few off-by-one errors that added length and could probably be golfed more.


CJam, 45

q~_,@m>0@{@(:T+@T*@+}/\;La{\)_@+@@md@@j@+}jp;

Finally I found a good use of j.

How it works

Long ArrayList Block j executes the block which takes an integer as the parameter, and Long j will call this block recursively in the block. It will also store the values returned by the block in an internal array, which is initialized by the array parameter. It will not execute the block if the input is already in the array, and the value in the array is returned instead.

So if I initialize it with an array of an empty array, the empty array will be returned for input 0, and the block will be executed for any other input.

q~_,@m>0@{@(:T+@T*@+}/\;     " See below. Stack: O decoded-D ";
La                           " Initialized the value with input 0 as empty list. ";
{
  \)_@+@@md@@                " See below. Stack: remainder O quotient ";
  j                          " Call this block recursively except when the same quotient has
                               appeared before, which is impossible except the 0.
                               Stack: remainder O returned_list ";
  @+                         " Append the remainder to the list. ";
}j
p;                           " Format and output, and discard O. ";

CJam, 49 48

q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`

Input should be O I D.

Examples:

$ while read; do <<<$REPLY ./cjam-0.6.2.jar <(echo 'q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`');echo; done
[2] [10] [1 0 0]
[10] [2] [1 0 0]
[10] [2 10] [1 9 0 3 1 5]
[4 3 2] [2 10] [1 9 0 3 1 5]
[10] [100 7 24 60 60] [52 0 0 0 0]
[42] [2 4 8 16] [0 2 10]
[13] [123 456] []
[13] [123 456] [0 0]
[1 1 0 0 1 0 0]
[4]
[7 6 7 5]
[2 0 1 1 0 1 3 0 1]
[3 1 4 4 9 6 0 0]
[1 0]
""
""

How it works

q~           “ Read the input and evaluate. ";
_,@m>        " Rotate I to the right by the length of D. ";
0@{          " For each item in D, with the result initialized to 0: ";
  @(:T+      " Rotate I to the left, and set the original first item to T. ";
  @T*@+      " Calculate result * T + current. ";
}/
\;           " Discard I. ";
{            " Do: ";
  \)_@+      " Rotate O to the right, and get a copy of the original last item. ";
  @@md       " Calculate divmod. ";
  @@         " Move O and the quotient to the top of the stack. ";
}h           " ...while the quotient is not 0. ";
;;           " Discard O and the last 0. ";
_{}?         " If the last item is still 0, discard it. ";
]W%          " Collect into an array and reverse. ";
`            " Turn the array into its string representation. ";


Output all of printable ASCII using all of printable ASCII

Husk, 95 95 bytes
Edit: adjusted to fix bug pointed-out by Neil.  Same bytes
mcW=2`R\.5+46L" !#$%&'()*,-/013789:;<=?@ABCDEFGHIJKMNOPQSTUVXYZ[]^_abdefghijklnopqrstuvwxyz{|}~

Try it online!
Well, 96 bytes in Husk is trivial as a literal string, but 95 bytes was much more tricky.
The strategy that I've used is to (1) output all 95 printable ASCII characters using a program written using only non-repeating ASCII characters (this isn't completely straightforward, since many of the useful commands in Husk are encoded by non-ASCII characters), and then (2) to adjust it so that output is dependent on the length of a literal string containing all the unused characters: this second bit will ensure that all the characters are used, and also that the program is irreducible.
Here's how it works:
mcW=2`R\.5+46L"...
m                   # map this function:
 c                  # ASCII character
                    # across all the elements in this list:
  W                 # indexes of all elements that satisfy:
   =2               # are equal to 2
                    # among all the elements in this list:
     `R             # repeat this value:
       \            # reciprocal of
        .5          # .5
                    # this number of times:
          +46       # add 46 to
             L      # the length of
              "...  # this string
                    # the string consists of all the printable ASCII characters,
                    # with the characters of the program removed.  There are 15
                    # characters in the program, so the remaining 95-15=80 characters
                    # are all present in the string.
                    # So, to output all the ASCII characters up to
                    # 126, we need to add 126-80 = 46.


Java, 99.04 98.46 97.66 lcs() calls

How it works

Exaple: Our line that is to be reconstructed is 00101.
First we find out how many zeros there are, by comparing (here comparing = computing lcs with the original string) by a zeros only string 00000. Then we go through each position, flip the 0 to a 1 and check if we now have a longer common substring. If yes, accept and go to next position, if no, flip the current 1 back to a 0 and go to next position:

For our example of "00101" we get following steps:
input  lcs  prev.'best'
00000  3    0           //number of zeros
̲10000  3    3           //reject
0̲1000  3    3           //reject
00̲100  4    3           //accept
001̲10  4    4           //reject
0010̲1  5    4           //accept

Optimizations

This is just a "naive" implementation, perhaps it would be possible to find a more sophisticated alogrithm checking multiple positions at once. But I am not sure if there really is a better one (e.g. based on the calculation of parity bits similar to the Hamming code), as you can always just evaluate the length of the common substring.

For one given line of digits, this algorithm needs exactly #ofDigitsUntilTheLastOccurenceOf1 + 1 checks. (Substract one if the last digits is an 1.)

EDIT: One small optimization: If we just checked the 2nd last digit and we still need to insert a 1, we know for sure that it must be in the very last position, and can omit the corresponding check.

EDIT2: I just noticed you can apply above idea to the last k ones.

It might of course be possible to achieve a slightly lower score with the this optimization, by reordering the all lines first, because it could be, that you get more lines with ones at the very end but that would obviously be and optimization for the current test cases which is no longer funny.

Runtime

The upper limit is O(#NumberOfBits).

Full code

Here the full code:

package jcodegolf;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

// http://codegolf.stackexchange.com/questions/69799/know-a-sequence-by-its-subsequences

public class SequenceReconstructor {
    public static int counter = 0;
    public static int lcs(String a, String b) { //stolen from http://rosettacode.org/wiki/Longest_common_subsequence#Java
        int[][] lengths = new int[a.length()+1][b.length()+1];

        // row 0 and column 0 are initialized to 0 already

        for (int i = 0; i < a.length(); i++)
            for (int j = 0; j < b.length(); j++)
                if (a.charAt(i) == b.charAt(j))
                    lengths[i+1][j+1] = lengths[i][j] + 1;
                else
                    lengths[i+1][j+1] =
                        Math.max(lengths[i+1][j], lengths[i][j+1]);

        // read the substring out from the matrix
        StringBuffer sb = new StringBuffer();
        for (int x = a.length(), y = b.length();
             x != 0 && y != 0; ) {
            if (lengths[x][y] == lengths[x-1][y])
                x--;
            else if (lengths[x][y] == lengths[x][y-1])
                y--;
            else {
                assert a.charAt(x-1) == b.charAt(y-1);
                sb.append(a.charAt(x-1));
                x--;
                y--;
            }
        }

        counter ++;
        return sb.reverse().toString().length();
    }

    public static String reconstruct(String secretLine, int lineLength){
        int current_lcs = 0;
        int previous_lcs = 0;
        char [] myGuess = new char[lineLength];
        for (int k=0; k<lineLength; k++){
            myGuess[k] = '0';
        }

        //find the number of zeros:
        int numberOfZeros = lcs(secretLine, String.valueOf(myGuess));
        current_lcs = numberOfZeros;
        previous_lcs = numberOfZeros;

        if(current_lcs == lineLength){ //were done
            return String.valueOf(myGuess);
        }

        int numberOfOnes = lineLength - numberOfZeros;
        //try to greedily insert ones at the positions where they maximize the common substring length
        int onesCounter = 0;
        for(int n=0; n < lineLength && onesCounter < numberOfOnes; n++){

            myGuess[n] = '1';
            current_lcs = lcs(secretLine, String.valueOf(myGuess));

            if(current_lcs > previous_lcs){ //accept

                previous_lcs = current_lcs;
                onesCounter ++;

            } else { // do not accept
                myGuess[n]='0';
            }

            if(n == lineLength-(numberOfOnes-onesCounter)-1 && onesCounter < numberOfOnes){ //lets test if we have as many locations left as we have ones to insert
                                                                // then we know that the rest are ones
                for(int k=n+1;k<lineLength;k++){
                    myGuess[k] = '1';
                }
                break;
            }

        }

        return String.valueOf(myGuess);
    }

    public static void main(String[] args) {
        try {

            //read the file
            BufferedReader br;

            br = new BufferedReader(new FileReader("PATH/TO/YOUR/FILE/LOCATION/subsequence_data.txt"));

            String line;

            //iterate over each line
            while ( (line = br.readLine()) != null){

                String r = reconstruct(line, line.length());
                System.out.println(line);     //print original line
                System.out.println(r);        //print current line
                System.out.println(counter/100.0);  //print current number of calls
                if (! line.equals(r)){
                    System.out.println("SOMETHING WENT HORRIBLY WRONG!!!");
                    System.exit(1);
                }

            }

        } catch(Exception e){
            e.printStackTrace();;
        }

    }

}


Python 3, 42 bytes

lambda s:len({*s.upper()}-{*s.lower()})/26

Try it online!

We filter all the non-alphabetic characters out of the string by taking the (set) difference of the uppercase and lowercase representations. Then, we take the length and divide by 26.

Python 3, 46 bytes

lambda s:sum(map(str.isalpha,{*s.lower()}))/26

Try it online!

Count the unique alphabetic (lowercase) characters, and divide by 26. In Python 2 it would require 3 more characters; two for changing {*...} to set(...), and one for making 26 a float: 26., to avoid floor division.

Python 3, 46 bytes

lambda s:sum('`'<c<'{'for c in{*s.lower()})/26

Try it online!

Same length, essentially the same as the previous one, but without "built-in" string method.


Quine that takes as input the name of a language and outputs the same thing implemented in the input language

Ruby

require 'json';s=%q[{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}];j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))

Python

import json,re;s='''{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}''';j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))

Both versions take input on stdin (ruby or python currently) and generate the output to stdout in either language.


Jelly, 43 44 bytes

+1 byte - forgot to double the characters (not that anyone noticed!)

“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y

TryItOnline

How?

Preparation was to compress the data as a run-length encoding of the original image:

Count the length of each run of 1s (space) or 0s (hash) in the image, ignoring new lines - yields a list: [4,2,11,1,1,...];
Subtract one from each number - this gives a range of [0,15];
Treat this as a base-16 number (enumerate the values, v, with index i in reverse and sum up 16**i*v = 19468823747267181273462257760938030726282593096816512166437);
Convert this to base-250: [5,119,249,42,...];
Map into Jelly's code page as indexes: ¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P

Now the code evaluates this number, maps the 1s and 0s to space and hash characters*, doubles each, splits into lines and repeats each the appropriate number of times.
* actually the implementation is performed modulo 2 to save bytes, so spaces are odd and hashes are even:

“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y - Main link: n
“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’                  - base 250 number, as above
                           b⁴                - convert to base 16 (the run length - 1 list)
                             ‘               - increment (vectorises) (the run length list)
                              Ė              - enumerate (pairs each with 1,2,3...)
                               Œṙ            - run length decode
                                              ([1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,4,5,...])
                                  ⁾ #        - string " #"
                                 ị           - index into (1 based and modular)
                                              (makes a bomb without line feeds)
                                     Ḥ       - double (each char becomes a list of 2 chars)
                                      s⁴     - split into slices of length 16
                                        ẋ€³  - repeat each input, n, times
                                           Y - join with line feeds


Python, 299 295 265 263
from threading import*
from socket import*
a='',7;S=socket
u=S(2,2);u.bind(a)
def U():
 while 1:u.sendto(*u.recvfrom(4**8))
Thread(None,U).start()
def C(c,x):
 while c.send(c.recv(1)):1
s=S(2,1);s.bind(a);s.listen(1)
while 1:Thread(None,C,args=s.accept()).start()

handles both udp and tcp.
@MorganThrapp helped saving 33 (!) chars


APL (Dyalog), 17 bytes
1=⊢∨(×/∘,↓)⌺3 3÷⊢

Try it online! (credits to ngn for translating the test cases to APL)
Brief explanation
(×/∘,↓)⌺3 3 gets the product of each element with its neighbours.
Then I divide by the argument ÷⊢, so that each entry in the matrix has been mapped to the product of its neighbors.
Finally I take the gcd of the argument with this matrix ⊢∨, and check for equality with 1, 1=
Note, as with ngn's answer, this fails for some inputs due to a bug in the interpreter.


J I*, 536 431 417 380 263 218 203 197 186 167

p=:4 :0
a=.u:65+9-.~i.26
,_2(5|,:~@|.@(=/)+$$,A.~5*1-0{=/)&.(5 5#:(~.n x,a)&i.)\(,'X'#~2|#)(({.,'X',}.)~1+2*1{&I._2{.\2=/\]) ::]^:_(n=:a(e.~#])'JI'charsub toupper)y
)

(with extensive suggestions from @algorithmshark)

example use:

   'Stack Overflow' p 'The cat crept into the crypt, crapped, and crept out again.'
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY

splits input correctly:

   d=:(({.,'X',}.)~1+2*1{&I._2{.\2=/\]) ::]
   d^:_ 'MASSACHUSETTS'
MASXSACHUSETTS

*replace every J with an I, right?


JavaScript, 47 points (53 tiebreaker)

Array.prototype.group = function(f){
    const r = []
    let k = r
    for(const i of this)
        k !== (k = f ? f(i) : i) ? r.push(a = [i]) : a.push(i)
    return r
}

Body: +52
Identity comparison: -5
Full-length built-ins: +6

Try it:

Array.prototype.group = function(f){
    const r = []
    const k = r
    for(const i of this)
        k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i)
    return r
}

console.log(
    ['a','c','E','G','n'].group(x => x==x.toUpperCase()),
    [1,1,'1'].group(x=>x),
    [3,1,'1',10,5,5].group(x=>x+2),
    [{a:1,b:2,c:3}, {b:2,a:1,c:0}, {c:5}].group(x => JSON.stringify([x.a, x.b])),
    [].group(x=>x)
)

JavaScript, 48 points (56 tiebreaker)

More traditional code golf-y solution.

Array.prototype.group = function(f,r=[],k=r){
    this.map(i=>k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i))
    return r
}

Signature: +9
Body: +44
Identity comparison: -5
Full-length built-ins: +8

Try it:

Array.prototype.group = function(f,r=[],k=r){
    this.map(i=>k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i))
    return r
}

console.log(
    ['a','c','E','G','n'].group(x => x==x.toUpperCase()),
    [1,1,'1'].group(x=>x),
    [3,1,'1',10,5,5].group(x=>x+2),
    [{a:1,b:2,c:3}, {b:2,a:1,c:0}, {c:5}].group(x => JSON.stringify([x.a, x.b])),
    [].group(x=>x)
)


Algorithm - Costliest Possible Route in Grid Puzzle

CJam, 72 71 bytes
q~:Q,mqi:L(2*0aa\{{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}*{Qf=:+}%f-{W>},$W+0=

This is really long and I think a different approach to the question is the only way to get it shorter.
Try it online here
Input is in the following format : <Steps> [<Flat Grid>] . For ex:
9 [0 1 5 2 3 2 2 3 2]

And output is the cost remaining, so 1 in above example.
*Note that [0 1 5 2 3 2 2 3 2] is just a flat representation of the grid
0 1 5
2 3 2
2 3 2

How it works (slightly outdated):
q~                                     "Read the input and evaluate it";
  :Q                                   "Store the array in Q";
    ,mqi:L                             "Do floor of square root of its length";
          LL+((                        "Double length and decrease 2 from the double";
               0aa                     "Put [[0]] on stack. This is the starting index"
                                       "for any path in the grid";
                  \{ ... }*            "Swap to but L + L - 1 on top and run the code"
                                       "block that many times";
 {{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}*    "This block calculates indexes of all possible";
                                       "paths from top left to bottom right of the grid";
 {                            }%       "Map each array based on this code block";
  _[~                                  "Copy the array and start a new array with the"
                                       "contents of the copied one";
     __                                "Make two copies of the last element of the array";
       )L%                             "Increment the element and calculate module L";
          1L?                          "Choose L if module is 0, 1 otherwise";
             +]                        "Add it to the copy of last array element. With"
                                       "this, we have created one of the two possible"
                                       "next step, that is going right. Except if we are"
                                       "on the last column, then go down";
               \[~                     "Swap and start a new array with contents of"
                                       "the original array";
                  __                   "Make two copies of the last element";
                    L/)                "Divide the 2nd copy by L and add 1 to the result";
                       L=1L?           "If index belongs to last row, choose 1, else L";
                            +]         "Add to the first copy of last element and close"
                                       "the array. Now we have the second possible next"
                                       "step, i.e. going down. But if we are on last row"
                                       "then go right";
{Qf=:+}%                               "Map this block on the array containing all"
                                       "possible path indexes";
 Qf=                                   "Get the corresponding cell amount array";
    :+                                 "Sum the array elements to get total path cost";
        {1$)<},                        "Filter out paths which are not possible. i.e."
                                       "paths having total cost more than first input";
               $W=                     "Sort and get the last (highest) path cost";
                  -                    "decrement from input to get remaining steps";


Be the First 1 (leave only the first Truthy)

Python 2, 35 bytes

while 1:b=input();print b;True&=b<1

Try it online! Input and output are lines of True/False.

Based on Dennis's solution. Redefines the variable True to be False after a True input is encountered. That way, any further inputs of True will evaluate to False and be printed as such. Python 3 no longer allows True and False to be redefined, so this answer uses Python 2.

The redefinition is True&=b<1, i.e. True = True & (b<1). When the input b is True, then (b<1) is False (since True==1), so True becomes False. See Kevin Cruijssen's answer for a shorter way to handle this redefinition.


JavaScript (ES6), 147 146 bytes
(p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')

Saved 1 byte thanks to @NinjaBearMonkey!
Explanation
Takes a floorplan as a string and the number of moves. Returns a number.
(p,n)=>                               // p = floor plan as string, n = number of moves
  eval(`                              // use eval to enable for loop without {} or return
    l=p.search\`\n\`+1;               // l = line length
    m=p.match\`[<>v^]\`;              // m = the position and orientation of the person
    for(
      r=                              // r = result at the current step
        d=                            // d = 2 if the person has been defenestrated
          i=0;                        // i = current step
      i++<n&r<3;                      // for each step while the person has not hit a wall
      r-1?0:d=2                       // set d to 2 once the person enters the window
    )
      r=(                             // r = 0 if on " ", 1 if on "#" or 3 if on "|" or "-"
        c=p[m.index+i*                // c = character after current step
          ({v:l,"<":-1,">":1}[m]||-l) // get the index offset of each step
        ]
      )>"#"?3:c>" ";
    +r||d                             // return the result of the current step or d
  `)

Test

var solution = (p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')
<textarea id="floorplan" rows="6" cols="30">-----
|   |
|###|
|   |
| ^ |</textarea>

Moves = <input type="text" id="moves" value="3" />
<button onclick="result.textContent=solution(floorplan.value,moves.value)">Go</button>


Jelly, 32 31 bytes

O“=!"Ṣ$%&/()“)!@#$%^&*(‘iⱮ€PƇ’Q

Try it online!

-1 bytes thanks to Erik the Outgolfer

O“!"Ṣ$%&/()=“!@#$%^&*()‘iⱮ€PƇ%⁵Q
O                                  ord of each character in the input
 “!"Ṣ$%&/()=“!@#$%^&*()‘           Constant that yields the list:
                                      [[33, 34, 183, 36, 37, 38, 47, 40, 41, 61],
                                       [33, 64, 35, 36, 37, 94, 38, 42, 40, 41]
                          €        For each list of numbers:
                         Ɱ           For each ord of the characters in the input:
                        i              Find the index of the ord of the character
                                       in the list of numbers.
                                       If the number is not found, `i` returns zero
                                       which means it's a character from only one
                                       keyboard.
                                   There are now two lists of numbers 1-10.
                            Ƈ      Keep the list(s) that:
                           P         have nonzero product.
                             %⁵    Modulo 10. This maps 10->0.
                               Q   Unique elements. This removes duplicates if the two numbers are the same.


Python, 456 429 381
import turtle as t
L="fl"
R="fr"
d=L*3+R*3
b=(d+R)*3
a=[b,120,L*3+"fflflffflflfrflflfffl"+R*4+"flf",90,b+"ffrfrflffrffrfrfrflflf",120,(R*5+L*5+R+L)*5+"rrfr"+L*5+R*2+L*2+R*4+"f",72,(d+"f")*5+"rfl"+((d+"b")*5)[:-1],120]
l=t.lt
f=t.fd
b=t.bk
r=t.rt
p=input()*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()
for c in a[p]:exec c+"(a[p+1])"
t.getscreen().getcanvas().postscript(file="o")

I implemented a primitive interpreter with l r f b as operators that move the turtle cursor around at the angle of the shapes. At one time, it turns only one angle. I compressed the strings by reusing strings (kind of like psuedo-subroutines), other than that, I didn't check to see if I was using the best path. It outputs to a postscript file.
A little explanation of un-golfed code:
import turtle as t
Left="fl"
Right="fr"
diamond= Left*3 + Right*3
tetrahedron=(d+R)*3 #used to be b

Imports the built-in turtle module and defines the macros that shorten the strings. The turtle module uses commands to move a 'turtle' around the screen (ie forward(100), left(90))
netList=[
   #tetrahedron
   tetrahedron,120,
   #cube
   Left*3+"fflflffflflfrflflfffl"+Right*4+"flf",90,
   #octohedron, builds off the tetrahedron
   tetrahedron+"ffrfrflffrffrfrfrflflf",120,
   #dodecahedron
   (Right*5 + Left*5 + Right + Left)*5
    +"rrfr"+
    Left*5 + Right*2 + Left*2 + Right*4 + "f",72,
   #icosahedron
   (diamond+"f")*5 +"rfl"+((diamond+"b")*5)[:-1],120
]

This list holds the angles and movement sequences. The tetrahedron was saved to reuse with the octohedren.
l=t.left
f=t.forward
b=t.back
r=t.right

This is the part that i like, it makes single character local functions so the calls can be shortened and automated through pre-defined strings.
input=int(raw_input())*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()

This starts by taking the input (between 1 and 5), and converting that to an index that points to the shape string in the netList. These setup turtle to show the whole net. These could be left out if the task was just to draw them, but since we need a picture output they are needed.
for command in netList[input]:
    exec command+"(netList[input+1])"
t.getscreen().getcanvas().postscript(file="o")

The for loop takes the commands in the command sequence string and executes them, so for a string like "fl", this executes "forward(angle);left(angle);" by calling the newly created local functions. the last line outputs a file called 'o' that is in postscript format format using turtle function.
To run:
Copy it into a file and run it from there. When you run it, it will wait for a number input between 1 and 5 (i just changed it so that it asks before setting up turtle). When you input a number, a window pops up and draws the net. if you want it to go faster you can add t.speed(200) before setup.
You can copy-paste it into the interpreter, but when raw_input() is called it consumes the next string you input "t.setup(.9,.9)" instead of a number. So if you do this, copy up until raw_input(), input a number, than copy paste the rest. It is intended to be run as a whole. Or you could copy it into a function and call it.
Here are it's outputs (converted from postscript):
Note: the position of these in the window has changed, but their overall shape is the same.

It's a little brute force for code golf, but I got tired of trying to find a consistent pattern between the shapes.


What's the missing column/row? (GCJ 2016-1A rankfile)

CJam, 5 - 10% = 4.5

This is an unnamed function (block) that takes an array of arrays and returns an array:

{:^$}

(With some inspiration from Dennis)

Try it online

And here is the code I actually submitted at GCJ (24 bytes):

li2*({l~}*]$e`{(2%*~}%S*

Try it online

Explanation:

This basically lists the values that appear an odd number of times.

:^    reduce by symmetric difference; pairs of duplicate values "cancel" each other
$     sort the resulting array


Little Chandler is sad. Draw him a cloud to cheer him up

T-SQL 235 234 229 212 171 73 bytes
This makes use of spatial functionality in SQL Server 2012+.  When it is run in SSMS (SQL Server Management Studio) is produces a spatial results pane.
The input is from variable @i.  I could reduce it further if the input could be taken from a table.
Since table input is now allowed.
SELECT Geometry::UnionAggregate(Geometry::Point(X,Y,0).STBuffer(R))FROM A

I've left the previous solution below.
DECLARE @ VARCHAR(999)='WITH a AS(SELECT *FROM(VALUES('+REPLACE(@i,' ','),(')+'))A(X,Y,R))SELECT Geometry::UnionAggregate(Geometry::Point(X,Y,0).STBuffer(R))FROM a'EXEC(@)

Edit: Remove stray space, surplus into and subquery
171: Replaced table creation with CTE and @s with @.

Break down of the Dynamic SQL
DECLARE @i VARCHAR(100) = '1,4,2 5,2,1 3,1,1 3.5,2,1.2 3,3,0.7 1,2,0.7' -- Input
DECLARE @ VARCHAR(999) = '
WITH a AS(                                       --CTE to produce rows of x,y,r
    SELECT *FROM(VALUES('+
        REPLACE(@i,' ','),(')                    --Format @i to a value set
        +'))A(X,Y,R)
)
SELECT Geometry::UnionAggregate(                 --Aggregate Buffered Points
    Geometry::Point(X,Y,0).STBuffer(R)           --Create point and buffer
    )
FROM a                                           --from the table variable
'
EXEC(@)                                          --Execute Dynamic sql


Jelly, 13 10 bytes

-3 thanks to Nick Kennedy

Feels like the repeated code should be is golf-able, but I have did not managed it...

*€Ṗ%µQƑƇḢị

Try it online! (footer pretty-formats as a grid)

How?

*€Ṗ%µQƑƇḢị - Link: integer, p
 €         - for each n in [1..p]
*          -   exponentiate with:
  Ṗ        -     pop = [1..p-1]
           - ...i.e [[1^1,1^2,...,1^(p-1)],[2^1,2^2,...,2^(p-1)],...,[....,p^(p-1)]]
   %       - modulo p
    µ      - start a new monadic chain (call that list of lists X)
       Ƈ   - keep those which:
      Ƒ    -   are invariant under:
     Q     -     de-duplicate
        Ḣ  - head
         ị - index into the list of lists X


Write the code in Python first
Pyth is so similar to Python that it is pretty easy to translate Python programs to Pyth. However, because Pyth is a single-letter-per-command language, it is sometimes hard to write straight Pyth. By writing in Python first, there is less to think about at a time (since Python is a pretty easy language to code in).


CJam, 121 bytes

5,{_5\-S*\)_'/*"**"@'\*N}%:A['+"+
"]"=*"6**:Lri:M{M(:M;2,{M+2%:J;3,{:I'|J@2\-'.*I'.*?_J"/\\""\/"?JI)3I-?*\++_+'|N}%}%L}*A

Try it online

Takes the input n via STDIN.

I'll add an explanation at some point later. Basically it's all just a bunch of loops in a very naive way. To alternate between the two different body parts, I've got a nested loop over the part and a loop over 0 and 1. Then I just add the outer iterator and the inner one, and use their parity to decide between upwards or downwards pointing triangle.


R, 9 bytes

F:volcano

Try it online!
The sequence operator : coerces its arguments to integers. F is the boolean FALSE, which gets coerced to 0. volcano is one of the many built-in datasets (it gives topographic information about Maunga Whau in New Zealand); since it is a matrix, : fetches the value at position [1, 1] which is luckily equal to 100. The code is therefore equivalent to 0:100.
This answer was inspired by a conversation with Giuseppe and Kirill L. in the comments under Giuseppe's R answer.


J, 20 18 15 14 bytes

-1 thanks to Jonah.

Goes the other way around: sorts the string ('node' -> 'deno'), rotates it back ('deno' -> 'node') and checks if this equals the input. Fits better J trains.

-:<.@-:@#|./:~

Try it online!

How it works

-:<.@-:@#|./:~
           /:~  sort input
  <.@-:@#       length of input, halved and floored
         |.     rotate sorted input by that amount
-:              input equal to that?


How high can you count in different languages?


40 bytes

for a in ${@:2};do eval "${1} ${a}";done

Usage: ./[filename] "[primary command]" [arguments]

Ex. ./twice "sudo apt" update upgrade (Assumes 'twice' as file name)

Was this what you wanted?

Note: Please golf me further if it is possible, and correct me if I'm wrong. This was my first bash entry.


C# (Visual C# Interactive Compiler), 63 bytes

n=>n.Append(0).Where((a,b)=>n.Take(b).Sum()*2==n.Sum()).Count()

Saved 6 bytes thanks to dana

Try it online!


Jelly, 11 10 bytes

FṀ⁸ċþµJ€x"

Input and output are 1-based.

Try it online! or verify all test cases (0-based for easy comparison).


Number of Straight-Chain Alk*nes of given length

MATL, 10 bytes
7K5vBiY^1)

Try it online!
Explanation
This uses the characterization found in OEIS

a(n) is the top left entry of the n-th power of the 3 X 3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1]

7    % Push 7
K    % Push 4
5    % Push 5
v    % Concatenate all numbers into a column vector: [7; 4; 5]
B    % Convert to binary: gives 3×3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1]
i    % Input n
Y^   % Matrix power
1)   % Take the first element of the resulting matrix, i.e. its upper-left corner.
     % Implicitly display


Python 2, 1666 chars

The layout is actually pretty easy - it's the parsing of the input that's a royal pain.  I'm still not sure it is completely correct.

import re,shlex
s=' '
R=range

# Tokenize.  The regex is because shlex doesn't treat 3x and x3 as two separate tokens.  The regex jams a space in between.
r=r'\1 \2'
f=re.sub
x=shlex.shlex(f('([^\d])(\d)',r,f('(\d)([^\d])',r,raw_input())))
T=[s]
while T[-1]:T+=[x.get_token()]
T[-1]=s

# convert implicit * to explicit *
i=1
while T[i:]:
 if(T[i-1].isalnum()or T[i-1]in')]')and(T[i].isalnum()or T[i]in'('):T=T[:i]+['*']+T[i:]
 i+=1

# detect unary -, replace with !
for i in R(len(T)):
 if T[i]=='-'and T[i-1]in'=+-*/^![( ':T[i]='!'
print T

# parse expression: returns tuple of op and args (if any)
B={'=':1,',':2,'+':3,'-':3,'*':4,'/':4,'^':5}
def P(t):
 d,m=0,9
 for i in R(len(t)):
  c=t[i];d+=c in'([';d-=c in')]'
  if d==0and c in B and(B[c]<m or m==B[c]and'^'!=c):m=B[c];r=(c,P(t[:i]),P(t[i+1:]))
 if m<9:return r
 if'!'==t[0]:return('!',P(t[1:]))
 if'('==t[0]:return P(t[1:-1])
 if'I'==t[0][0]:return('I',P(t[2:-1]))
 return(t[0],)

# parenthesize a layout
def S(x):
 A,a,b,c=x
 if b>1:A=['/'+A[0]+'\\']+['|'+A[i]+'|'for i in R(1,b-1)]+['\\'+A[-1]+'/']
 else:A=['('+A[0]+')']
 return[A,a+2,b,c]

# layout a parsed expression.  Returns array of strings (one for each line), width, height, centerline
def L(z):
 p,g=z[0],map(L,z[1:])
 if p=='*':
  if z[1][0]in'+-':g[0]=S(g[0])
  if z[2][0]in'+-':g[1]=S(g[1])
 if p=='^'and z[1][0]in'+-*/^!':g[0]=S(g[0])
 if g:(A,a,b,c)=g[0]
 if g[1:]:(D,d,e,f)=g[1]
 if p in'-+*=,':
  C=max(c,f);E=max(b-c,e-f);F=C+E;U=[s+s+s]*F;U[C]=s+p+s;V=3
  if p in'*,':U=[s]*F;V=1
  return([x+u+y for x,u,y in zip((C-c)*[s*a]+A+(E-b+c)*[s*a],U,(C-f)*[s*d]+D+(E-e+f)*[s*d])],a+d+V,F,C)
 if'^'==p:return([s*a+x for x in D]+[x+s*d for x in A],a+d,b+e,c+e)
 if'/'==p:w=max(a,d);return([(w-a+1)/2*s+x+(w-a)/2*s for x in A]+['-'*w]+[(w-d+1)/2*s+x+(w-d)/2*s for x in D],w,b+e+1,b)
 if'!'==p:return([' -  '[i==c::2]+A[i]for i in R(b)],a+2,b,c)
 if'I'==p:h=max(3,b);A=(h-b)/2*[s*a]+A+(h-b+1)/2*[s*a];return(['  \\/|/\\  '[(i>0)+(i==h-1)::3]+A[i]for i in R(h)],a+3,h,h/2)
 return([p],len(p),1,0)

print'\n'.join(L(P(T[1:-1]))[0])

For the big input in the question, I get:

 /\         2                     2
 |     - m x  b          2 + b m x
 |     --------    = - -------------
 |  3      2                    2
\/ x  e         dx         b m x
                           ------
                        2     2    2
                       b  e       m

Here's some more tricky test cases:

I:(2^3)^4
O:    4
  / 3\
  \2 /

I:(2(3+4)5)^6
O:             6
  (2 (3 + 4) 5)

I:x Integral[x^2,dx] y
O:   /\ 2
  x  | x  dx y
    \/

I:(-x)^y
O:     y
  (- x)

I:-x^y
O:     y
  (- x)

That last one is wrong, some precedence error in the parser.


Fastest square root of an arbitrary size

C++, 140 µs
This is a trivial answer that uses GMP, but I’m submitting it anyway to drive home the point that the test cases are way too small.  Scores in the range of literally nanoseconds per input cannot meaningfully be compared.  We need larger test cases for this to be an interesting challenge.

#include <chrono>
#include <gmpxx.h>
#include <iostream>
#include <vector>

int main() {
  std::vector<mpz_class> numbers;
  mpz_class number;
  while (std::cin >> number)
    numbers.push_back(number);
  auto t0 = std::chrono::high_resolution_clock::now();
  for (auto &number : numbers)
    number = sqrt(number);
  auto t1 = std::chrono::high_resolution_clock::now();
  for (const auto &number : numbers)
    std::cout << number << '\n';
  std::cout
      << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()
      << "ns\n";
}

Try it online!


Python 2, 269

Here's a nice little expression that evaluates to a function. It accepts three lists of integers. Passes all test cases.

lambda A,B,C,w=lambda A,B:cmp(sum(cmp(a,b)for a in A for b in B),0),x=lambda A,B:cmp(sum(cmp(a+c,b+d)for a in A for b in B for c in A for d in B),0): (w(A,B)==w(B,C)==w(C,A)!=0)*((x(A,B)==x(B,C)==x(C,A))*["","strongly ","Grime-"][x(A,B)*w(A,B)]+"nontransitive")or"none"


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

Perl

sub foo {
    @a = (2..5);
    @a = grep $_ != 2, (@a ? @a : (1..5));
    @a = grep $_ != 3, (@a ? @a : (1..5));
    @a = grep $_ != 4, (@a ? @a : (1..5));
    @a = grep $_ != 5, (@a ? @a : (1..5));
}

This actually works for any number of lines removed (as long as it's not all the lines, that is), and can be trivially extended to more than 5 lines.  No helper functions are used, and it even uses only one statement per line.  It relies on the fact that, in the absence of an explicit return statement, the return value of a Perl function is the value of the last statement in it.

Note that (in list context) this code returns an empty list rather than the number 0 if no lines have been deleted.  This could be fixed (e.g. by appending "@a ? @a : 0;" to the last line), but would make the code uglier.  In any case, in scalar context it does return the number of deleted lines, which will be 0 if no lines have been removed. ;-)


Jelly, 30 29 27 25 bytes
_AṢæ..
0,0ṭṚç2\+\<S
Œ!ç€Ṁ

Try it online!
Apparently Jelly's dot product just ignores a list size mismatch and doesn't multiply the extra elements of the other array, just adds them. Shaves off 2 bytes.
Explanation
_AṢæ..              Helper link to calculate distance. Arguments: a, b
_                     subtract the vertices from each other
 A                    take absolute values of axes
  Ṣ                   sort the axes
   æ..                dot product with [0.5]

0,0ṭṚç2\+\<S        Helper link to calculate max cities. Arguments: perm, max
0,0                   create pair [0,0]
   ṭ                  append that to the permutation
    Ṛ                 reverse the permutation (gets the [0,0] to the beginning)
     ç2\              find distances of each pair using the previous link
        +\            find all partial sums
          <           see if each sum was less than the max
           S          sum to count cases where it was

Œ!ç€Ṁ               Main link. Arguments: cities, max
Œ!                    get permutations of cities
  ç€                  find max cities for each permutation using the previous link
    Ṁ                 take the maximum


Charcoal, 52 50 bytes
≔⪪Ａ²θＦ⟦Ｅ³§θ⊖ιθ✂θ¹⟧⊞υ↔ΣＥι⁻×§κ⁰§§ι⊕λ¹×§κ¹§§ι⊕λ⁰⁼⊟υΣυ

Try it online! Link is to verbose version of code. Explanation:
≔⪪Ａ²θ

Split the input into pairs of coordinates.
Ｆ⟦Ｅ³§θ⊖ιθ✂θ¹⟧

Calculate the area of three polygons: the one formed by taking the last, first and second points; the one formed from all of the points (including the test point); the one formed from all of the points except the test point.
⊞υ↔ΣＥι⁻×§κ⁰§§ι⊕λ¹×§κ¹§§ι⊕λ⁰

Use the shoelace formula to calculate the area of that polygon.
⁼⊟υΣυ

Check whether the last area equals the sum of the first two. If this is the case, then the point lies within the polygon.


Python 3, 264 262 bytes

f=lambda s,b='\\',r=str.replace:min(sum([['r'+d+s+d,d+r(r(s[:-1],b,b+b),d,d[1:]+b+d[0])+b*(s[-1:]in[b,d[0]])+s[-1:]+d][d in r(r(s+d[1:],b+b,'x'),b+d[0],b)or r(s,b+b,'')[-1:]==b:]for d in["'",'"',"'''",'"""']],[f(s[:k])+f(s[k:])for k in range(1,len(s))]),key=len)

Try it online!

This works but is very slow without memoization, which you can add with

import functools
f=functools.lru_cache(None)(f)

It found an improved solution for one of the test cases:

t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
 -> 't"e"s"t"s"t"r"i"n"g"'r"\'\'\'\'\'\'\'"'\\'
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'

Previous versions of this answer returned incorrect results on the following, which could be added as test cases:

\\'"\\'\
 -> "\\\\'\"\\\\'\\"
''"""''"""''
 -> '''''"""''"""'\''''


CJam, 16 bytes
4,4,4,4,@@@@\\\\

Try it online!


The sequence of range-exponentiated integers

Python 3, 39 bytes

1-indexed

f=lambda x,n=1:n**x*(x<=n)or f(x-n,n+1)

Try it online!


Smallest python script to print even numbers 0 to 100


Find all Perrin pseudoprimes less than 100 million

Ruby, 183

require'Prime'
f=->a{a=a.flat_map{|n|String===n ? n : n<3?%w[3 0 2][n]:[n-2,n-3]} until a.all?{|x|String===x}
a.map(&:to_i).inject :+}
n=1
p n if f[[n+=1]]%n==0&&!n.prime? while n<1e8

Technically works but runs in an unreasonable amount of time. Try setting the lower bound to 271435 and upper bound to 271450.


Calculate the number of topologies on {1,2,...,n}

Python, 147 chars

N=input()
S=lambda i,K:1+sum(0if len(set(j&k for k in K)-K)-1 else S(j+1,K|set(j|k for k in K))for j in range(i,2**N))
print S(1,set([0,2**N-1]))

Quick for N<=6, slow for N=7, unlikely N>=8 will ever complete.

Individual sets are represented by integer bitmasks, and topologies by sets of bitmasks.  S(i,K) computes the number of distinct topologies you can form by starting with K and adding sets with bitmasks >= i.


Ruby, 139 138 bytes

->s,n{w=(((s=s.chars*' ').size/n=n.hex)**0.5).to_i+k=1&~n
(0..h=w+n/5*~-w).map{|i|s.slice!(0,[w+n/6*~-w,w**k+i,w+h+~i].min*2).center w*4}}

Try it online!

A function taking 2 arguments: a string s and a shape n as a single character in hexadecimal of value 1,2,6 or A. It returns an array of strings.

Explanation

The input string is converted to an array, then joined back into a string with spaces between the characters. The length of this combined string is twice the length of the original string, minus 1. This is divided by a constant, square rooted and rounded to determine the side length w of the polygon to be drawn. The value of the constant is per the table below. For triangles, the square root is rounded down. For others, it needs to be rounded up, so we round down then add k=1&~n to correct.

 Shape   Triangle  Square  Hexagon  Octagon
 n =     1         2       6        10

We iterate through h rows of output. For the triangle and square, h=w.  For the other shapes we need to add w-1 for the hexagon and twice this amount for the octagon. This is done by adding n/5*~-w.

Each line of output is centred and padded to w*4 characters which is enough for all cases. Chunks of s are removed using slice! and outputted. For the octagon the number of symbols to be outputted on each line is the minimum of three numbers: w+w-1 for the centre section, w+i for the top section and w+h-i-1 = w+h+~i for the bottom section. These formulas also work for the hexagon. Note that the numbers have to be multiplied by 2 to account for the spaces.

For the square and triangle, the width of the output is restricted to w. Therefore the formula for the centre section becomes w+n/6*~-w to cover all shapes . For the triangle, the width of the output is further restricted to 1+i. Therefore the formula for the top section becomes w**k+i to cover all shapes.


CJam, 296 284 272 265 264 bytes

"03½åÙªWË#å¥ÜZ2ò'ýðDc}¦Ð£RÞ5ä<Üå§ÖÞYÏuäOe¤¶è2²|ZëßB«ô¬cm"257b2bSf*Qa/"®=&ðS¢Òpût£Ð`ç«^º,[öÄ©3¸YÝæ[%$>\D£(´õÓÆeUØRHáÄ¡ããîùK½ÊÆÇ:UBÍm¥·fèäBÓEwWOkQq×tÌVfè£g8·¨    q©ñäp-ÁgUÚ´Éõ'>r    Ê#"256bDb"
.\"'()-/:\_|J"f=.+sSN+/l~\K>+=

Try it online in the CJam interpreter.

Idea

We start by joining all twelve signs using the string <SP><LF> as separator. We opt for the zodiac signs not to contain trailing spaces, so this allows to separate them easily.

The joined string is 542 bytes long. 236 of these bytes are spaces, which is almost half of them. We build an array that contains a 1 for every space and a 0 for every non-space. This way, encoding a space will only cost 1 bit.

Removing all spaces from the joined string, we are left with the characters <LF>."'()-/:J\_|. Assigning each of them a value (e.g., the index in this string) between 0 and 12

Finally, we decode the above base 2 and base 13 arrays as byte arrays.

In the final program, for a given input DD MM, we compute (int(MM) + (int(DD) > 20)) % 12, reverse the above process to obtain the array of all zodiac signs and select the proper one.

Code

"03½åÙªWË#å¥ÜZ2ò'ýðDc}¦Ð£RÞ5ä<Üå§ÖÞYÏuäOe¤¶è2²|ZëßB«ô¬cm"

        e# Push the encoded space positions.

257b2b  e# Convert from base 257 to base 2.
Sf*     e# Replace 1's with spaces and 0's with empty strings.
Qa/     e# Split at empty strings.

"®=&ðS¢Òpût£Ð`ç«^º,[öÄ©3¸YÝæ[%$>\D£(´õÓÆeUØRHáÄ¡ããîùK½ÊÆÇ:UBÍm¥·fèäBÓEwWOkQq×tÌVfè£g8·¨ q©ñäp-ÁgUÚ´Éõ'>r    Ê#"

        e# Push the encoded non-space characters.

256bDb  e# Convert from base 256 to base 13.

"
.\"'()-/:\_|J"f=

        e# Replace each digit in base 13 by the corresponding character.

.+s     e# Interleave both arrays to create a string.
SN+/    e# Split at trailing spaces.
l~      e# Evaluate the input from STDIN.
\K>+    e# Add 1 to the month if the day is larger than 20.
=       e# Retrieve the corresponding element from the array.


Scala, 605

Golfed:
import scala.util.Random;object G extends App{var b,h=(0,0);while(b==h)h =(Random.nextInt(10),Random.nextInt(10));var s=0;def f{for(y<- 0 to 9){for(x<- 0 to 9)print(if(b==(x,y))"X"else if(h==(x,y))"O"else ".");println};println("score : "+s)};f;while(b!=h){val i=readLine.split(" ");val x=i(1).toInt.ensuring(a=>a>0&&a<10)-1+Random.nextInt(3);b=i(0).toLowerCase match{case "d"=>(b._1,b._2+x) case "u"=>(b._1,b._2-x) case "r"=>(b._1+x,b._2) case "l"=>(b._1-x,b._2)};b=(b._1.min(9).max(0),b._2.min(9).max(0));s+=1;f;println("applied force : "+i(1));println("real force : "+x)};println("Par in "+s+" shots!")}

Just a straight-forwardly implemented ice-breaker. Input is read line-by-line from stdin and power lower then 1 or higher then 9 will result in an AssertionError to comply with the specs.
I am pretty sure there are shorter programs, but let's see how far we get ;-)
Ungolfed:
import scala.util.Random

object Golf extends App {
  var b, h = (0, 0)
  while (b == h) h = (Random.nextInt(10), Random.nextInt(10))
  var s = 0

  def field {
    for (y <- 0 to 9) {
      for (x <- 0 to 9)
        print(if (b ==(x, y)) "X" else if (h ==(x, y)) "O" else ".")
      println
    }
    println("score : " + s)
  }
  field
  while (b != h) {
    val i = readLine.split(" ")
    val x = i(1).toInt.ensuring(a => a > 0 && a < 10) - 1 + Random.nextInt(3)
    b = i(0).toLowerCase match {
      case "d" => (b._1, b._2 + x)
      case "u" => (b._1, b._2 - x)
      case "r" => (b._1 + x, b._2)
      case "l" => (b._1 - x, b._2)
    }
    b = (b._1.min(9).max(0), b._2.min(9).max(0))
    s += 1
    field
    println("applied force : " + i(1))
    println("real force : " + x)
  }
  println("Par in " + s + " shots!")
}

Random example run:

X......O..
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 0

r 8
.......OX.
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 1
applied force : 8
real force : 8

l 1
.......OX.
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 2
applied force : 1
real force : 0

l 1
.......X..
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 3
applied force : 1
real force : 1
Par in 3 shots!


EvaluaterBot

class EvaluaterBot:
    def __init__(self):
        self.c2i = {"C":0, "N":1, "D":2}
        self.i2c = {0:"C", 1:"N", 2:"D"}
        self.history = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.last = [None, None]

    def round(self, last):
        if self.last[0] == None:
            ret = 2
        else:
            # Input the latest enemy action (the reaction to my action 2 rounds ago)
            # into the history
            self.history[self.last[0]][self.c2i[last]] += 1
            # The enemy will react to the last action I did
            prediction,_ = max(enumerate(self.history[self.last[1]]), key=lambda l:l[1])
            ret = (prediction - 1) % 3
        self.last = [self.last[1], ret]
        return self.i2c[ret]

Wins against all previously submitted bots except (maybe) the random bot (but it could have an advantage, because it picks D in a draw and D should optimal) and plays a constant draw against themself.


APL (10)

(Assuming ⎕IO=0. It works on ngn/apl by default, other APLs tend to need an ⎕IO←0 first.)

{⍵|∘.+⍨⍳⍵}

Explanation:

⍳⍵: the numbers [0..⍵)
∘.+⍨: create a sum table
⍵|: numbers in the table mod ⍵


JavaScript (Firefox 30-57), 75 bytes

f=([c,...s])=>c?[for(t of s[0]?f(s):[''])for(d of c+c.toUpperCase())d+t]:[]

67 bytes if the empty string returns [""]:

f=([c,...s])=>c?[for(t of f(s))for(d of c+c.toUpperCase())d+t]:['']


APL (Dyalog), 20 9 bytes

⊃{⌽[⍺]⍵}/

Try it online!

How?

/ - reduce - take the rightmost element in the input (the array) and apply the function with next left element as left argument

{⌽[⍺]⍵} - reverse in the left argument (⍺) dimension

⊃ - flatten the enclosed array


Pyth, 9 bytes

ehc2osNyQ

Input, output formats:

Input:
[1, 2, 3, 4, 5]
Output:
[1, 2, 4]

Demonstration.

ehc2osNyQ
             Q = eval(input())
       yQ    Take all subsets of Q.
    osN      Order those element lists by their sums.
  c2         Cut the list in half.
eh           Take the last element of the first half.

This works because y returns the subsets in such an order that each subset and its complement are equidistant fom the center. Since the sum of a subset and the sum of its complement will always be equidistant from the center, the list after osNyQ will also have this property. Thus, the center two elements of osNyQ are complements, and must have an optimal split. We extract the first of those two elements and print it.


Desmos, 122 bytes

Online use. Copy+paste each equation into an equation box, click "add all" for each box, then click on the point of intersection, then enter in each value as appropriate. each of A, B, and C are the distances for the points (a,b), (c,d), and (E,f), respectively. To get a square root in the value, type sqrt then the value in the box.

\left(x-a\right)^2+\left(y-b\right)^2=AA
\left(x-c\right)^2+\left(y-d\right)^2=BB
\left(x-E\right)^2+\left(y-f\right)^2=CC

Verify the first test case.

Or you can take a look here:


Write an interpreter for my esoteric language Jumper

Ruby, 447 bytes

p,i=$*
l=(i||'').length
r=[0]*l
l.times{|j|r[j]=i[j].ord}
i=j=0
s=p.gsub(/\(.*?\)|\s/,'')
q=s.scan(/(\?)?([#<>=+:-])(\d*)/)
e=->{abort"Error"}
p[/\d\s+\d/]||q*''!=s ?e[]:(r+=[0]until i+1<r.length
c=q[j]
j+=1
f=c[1]
c[0]&&r[i]==0?next: a=c[2]==''? '><+-'[f]?1:0:c[2].to_i
'=+-'[f]&&a>255?e[]: f==?#?i=a :f==?>?i+=a :f==?<?i-=a :f==?=?r[i]=a :f==?+?r[i]+=a :f==?-?r[i]-=a :j=a
i<0?e[]:r[i]%=256)while j<q.length
puts r.first(r.index 0).map(&:chr)*''

Takes both the program and the input via command line arguments.

EDIT: Fixed a few bugs, and added support for invalid syntax at the cost of 40 bytes (while adding a few other optimisations).


05AB1E, 101 bytes + 5 UTF-8 bytes = 116 Total Bytes = 106 Bytes

(LEGACY 05AB1E VERSION, NO LONGER ON TIO)

•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•6B"102345"" ┌─┐└┘"‡6ävyN" A B X"èì}»

Try it online!

The compression:

•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•
# Pattern, converted to base-6 in base-6=214.

111023102310222223102310231022231112251425142511111425142514251114221022231022231023102222231110231023151114251114251425111114222514251411102222231110231110231110222311111225111114222514222514222511142222
# Actual base-6 pattern.

1110231023102222231023102310222311
1225142514251111142514251425111422
1022231022231023102222231110231023
1511142511142514251111142225142514
1110222223111023111023111022231111
1225111114222514222514222511142222
#Pattern split into chunks of 34.

   ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
 ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
 ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
 ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
   ┌─────┐   ┌─┐   ┌─┐   ┌───┐
 ──┘     └───┘ └───┘ └───┘   └────
# Pattern after replacing 0,1,2,3,4,5 with appropriate blocks.

The conversion:

6B                                   # Convert back to base-6.
  "102345"" ┌─┐└┘"‡                  # Replace numbers with appropriate counterparts.
                   6ä                # Split into 6 equal parts (the rows).
                     vy           }  # For each row (chunk).
                       N" A B X"èì   # Push label at index [i], prepend to line.
                                   » # Print all separated by newlines.

Using the CP-1252 encoding.