Pyth, 29 28 bytes

M/*FPJm*F.!MhMrd8aFCB,SGSHeJ

Try it online in the Pyth Compiler.

Algorithm

The result does not depend on the order of A, so we can assume it to be sorted. This means that B must also be sorted to attain the maximal dot product.

Now, if r1, … rn are the length of the runs of the sorted A, there are ∏rk! different rearrangements of the elements of A that still result in ascending order.

Likewise, if s1, … sn are the length of the runs of the sorted B, there are ∏sk! different rearrangements of the elements of B that still result in ascending order.

However, this counts all pairings multiple times. If we take the pairs of of the corresponding elements of sorted A and sorted B and define t1, … tn as the length of the runs of the resulting array, ∏tk! is the aforementioned multiplier.

Thus, the desired result is (∏rk!) × (∏sk!) ÷ (∏tk!).

Code

M/*FPJm*F.!MhMrd8aFCB,SGSHeJ

M                             Define g(G,H):
                      SGSH      Sort G and H.
                     ,          For the pair of the results.
                   CB           Bifurcated zip (C).
                                This returns [[SG, SH], zip([SG, SH])].
                 aF             Reduce by appending.
                                This returns [SG, SH, zip([SG, SH])].
      m                         Map; for each d in the resulting array:
              rd8                 Perform run-length encoding on d.
            hM                    Mapped "head". This returns the lengths.
         .!M                      Mapped factorial.
       *F                         Reduce by multiplication.
     J                          Save the result in J.
    P                           Discard the last element.
  *F                            Reduce by multiplication.
 /
                          eJ    Divide the product by the last element of J.
                                Return the result of the division.

Verification

I've pseudo-randomly generated 100 test cases of length 6, which I've solved with the above code and this brute-force approach:

Ml.Ms*VGZ.pH

M             Define g(G,H) (or n(G,H) on second use):
         .pH    Compute all permutations of H.
  .M            Filter .pH on the maximal value of the following;
                 for each Z in .pH:
     *VGZ         Compute the vectorized product of G and Z.
    s             Add the products.
                  This computes the dot product of G and Z.
 l              Return the length of the resulting array.

These were the results:

$ cat test.in
6,9,4,6,8,4,5,6,5,0,8,2
0,7,7,6,1,6,1,7,3,3,8,0
3,6,0,0,6,3,8,2,8,3,1,1
2,3,0,4,0,6,3,4,5,8,2,4
9,1,1,2,2,8,8,1,7,4,9,8
8,3,1,1,9,0,2,8,3,4,9,5
2,0,0,7,7,8,9,2,0,6,7,7
0,7,4,2,2,8,6,5,0,5,4,9
2,7,7,5,5,6,8,8,0,5,6,3
1,7,2,7,7,9,9,2,9,2,9,8
7,2,8,9,9,0,7,4,6,2,5,3
0,1,9,2,9,2,9,5,7,4,5,6
8,4,2,8,8,8,9,2,5,4,6,7
5,2,8,1,9,7,4,4,3,3,0,0
9,3,6,2,5,5,2,4,6,8,9,3
4,2,0,6,2,3,5,3,6,3,1,4
4,8,5,2,5,0,5,1,2,5,9,5
6,8,4,4,9,5,9,5,4,2,8,7
8,9,8,1,2,2,9,0,5,6,4,9
4,7,6,8,0,3,7,7,3,9,8,6
7,5,5,6,3,9,3,8,8,4,8,0
3,8,1,8,5,6,6,7,2,8,5,3
0,9,8,0,8,3,0,3,5,9,5,6
4,2,7,7,5,8,4,2,6,4,9,4
3,5,0,8,2,5,8,7,3,4,5,5
7,7,7,0,8,0,9,8,1,4,8,6
3,9,7,7,4,9,2,5,9,7,9,4
4,5,5,5,0,7,3,4,0,1,8,2
7,4,4,2,5,1,7,4,7,1,9,1
0,6,2,5,4,5,1,8,0,8,9,9
3,8,5,3,2,1,1,2,2,2,8,4
6,1,9,1,8,7,5,6,9,2,8,8
6,2,6,6,6,0,2,7,8,6,8,2
0,7,1,4,5,5,3,4,4,0,0,2
6,0,1,5,5,4,8,5,5,2,1,6
2,6,3,0,7,4,3,6,0,5,4,9
1,4,8,0,5,1,3,2,9,2,6,5
2,7,9,9,5,0,1,5,6,8,4,6
4,0,1,3,4,3,6,9,1,2,7,1
6,5,4,7,8,8,6,2,3,4,1,2
0,3,6,3,4,0,1,4,5,5,5,7
5,4,7,0,1,3,3,0,2,1,0,8
8,6,6,1,6,6,2,2,8,3,2,2
7,1,3,9,7,4,6,6,3,1,5,8
4,8,3,3,9,1,3,4,1,3,0,6
1,4,0,7,4,9,8,4,2,1,0,3
0,4,1,6,4,4,4,7,5,1,4,2
0,0,4,4,9,6,7,2,7,7,5,4
9,0,5,5,0,8,8,9,5,9,5,5
5,7,0,4,2,7,6,1,1,1,9,1
3,1,7,5,0,3,1,4,0,9,0,3
4,4,5,7,9,5,0,3,7,4,7,5
7,9,7,3,0,8,4,0,0,3,1,0
2,4,4,3,1,2,5,2,9,0,8,5
4,8,7,3,0,0,9,3,7,3,0,6
8,9,1,0,7,7,6,0,3,1,8,9
8,3,1,7,3,3,6,1,1,7,6,5
6,5,6,3,3,0,0,5,5,0,6,7
2,4,3,9,7,6,7,6,5,6,2,0
4,8,5,1,8,4,4,3,4,5,2,5
7,5,0,4,6,9,5,0,5,7,5,5
4,8,9,5,5,2,3,1,9,7,7,4
1,5,3,0,3,7,3,8,5,5,3,3
7,7,2,6,1,6,6,1,3,5,4,9
9,7,6,0,1,4,0,4,4,1,4,0
3,5,1,4,4,0,7,1,8,9,9,1
1,9,8,7,4,9,5,2,2,1,2,9
8,1,2,2,7,7,6,8,2,3,9,7
3,5,2,1,3,5,2,2,4,7,0,7
9,6,8,8,3,5,2,9,8,7,4,7
8,8,4,5,5,1,5,6,5,1,3,3
2,6,3,5,0,5,0,3,4,4,0,5
2,2,7,6,3,7,1,4,0,3,8,3
4,8,4,2,6,8,5,6,2,5,0,1
7,2,4,3,8,4,4,6,5,3,9,4
4,6,1,0,6,0,2,6,7,4,9,5
6,3,3,4,6,1,0,8,6,1,7,5
8,3,4,2,8,3,0,1,8,9,1,5
9,6,1,9,1,1,8,8,8,9,1,4
3,6,1,6,1,4,5,1,0,1,9,1
6,4,3,9,3,0,5,0,5,3,2,4
5,2,4,6,1,2,6,0,1,8,4,0
3,5,7,6,3,6,4,5,2,8,1,5
6,3,6,8,4,2,7,1,5,3,0,6
9,1,5,9,9,1,1,4,5,7,3,0
1,6,7,3,5,8,6,5,5,2,6,0
2,8,8,6,5,5,2,3,8,1,9,8
0,4,5,3,7,6,2,5,4,3,2,5
5,1,2,3,0,3,4,9,4,9,4,9
5,8,2,2,0,2,4,1,1,7,0,3
0,6,0,0,3,6,3,6,2,2,2,9
2,4,8,1,9,4,0,8,8,0,4,7
3,9,1,0,5,6,8,8,2,5,2,6
5,3,8,9,1,6,5,9,7,7,6,1
8,6,9,6,1,1,6,7,7,3,2,2
7,2,1,9,8,8,5,3,6,3,3,6
9,9,4,8,7,9,8,6,6,0,3,1
8,3,0,9,1,7,4,8,0,1,6,2
8,2,6,2,4,0,2,8,9,6,3,7
1,0,8,5,3,2,3,7,1,7,8,2
$ while read; do
> pyth -c 'M/*FPJm*F.!MhMrd8aFCB,SGSHeJMl.Ms*VGZ.pHAc2Q,gGHnGH' <<< "$REPLY"
> done < test.in
[4, 4]
[4, 4]
[8, 8]
[4, 4]
[8, 8]
[2, 2]
[4, 4]
[4, 4]
[4, 4]
[36, 36]
[2, 2]
[8, 8]
[24, 24]
[8, 8]
[2, 2]
[2, 2]
[6, 6]
[2, 2]
[8, 8]
[2, 2]
[12, 12]
[2, 2]
[8, 8]
[12, 12]
[4, 4]
[12, 12]
[4, 4]
[6, 6]
[8, 8]
[8, 8]
[6, 6]
[4, 4]
[48, 48]
[8, 8]
[4, 4]
[1, 1]
[4, 4]
[4, 4]
[8, 8]
[4, 4]
[12, 12]
[2, 2]
[96, 96]
[2, 2]
[4, 4]
[2, 2]
[6, 6]
[24, 24]
[24, 24]
[48, 48]
[4, 4]
[8, 8]
[12, 12]
[8, 8]
[4, 4]
[2, 2]
[24, 24]
[16, 16]
[2, 2]
[8, 8]
[24, 24]
[4, 4]
[24, 24]
[4, 4]
[12, 12]
[8, 8]
[12, 12]
[4, 4]
[8, 8]
[4, 4]
[16, 16]
[4, 4]
[8, 8]
[8, 8]
[4, 4]
[4, 4]
[4, 4]
[4, 4]
[72, 72]
[24, 24]
[4, 4]
[4, 4]
[4, 4]
[2, 2]
[12, 12]
[4, 4]
[8, 8]
[4, 4]
[36, 36]
[6, 6]
[12, 12]
[8, 8]
[4, 4]
[2, 2]
[8, 8]
[24, 24]
[6, 6]
[1, 1]
[2, 2]
[2, 2]

To verify my submission satisfies the speed requirement, I've ran it with this test case.

$ time pyth -c 'M/*FPJm*F.!MhMrd8aFCB,SGSHeJAc2QgGH' < test-large.in | md5sum
5801bbf8ed0f4e43284f7ec2206fd3ff  -

real    0m0.233s
user    0m0.215s
sys     0m0.019s


Octave, 46 43 36 30 23 bytes
tic;(-1e3:1e3)',toc*1e3

This will print:
ans =

  -1000
   -999
   -998
   -997
   -996
   -995

If you don't like the ans = , then we have to add an additional 6 bytes for disp:
tic;disp((-1e3:1e3)'),toc*1e3

Saved a lot of bytes thanks to a few reminders from rahnema1.
Explanation:
tic;                              % Starts timer
         (-1e3:1e3)'              % A vertical vector -1000 ... 1000
    disp((-1e3:1e3)'),            % Display this vector
                      toc*1e3     % Stop the timer and output the time in milliseconds


Python

Real Y2K bugs are about the year being represented as a 2-digit number. And doing something wrong when that number overflows to 0. Such as this nuclear missile watchdog, launching all ICBMs if we haven't received a heartbeat message from HQ in 60 seconds.

import datetime, select, socket, sys

launch_icbm = lambda: (print("The only winning move is not to play"), sys.exit(11))
now  = lambda: int(datetime.datetime.now().strftime("%y%m%d%H%M%S"))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 1957))
last_message_received = now()

while True:
    r, w, e = select.select([sock], [], [], 10)
    if sock in r:
        msg = sock.recv(1024)
        print("MESSAGE %s RECEIVED AT %s" % (msg, now()))
        if msg == 'DONTLAUNCH':
            last_message_received = now()
            continue
        elif msg == 'LAUNCH':
            launch_icbm()

    # Is HQ dead?
    abs(now() - last_message_received) > 60 and launch_icbm()


POV-Ray, 512 characters
Here's my try. I didn't manage to replicate the lighting, so I've decided to keep the variation of highlight positions rather than to put the lights further away to keep the background brighter.
The area shadow is rather low-quality. I might as well turn it off completely (and save precious characters), but if someone is willing to donate some computing power and crank up the shadow quality and/or the dither quality, I'll gladly accept.
#include"functions.inc"
camera{location<-3,5,-6>right x look_at 0 focal_point 0 aperture 1 blur_samples 9}
#macro s(p)sphere{pi*p+y/3 1 pigment{rgb<2,8,2>/9}finish{phong .5 phong_size 5 specular 1 roughness .001}}#end
#macro l(p,c)light_source{p c/8 area_light 9*x,9*z,3,3}#end l(<6,6,0>,<8,4,8>)l(<0,6,0>,<4,8,8>)
isosurface{function{y/3+pow(cos(x)*cos(z),2)/2}contained_by{box{-9,100}}pigment{tiling 1 color_map{[.9 rgb 1][1 rgb 0]}scale .5/pi}}
s(0)s(<0,0,-1>)s(<-1,0,0>)s(<0,0,2>)s(<2,0,1>)s(<2,0,3>)

Result:

ungolfed:
#version 3.7;
#include "functions.inc"
global_settings{assumed_gamma 1}
camera{
  location <-3,5,-6>
  right x //set the aspect ratio
  look_at 0
  focal_point 0 aperture 1 blur_samples 9
}

#macro l(p,c) // position, color
  light_source{
    p c/8
    area_light 9*x,9*z,3,3
  }
#end
l(<6,6,0>,<8,4,8>)
l(<0,6,0>,<4,8,8>)

isosurface{
  function{y/3+pow(cos(x)*cos(z),2)/2}
  contained_by{box{-9,100}}
  pigment{
    tiling 1
    color_map{[.9 rgb 1][1 rgb 0]}
    scale .5/pi
  }
}
#macro s(p) //position
  sphere{
    pi*p+y/3 1
    pigment{rgb<2,8,2>/9}
    //phong for the wide highlights, specular for the small ones.
    finish{phong .5 phong_size 5 specular 1 roughness .001}
  }
#end
s(0)
s(<0,0,-1>)
s(<-1,0,0>)
s(<0,0,2>)
s(<2,0,1>)
s(<2,0,3>)

P.S.: I've only counted the five line-breaks to round the character count to a perfectly round number.


Python, 121 110 109 108 104 103 characters
p,n,m=[2],3,0
while 1:
 if all(n%x for x in p):
  c=n-p[0]
  if m<c:m=c;print(p[0],n,c)
  p=[n]+p
 n+=1

First time I tried to answer here, I hope I did it right... not sure I even counted the characters right.
Hmmm, I could save another character on the print by downgrading to Python 2.x...


Jelly, 10 7 bytes

BṡRḄFS_

Try it online!

How it works

BṡRḄFS_  Main link. Input: n

B        Convert n to base 2.
  R      Yield [1, ..., n].
 ṡ       Get all overlapping slices of lengths 1 to n.
         This yields empty arrays if the slice size is longer than the binary list.
   Ḅ     Convert each binary list to integer.
    F    Flatten the resulting, nested list.
     S   Compute the sum of the result.
      _  Subtract n from the sum.


It's getting harder and harder to be composite these days

Pyth, 24 bytes

Pu+GfP_+Tf!fP_+ZYG)eGQ]2

Demonstration

Basically, we start with [2], then add elements 1 at a time by alternately finding d, then adding an element, and so forth. Outputs the first n elements of the sequence.

Contains a filter inside a first integer filter inside a first integer filter inside an apply repeatedly loop.

Explanation:

Pu+GfP_+Tf!fP_+ZYG)eGQ]2
 u                   Q]2    Starting with `[2]`, do the following as many times
                            as the input
         f        )         Starting from 1 and counting upward, find d where
          !f     G          None of the elements in the current list
            P_+ZY           plus d give a prime.
    f              eG       Starting from the end of the current list and counting
                            upward, find the first number which
     P_+T                   plus d gives a prime.
  +G                        Append the new number to the current list
P                           Trim the last element of the list

There's obvious repeated effort between the two "Add and check if prime" calls, but I'm not sure how to eliminate it.


Recreate the Windows ME screensaver as ASCII

Nothing says nostalgia quite like...

QBasic, 332 bytes

INPUT t,w,h
RANDOMIZE
CLS
1b=INT(RND*4)
d=b
IF b MOD 2THEN c=(b-1)/2*(w-1)+1:r=1+INT(RND*h)ELSE c=1+INT(RND*w):r=b/2*(h-1)+1
WHILE t
LOCATE r,c
m=(b+d)MOD 4
IF b=d THEN x=8.5*m ELSE x=13*m+(1<((b MOD m*3)+m)MOD 5)
?CHR$(179+x);
r=r-(d-1)MOD 2
c=c-(d-2)MOD 2
b=d
d=(4+d+INT(RND*1.25-.125))MOD 4
t=t-1
IF(r<=h)*(c<=w)*r*c=0GOTO 1
WEND

QBasic is the right language for the task because:

Its encoding includes box drawing characters--no need for Unicode
LOCATE allows you to print to any location on the screen, overwriting what was there previously
Microsoft®

Specifics

This is golfed QBasic, written and tested on QB64 with autoformatting turned off. If you type/paste it into the actual QBasic IDE, it will add a bunch of spaces and expand ? into PRINT, but it should run exactly the same.

The program inputs three comma-separated values: ticks, width, and height. It then asks for a random-number seed. (If this behavior isn't acceptable, change the second line to RANDOMIZE TIMER for +6 bytes.) Finally, it draws the pipes to the screen.

The maximum dimensions that can be entered are 80 (width) by 25 (height). Giving a height of 25 will result in the bottom row getting cut off when QBasic says "Press any key to continue."

How?

TL;DR: A lot of math.

The current row and column are r and c; the current direction is d and the previous direction is b. Direction values 0-3 are down, right, up, left. Arithmetic translates those into the correct step values for r and c, as well as the correct edge coordinates to start on.

The box drawing characters │┐└─┘┌ are code points 179, 191, 192, 196, 217, and 218 in QBasic. Those appear pretty random, but it still used fewer characters to generate the numbers with some (pretty convoluted, I'm-not-sure-even-I-understand-it) math than to do a bunch of conditional statements.

The code for changing direction generates a random number between -0.125 and 1.125 and takes its floor. This gives -1 10% of the time, 0 80% of the time, and 1 10% of the time. We then add this to the current value of d, mod 4. Adding 0 keeps the current direction; adding +/-1 makes a turn.

As for control flow, the WHILE t ... WEND is the main loop; the section before it, starting with line number 1 (1b=INT(RND*4)), restarts the pipe at a random edge. Whenever r and c are outside the window, we GOTO 1.

Show me the GIF!

Here you go:

This was generated by a somewhat ungolfed version with animation, color, and an automatic random seed:

INPUT t, w, h
RANDOMIZE TIMER
CLS

restart:
' Calculate an edge to start from

b = INT(RND * 4)
'0: top edge (moving down)
'1: left edge (moving right)
'2: bottom edge (moving up)
'3: right edge (moving left)
d = b

' Calculate column and row for a random point on that edge
IF b MOD 2 THEN
    c = (b - 1) / 2 * (w - 1) + 1
    r = 1 + INT(RND * h)
ELSE
    c = 1 + INT(RND * w)
    r = b / 2 * (h - 1) + 1
END IF
COLOR INT(RND * 15) + 1

WHILE t
    ' Mathemagic to generate the correct box-drawing character
    m = (b + d) MOD 4
    IF b = d THEN
        x = 17 * m / 2
    ELSE
        x = 13 * m + (1 < ((b MOD m * 3) + m) MOD 5)
    END IF
    LOCATE r, c
    PRINT CHR$(179 + x);

    ' Update row and column
    r = r - (d - 1) MOD 2
    c = c - (d - 2) MOD 2
    ' Generate new direction (10% turn one way, 10% turn the other way,
    ' 80% go straight)
    b = d
    d = (4 + d + INT(RND * 1.25 - .125)) MOD 4

    ' Pause
    z = TIMER
    WHILE TIMER < z + 0.01
        IF z > TIMER THEN z = z - 86400
    WEND

    t = t - 1
    IF r > h OR c > w OR r = 0 OR c = 0 THEN GOTO restart
WEND


Program a 2048 AI using an existing Framework

Sinker/Shaker, 65 bytes

Here's mine. It's as blind and simple as they come.

if(startup){startup=false;a=0}b=(a++)%4;move(frozen>2?0:b==0?2:b)

Uncompressed(ish)...

if(startup){startup=false;a=0;}
b=(a++)%4;
move(frozen>2?0:b==0?2:b)

All it does is repeats down, right, down, left, etc. and hits up once if it gets stuck. It doesn't always do very well, but it'll occasionally get 512s. My high score during testing was 7520.


APL, 18 12 bytes

⍉(2×⎕)3⍴'↑↓'

This constructs a 2n x 3 matrix, where n is the input (⎕), filled with the characters ↑ and ↓. The transpose (⍉) of this matrix is then printed.

You can try it online.


Python 2, 152

n=input();x=N=2*n
while~N<x:s='';y=n*3;exec"a=x+y;q=[0,a>N,x-y>N,-x>n,-a>N,y-x>N,x>n,1];s+=' BYROPG.'[q.index(sum(q)<~a%2*3)];y-=1;"*(y-~y);print s;x-=1

This is, in retrospect, the wrong approach for Python, but I'm posting it here in case someone can make use of it. Rather than explaining this mess of code, I'll try to say the idea behind it.

The idea is to use triangular coordinates, in which the triangular lattice corresponds to integer triples (a,b,c) with a+b+c=0.

(Here, the lattice points are drawn as hexagons.)

We can convert Cartesian coordinates to triangular ones as

a = (x+y)/2
b = (x-y)/2
c = -x

noting that x and y must have the same parity, or otherwise it's off-checkerboard and we should print a space.

In triangular coordinates, the bounding lines of the six-sided star have equations: a==n, b==n, c==n, a==-n, b==-n, c==-n.

So, we can determine what region we're in by which of [a,b,c,-a,-b,-c] are greater than n.

If none are, we're in the center and print a dot.
If exactly one is, we're in one of the six outer triangles, and print the letter corresponding to the index.
If two or more are, we're outside the board, and print a space.

The bounding rectangle requires that we do this for x in the closed interval [-2*n,2*n] and y in the closed interval [-3*n,3*n].


Python 2, 41 bytes

lambda n:min(map(abs,map(int,n.split())))

Try it online!


APL (30)

{' x'[1+(⍎⍵⌷'⌽+⍉⊖')≤/¨⍳2⍴⍺]}/⎕

Explanation:

{...}/⎕: reduce given function over the input (so if the input has 2 numbers, just calls the function with those two numbers, ⍺ being the left number and ⍵ the right number)
≤/¨⍳2⍴⍺: Make an ⍺-by-⍺ coordinate matrix and set those positions where the X coordinate is not greater than the Y coordinate, giving a bitfield.
(⍎⍵⌷'⌽+⍉⊖'): select a transformation function given by ⍵ to put the triangle right-side-up.
' x'[1+...]: add one to the bitfield, and use the result as an index into the string ' x', so putting space for 0 and x for 1.


Write a program that can draw 2-D shapes using ASCII or any other method

Logo
Just install it!
Then things like triangles, squares, pentagons and circles are defined as:
to triangle :length
    polygon :length 3
end

to square :length
    polygon :length 4
end

to pentagon :length
    polygon :length 5
end

to circle :length
    polygon :length 360
end

to polygon :length :sides
    repeat :sides [forward :length right 360/:sides]
end

Easy peasy lemon squeezy...


JavaScript (ES7),  25 24  23 bytes
Returns the \$n\$-th term, 1-indexed.

n=>n>(++n**.5|0)**2?2:1

Try it online!
How?
We have \$a(n)=2\$ iff the difference between \$n+1\$ and the previous square is greater than \$1\$:
$$n+1-\left\lfloor \sqrt{n+1}\right\rfloor^2>1$$
which boils down to:
$$n>\left\lfloor \sqrt{n+1}\right\rfloor^2$$


Reverse two sections of a string around a pivot

Mathematica, 42 bytes
Reverse@StringSplit[##,2]~StringRiffle~#2&

Try it online!


Inverse quine: print everything except your program

Ruby, 92 91 86 bytes
Saved 5 bytes thanks to a comment by @Sisyphus on another answer.

eval s="a=*?\0..?\x7f;90.times{|i|puts a.product(*[a]*i).map(&:join)-['eval s=%p'%s]}"

Try it online!
Forms arrays containing all permutations of ASCII characters (codepoints 00 to 127) of length 1 to 91, then subtracts from each the string eval$s=%q(#$s), which is equivalent to the full program (because of the interpolated string $s).
eval s="                               # evaluate s, a double-quoted string that contains most of the program
  a=*?\0..?\x7f;                       # create array of ASCII characters 00 to 127
  90.times{|i|                         # for permutations of length i = 1 to 91:
    puts a.product(*[a]*i).map(&:join)   # print all strings of length i...
    -['eval$s=%p'%s]                     # not equal to the full program
  }
"


¿xu ti te gismytermorna? (Is it a valid gismu?)

Ruby, 302 252 bytes
c='[cjsztdpbfvkgxmnlr]'
v=c+'[aeiou]'
z=!1
n=/#{c+v+v}/=~(s=gets.chop)*2
(n==0||n==2)&&289.times{|k|q=[i=k%17,j=k/17].max
z||=(x=s[n,2])==c[j+1]+c[i+1]&&['UeUeJOJOJOJOETJ
:'[i].ord-69>>j&1-j/14>0,i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]}
p z

A few more bytes could be saved as follows:
Initialize z to false using z=!c='[cjsztdpbfvkgxmnlr]'. This works but gives the warning warning: found = in conditional, should be ==.
Change from a program to a function (I left it as a program because according to the question, shortest "program" in bytes wins.)
Summary of changes from first post
Major overhaul of regex/matching part.
Constant 72 changed to 69 so that the lowest ASCII code in the magic string is 10 instead of 13. This enables a literal newline to be used in the golfed version instead of an escape sequence.
Magic string 'mzxcxkx' replaces arithmetic rules for the 5 prohibited characters in the CVCCV type table.
ungolfed version
added whitespace and changed newline in magic string to a \n
c='[cjsztdpbfvkgxmnlr]'                                   #c=consonants
v=c+'[aeiou]'                                             #v=consonant+vowel
z=!1                                                      #Set z to false (everything is truthy in Ruby except nil and false.)
n=/#{c+v+v}/=~(s=gets.chop)*2                             #Get input and duplicate it. do regex match, n becomes the index of the double consonant.
(n==0||n==2)&&                                            #If n==0 (ccvcv) or n==2 (cvccv)
   289.times{|k|                                          #iterate 17*17 times
     q=[i=k%17,j=k/17].max                                #generate row and column, find their maximum.
     z||=                                                 #OR z with the following expression:
     (x=s[n,2])==c[j+1]+c[i+1]&&                          #double consonant == the pair corresponding to j,i AND either
       ["UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0,       #this expression or
       i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]#this expresson, depending on the value of n/2
   }
p z                                                       #print output

Explanation of matching
The two characters in the input string s[n,2]are compared with the character pair of the iterating loop. If they match and the consonant-vowel regex pattern is correct, the row and column values i,j are checked for validity. Careful ordering of the consonants helps here.
For CVCCV:
i!=j                        It is forbidden for both consonants to be the same
(k%2<1||q>12)               It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this restriction. As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”, and both “ls” and “lz”, are permitted.
q>3                         It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.
!'mzxcxkx'.index(x)         The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

For CCVCV
A bitmap for each column of the table below is encoded into the magic string, from which 69 is subtracted. For all columns except the last two, only 6 bits are required. For the last two, the higher order bits need to be 1, so a negative number is generated (characters \n and :) in order to have leading 1's instead of leading zeroes. We don't want to include the last three rows of the table though, so instead of rightshift and ANDing by 1, we rightshift and AND by 1-j/14 which normally evaluates to 1, but evaluates to 0 for the last 3 rows.
The following program (with the same expressions as the submission) was used to generate the tables below (uncomment whichever if line is required for the table you want.
c='[cjsztdpbfvkgxmnlr]'
z=0
289.times{|k|
  q=[i=k%17,j=k/17].max
  r=c[j+1]+c[i+1]
  #if i!=j && q>3 && (k%2<1||q>12) && !'mzxcxkx'.index(r)
  #if "UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0
    print r,' '
    z+=1
  else
    print '   '
  end
  i==16&&puts
}
puts z

            ct    cp    cf    ck       cm cn cl cr
               jd    jb    jv    jg    jm jn jl jr
            st    sp    sf    sk    sx sm sn sl sr
               zd    zb    zv    zg    zm zn zl zr
tc    ts          tp    tf    tk    tx tm tn tl tr
   dj    dz          db    dv    dg    dm dn dl dr
pc    ps    pt          pf    pk    px pm pn pl pr
   bj    bz    bd          bv    bg    bm bn bl br
fc    fs    ft    fp          fk    fx fm fn fl fr
   vj    vz    vd    vb          vg    vm vn vl vr
kc    ks    kt    kp    kf             km kn kl kr
   gj    gz    gd    gb    gv          gm gn gl gr
      xs    xt    xp    xf             xm xn xl xr
mc mj ms    mt md mp mb mf mv mk mg mx    mn ml mr
nc nj ns nz nt nd np nb nf nv nk ng nx nm    nl nr
lc lj ls lz lt ld lp lb lf lv lk lg lx lm ln    lr
rc rj rs rz rt rd rp rb rf rv rk rg rx rm rn rl
179

            ct    cp    cf    ck       cm cn cl cr
               jd    jb    jv    jg    jm
            st    sp    sf    sk       sm sn sl sr
               zd    zb    zv    zg    zm
tc    ts                                        tr
   dj    dz                                     dr
                                             pl pr
                                             bl br
                                             fl fr
                                             vl vr
                                             kl kr
                                             gl gr
                                             xl xr
                                             ml mr

48


Third Argument in Output Command is Extra Memory
Subleq specifies output with the three word command x -1 y, where x is the address of the value to be output. Unlike other Subleq commands, execution will proceed to the next command in all cases and y is ignored.  This means it is available to be used for memory.
For example 0:2 -1 65 will print the "A" (CHAR(65)) stored in 2: and then proceed to 3:.


Mathematica 49 46 45 44 42
As a pure function: 42 chars
DayName@{#,m,6}~Table~{m,12}~Count~Friday&

Example
DayName@{#,m,6}~Table~{m,12}~Count~Friday&[2013]

2

As a named function: 44 chars
f=DayName@{#,m,6}~Table~{m,12}~Count~Friday&

Examples
f[1776]
f[2012]
f[2013]
f[2014]

2
3
2
1


Python 3, \$\approx\$A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99))) where A is the Ackermann function,or limited by RAM

A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
a='.'*(A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99))))
exec(a)

Don't try it online!
Stole the Ackermann function from here.
More manageable version to demonstrate:

A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
a='.'*(9999)
exec(a)

Try it online!
Admittedly I'm not certain this approach is arbitrarily extendible in practice.


BrainF**k, 396 391 bytes

>+>>++++[-<++++++++>]->,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-<+[-<+]->>+[-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>[[->+]->>+<<<+[-<+]->]>+[-<->[[->+]->+>>+<<<<+[-<+]->]<+>->+[->+]->>[->+<]>+>++++++++++>>-<<[-<-[>>]<]<->>>+[-<<<+>>>[-<->]<+++++++++>>>+]++++++++[-<++++<++++++>>]<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]>.>.[-]<[-]<<<[->+<]<<+[-<+]>+]>>[-]<<<-<+[-<+]->>+]

I couldn't resist the temptation to do this one. At least the triangle is pointy-side down.

Input comes in as a string of numeric characters followed by a single newline.

Output will contain a single trailing space on every line.

Examples:

$ bf sd.bf
010
0 1 0
 1 1
  2

$ bf sd.bf
123456
1 2 3 4 5 6
 3 5 7 9 1
  8 2 6 0
   0 8 6
    8 4
     2

$ bf sd.bf
9245322
9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0

Explanation

Since it's rather difficult to explain the code from a functional perspective, we can instead look at it from the perspective of the state of the tape at various times. The core idea here is that the triangle we output is initialized as a tightly-packed (for BF, anyway) array that shrinks in size by 1 every iteration of a loop. Another important thought is that we use 255 to indicate a "placeholder" that we can search for on the tape.

Initialization

This is the easiest step. At the start of the program, we execute the following:

>+>>++++[-<++++++++>]->

This forces the tape into the following state (where >N< indicates the location of the pointer on the tape)

[ 0 1 32 255 >0< 0 0 ...]

The first number here is a "buffer" location. We're not going to use it on a long-term basis, but it's useful to make little operations simpler and for copying data around.
The second number is the number of spaces that we'll be outputting at the start of each line, starting after the first line. The first line will have no leading spaces.
The third number is the space character we output.
The fourth number is a placeholder 255, so that we can get back to this position relatively easily.

Input

From this position, we will read in all of the characters. At the end of this step, we hope to be in the following situation:

[ 0 1 32 255 a b c d e f ... >255< 0 0 ... ]

Where a b c d e f ... indicates the string of numeric characters that was input (not the newline).

We accomplish this with the following:

,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-

There are some nuances to this. First of all, we will output each character as we get them, and then output a space after it. Secondly, we don't want to copy the ASCII value to the tape, we want to copy the actual numeric digit. Third, we want to stop when we hit a newline and leave ourselves in a good place at that time.
Say our input is 6723. Then, upon reading the first 6, our tape looks like this:

[ 0 1 32 255 >54< 0 0 ...]

We check that this value is not equal to 10 (an ASCII newline) with ,----------[++++++++++. We then print out the value and continue by simultaneously subtracting 48 from the input value and adding 32 to the value next to it (>>++++++++[-<++++<------>>]<), leaving us here:

[ 0 1 32 255 6 >32< 0 ...]

Notice how throughout this process we can assume that all digits to the right of our input are 0--this means that we're not in danger of ruining any previous state if we use values to the right to calculate 6 * 8 and 4 * 8.
Now we output the space character we just generated, and take in a new input, deleting the space we calculated there. Eventually, the input will be terminated by a new line and the loop will exit, leaving a 255 where the newline would have been (,----------]-). This is the second placeholder character we will use to navigate the tape. At this point in our scenario, our tape is exactly this:

[ 0 1 32 255 6 7 2 3 >255< 0 0 ... ]

Calculation

The way this works is that the list of digits between our 255 placeholders is going to shrink by one every iteration of the loop. When it only has 1 digit left in it, we're done and should halt immediately (Note that, at this point, every digit in that list has already been output, so we don't have to worry about outputting it again).

We now use this trick to navigate to the first 255 placeholder: <+[-<+]-. This effectively searches the tape to the left for a 255, changing nothing in between. Now that we've moved the pointer, we can check our exit condition: if there's only one digit in the list, then the cell two spaces to the right will hold 255. Thus, we check against that and start a loop: >>+[-<<

The first step in our loop is to output a newline. So we move to the first cell (our buffer cell), add 10 to it and output. The next step is to output all leading space characters. After outputting them, we increment our count for number of leading spaces. These steps are accomplished by the following:

-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>

Which leaves us in this state:

[ 0 2 32 255 >6< 7 2 3 255 0 0 0 0 0 0 ]

Our next step is to copy the first value in the list over, past the second placeholder 255:

[[->+]->>+<<<+[-<+]->]

We essentially do this by hopping back and forth between our placeholder 255s, leaving us here:

[ 0 2 32 255 >0< 7 2 3 255 0 6 0 0 ... ]

We now start a loop, iterating through the rest of the list, stopping when we hit 255 : >+[-<

At this point, the digit to our immediate left is always 0. So, because we love them, we pop a placeholder 255 in there so that we can come back to our place in the list. The next step is to move the second place in the list to locations surrounding where we moved the first place to, past the second placeholder 255. These steps are accomplished by the following:

->
[[->+]->+>>+<<<<+[-<+]->]

Leaving us here: [ 0 2 32 255 255 >0< 2 3 255 7 6 7 0 ]
Now, both the 6 and 7 have been moved to a location where the calculation can occur. We need two copies of the 7 because the next number in the list will need it as well. The 7 immediately after the 255 serves this purpose, whereas the other 7 will be consumed by the calculation.

First, we add the two digits:

<+>->+[->+]->>
[->+<]>

Leaving us here:

[ 0 2 32 255 0 255 2 3 255 7 0 >13< 0 ]

The next combination of steps is the most complicated. We need to see if the number we're pointing to is larger than 10, and if it is, we subtract 10. In reality, what we do is we subtract 10 from it and see if it hits 0 at any point in the subtraction. If it does, we add 10 back on later. At the end of this, we should have the sum modulo 10.

Prepare a 10 to the right
+>++++++++++
Leave yet another 255 for a loop condition later
>>-<<
If the number is greater than 10 end up one space to the left
else one space to the right
[-<-[>>]<]<->
Check if the previous 255 is two spaces to the right and if it is
add 10 back to our sum--we've subtracted too much
>>+[-<<<+>>>[-<->]<+++++++++>>>+]

At this point, we've accomplished the goal. We have the sum modulo 10!
Also, whether or not the number was greater than 10, we'll end up here:

[ 0 2 32 255 0 255 2 3 255 7 0 3 0 0 >0< ]

Our next goals are to output this new sum, follow it with a space, and inject it back into our list. We do this all with our previous techniques of 255-hopping and adding 48 to our sum, so I won't cover it in detail.

++++++++[-<++++<++++++>>]
<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]
>.>.

And we're here: [ 0 2 32 255 3 255 2 3 255 7 0 0 51 >32< ]
Notice how we put an additional 255 placeholder after our newly-injected 3 so that we don't lose place in the list. At this point, we have output our sum and its space, so we need to clean up and revert to a state where the next iteration of this loop is going to work. We need to clear out our 51 and 32 cells, move the 7 once to the right, and navigate to our list placeholder so that we can start over.

[-]<[-]<<<[->+<]<<+[-<+]

Now, we're here: [ 0 2 32 255 3 >0< 2 3 255 0 7 0 ... ]
Which is exactly where we want to be for our next iteration. So check for 255 and move on! (>+])

When we get dropped off from the loop, we're going to have a whole new list--made up of the sums from the previous list. The first time, it'll look like this:

 [ 0 2 32 255 3 9 5 0 >0< ]

Now we want to repeat that whole process on our new list, so we plop a 255 down to the left and start all over! We need to do a little bit of cleanup with >>[-]<<, and then drop our placeholder with <-. After that, we're in exactly the same place as we were after input, so we can get away with doing the same checks: <+[-<+]->>+, and boom! We've got our full loop! All we need is the closing bracket, and when it ends we've already output everything, so we're done: ].


Retrieve all possible marks that can be placed in a Sudoku puzzle


What is the Probability that a Knight Stays on Chessboard?

Pyth, 38 bytes

M?smcgtGd8fq5sm^-Fk2C,TH^UhQ2G1g@Q1>Q2

Try it online: Demonstration

Explanation:

                                        implicit: Q = evaluated input
M                                       define a function g(G,H): //G=depth, H=current cell
                         UhQ              the list [0,1,...,Q[0]-1]
                        ^   2             Cartesian product, gives all cells
          f                               filter for numbers numbers T, which satisfy:
                    C,TH                    zip(T,H)
              m                             map the two pairs k to:
                -Fk                           their difference
               ^   2                          squared
             s                              sum (distance squared)
           q5                               == 5
   m                                      map each valid cell d to:
     gtHd                                   g(G-1,d)
    c    8                                  divided by 8
  s                                       return sum
 ?                           G          if G > 0 else
                              1           return 1

                               g@Q1>Q2  call g(Q[1],Q[2:]) and print


x86-64 (and x86-32) machine code, 13 15 13 bytes
changelog:

Bugfix: the first version was only checking G=0xff, not requiring R and B to be 0.  I changed to modifying the background in place so I could use lodsd on the foreground to have fg pixels in eax for the short-form cmp eax, imm32 encoding (5 bytes), instead of cmp dh,0xff (3 bytes).

Save 2 bytes: noticed that modifying the bg in place allowed using a memory operand for cmov, saving a 2-byte mov load (and saving a register, in case that matters).

This is a function following the x86-64 System V calling convention, callable directly from C or C++ (on x86-64 non-Windows systems) with this signature:
void chromakey_blend_RGB32(uint32_t *background /*rdi*/,
                     const uint32_t *foreground /*rsi*/,
                  int dummy, size_t pixel_count /*rcx*/);

The image format is RGB0 32bpp, with the green component at the 2nd lowest memory address within each pixel.  The foreground background image is modified in-place.  pixel_count is rows*columns.  It doesn't care about rows/columns; it just chromekey blends however many dwords of memory you specify.
RGBA (with A required to be 0xFF) would require using a different constant, but no change in function size.  Foreground DWORDs are compared for exact equality against an arbitrary 32-bit constant stored in 4 bytes, so any pixel-order or chroma-key colour can be easily supported.
The same machine code also works in 32-bit mode.  To assemble as 32-bit, change rdi to edi in the source.  All other registers that become 64-bit are implicit (lodsd/stosd, and loop), and the other explicit regs stay 32-bit.  But note that you'll need a wrapper to call from 32-bit C, because none of the standard x86-32 calling conventions use the same regs as x86-64 SysV.
NASM listing (machine-code + source), commented for asm beginners with descriptions of what the more complex instructions do.  (Duplicating the instruction reference manual is bad style in normal usage.)
 1                       ;; inputs:
 2                       ;; Background image pointed to by RDI, RGB0 format  (32bpp)
 3                       ;; Foreground image pointed to by RSI, RGBA or RGBx (32bpp)
 4          machine      ;; Pixel count in RCX
 5          code         global chromakey_blend_RGB32
 6          bytes        chromakey_blend_RGB32:
 7 address               .loop:                      ;do {
 8 00000000 AD               lodsd                   ; eax=[rsi], esi+=4. load fg++
 9 00000001 3D00FF0000       cmp    eax, 0x0000ff00  ; check for chromakey
10 00000006 0F4407           cmove  eax, [rdi]       ; eax = (fg==key) ? bg : fg
11 00000009 AB               stosd                   ; [rdi]=eax, edi+=4. store into bg++
12 0000000A E2F4             loop .loop              ;} while(--rcx)
13
14 0000000C C3               ret

##  next byte starts at 0x0D, function length is 0xD = 13 bytes

To get the original NASM source out of this listing, strip the leading 26 characters of each line with <chromakey.lst cut -b 26- > chromakey.asm.  I generated this with
nasm -felf64 chromakey-blend.asm -l /dev/stdout | cut -b -28,$((28+12))-
NASM listings leave more blank columns than I want between the machine-code and source.  To build an object file you can link with C or C++, use nasm -felf64 chromakey.asm.  (Or yasm -felf64 chromakey.asm).
untested, but I'm pretty confident that the basic idea of load / load / cmov / store is sound, because it's so simple.
I could save 3 bytes if I could require the caller to pass the chroma-key constant (0x00ff00) as an extra arg, instead of hard-coding the constant into the function.  I don't think the usual rules allow writing a more generic function that has the caller set up constants for it.  But if it did, the 3rd arg (currently dummy) is passed in edx in the x86-64 SysV ABI.  Just change cmp eax, 0x0000ff00 (5B) to cmp eax, edx (2B).

With SSE4 or AVX, you might do this faster (but larger code size) with pcmpeqd and blendvps to do a 32-bit element size variable-blend controlled by the compare mask.  (With pand, you could ignore the high byte).  For packed RGB24, you might use pcmpeqb and then 2x pshufb+pand to get TRUE in bytes where all 3 components of that pixel match, then pblendvb.
(I know this is code-golf, but I did consider trying MMX before going with scalar integer.)


R, 70 62 bytes

function(d,i,y)(x=d%*%(a=c(1,29,493))*(1+i)^y)%/%a%%c(29,17,x)

Try it online!

Takes input as d: deposit in knuts, sickles, galleons; i: interest rate as decimal; y: years. Outputs final deposit in knuts, sickles, galleons. Thanks to @Giuseppe for using matrix multiplication to save some bytes (and pointing out how to avoid the need to wrap at 1e99).


What's my name? Produce the name of the language indirectly


Minecraft 18w11a (.mcfunction), 757 bytes
fill ~ ~ ~ ~15 ~ ~15 ice
fill ~13 ~ ~13 ~7 ~ ~11 cyan_wool
fill ~12 ~ ~14 ~10 ~ ~8 cyan_wool
fill ~12 ~ ~13 ~10 ~ ~11 diamond_block
fill ~11 ~ ~12 ~9 ~ ~10 diamond_block
fill ~10 ~ ~11 ~8 ~ ~9 diamond_block
fill ~3 ~ ~4 ~1 ~ ~2 dirt
setblock ~3 ~ ~4 oak_planks
setblock ~2 ~ ~3 oak_planks
clone ~3 ~ ~4 ~1 ~ ~2 ~4 ~ ~5
setblock ~4 ~ ~5 oak_planks
setblock ~4 ~ ~7 ice
setblock ~6 ~ ~5 ice
clone ~6 ~ ~5 ~4 ~ ~7 ~7 ~ ~8
setblock ~9 ~ ~10 diamond_block
setblock ~4 ~ ~4 dirt
setblock ~3 ~ ~5 dirt
setblock ~7 ~ ~7 dirt
setblock ~6 ~ ~8 dirt
setblock ~1 ~ ~2 ice
fill ~12 ~ ~9 ~12 ~ ~8 ice
setblock ~11 ~ ~8 ice
fill ~8 ~ ~13 ~7 ~ ~13 ice
setblock ~7 ~ ~12 ice
fill ~ ~ ~ ~15 ~ ~15 light_gray_concrete replace ice
fill ~ ~ ~ ~9 ~ ~10 dark_oak_bark replace dirt

Of course someone had to answer the question with Minecraft. Place answer inside of a datapack, and run with /function <packname>:<filename>. The shovel is drawn relative to you in the +X and +Z direction. Colors are wrong but I'll count that as a language limitation ;)
But the shovel is actually made out of wood and diamonds!!!!
Output


Python
def game(a):
    deck = range(1,a+1)
    #store the deck
    origDeck = []
    #copy the deck
    origDeck.extend(deck)
    table =[]
    ans = 0
    while 1:
        while len(deck) > 0:
            table.append(deck.pop(0))
            if len(deck) == 0:
                break
            deck.append(deck.pop(0))
        table.reverse()
        deck,table=table,deck
        ans+=1
        #this is the condition that exits the infinite loop
        if deck==origDeck:
            break
    print ans

Calling game(n) prints the number of rounds for n cards. The code can be easily changed to allow for printing the deck between rounds (add print deck before if deck==origDeck).

Tests (1 through 50):
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20
21: 21
22: 14
23: 24
24: 90
25: 63
26: 26
27: 27
28: 18
29: 66
30: 12
31: 210
32: 12
33: 33
34: 90
35: 35
36: 30
37: 110
38: 120
39: 120
40: 26
41: 41
42: 42
43: 105
44: 30
45: 45
46: 30
47: 60
48: 48
49: 120
50: 50

31 produces a peculiar output; it goes through 210 rounds.
It appears that primes have large cycles. For example, 97 has the largest cycle under 100: 6435.


Vim, 37, 34, 33, 32 bytes

:%s/\t/    /g|%norm ^hr/hv0r*r/

Try it online!

Note that this requires a trailing carriage return (enter) in vim, although not in the online interpreter.

This uses the V interpreter because it's backwards compatible. A very straightforward solution.

Here's a gif that lets you see the solution happen in real time. This uses a slightly older version, and I added some extra keystrokes to make it run slower so you can see what happens:

And here is the explanation of how it works:

:%s/\t/    /g           "Replace every tab with 4 spaces
|                       "AND
%norm                   "On every line:
      ^                 "  Move to the first non-whitespace char
       h                "  Move one character to the left. If there is none, the command will end here.
         r/             "  Replace it with a slash
           h            "  Move to the left
            v0          "  Visually select everything until the first column
              r*        "  Replace this selection with asterisks
                r/      "  Replace the first character with a slash


Test if a string can be made with substrings!

Brachylog, 8 bytes
~c¬{∋¬∈}

Try it online!
This is really slow. Took about 37 seconds for the "Hello, world!" test case on my PC, and timed-out on TIO.
This takes the string through the Input variable and the list through the Output variable
Explanation
             String = ?, List = .

             It is possible to find…
~c           …a deconcatenation of ?…
  ¬{   }     …such that it is impossible…
    ∋¬∈      …that an element of that deconcatenation is not an element of .


Build a Nonographic Magnitude Optimizer™

Python 2 & PuLP — 2,644,688 squares (optimally minimized); 10,753,553 squares (optimally maximized)

Minimally golfed to 1152 bytes

from pulp import*
x=0
f=open("c","r")
g=open("s","w")
for k,m in enumerate(f):
 if k%2:
    b=map(int,m.split())
    p=LpProblem("Nn",LpMinimize)
    q=map(str,range(18))
    ir=q[1:18]
    e=LpVariable.dicts("c",(q,q),0,1,LpInteger)
    rs=LpVariable.dicts("rs",(ir,ir),0,1,LpInteger)
    cs=LpVariable.dicts("cs",(ir,ir),0,1,LpInteger)
    p+=sum(e[r][c] for r in q for c in q),""
    for i in q:p+=e["0"][i]==0,"";p+=e[i]["0"]==0,"";p+=e["17"][i]==0,"";p+=e[i]["17"]==0,""
    for o in range(289):i=o/17+1;j=o%17+1;si=str(i);sj=str(j);l=e[si][str(j-1)];ls=rs[si][sj];p+=e[si][sj]<=l+ls,"";p+=e[si][sj]>=l-ls,"";p+=e[si][sj]>=ls-l,"";p+=e[si][sj]<=2-ls-l,"";l=e[str(i-1)][sj];ls=cs[si][sj];p+=e[si][sj]<=l+ls,"";p+=e[si][sj]>=l-ls,"";p+=e[si][sj]>=ls-l,"";p+=e[si][sj]<=2-ls-l,""
    for r,z in enumerate(a):p+=lpSum([rs[str(r+1)][c] for c in ir])==2*z,""
    for c,z in enumerate(b):p+=lpSum([cs[r][str(c+1)] for r in ir])==2*z,""
    p.solve()
    for r in ir:
     for c in ir:g.write(str(int(e[r][c].value()))+" ")
     g.write('\n')
    g.write('%d:%d\n\n'%(-~k/2,value(p.objective)))
    x+=value(p.objective)
 else:a=map(int,m.split())
print x

(NB: the heavily indented lines start with tabs, not spaces.)

Example output: https://drive.google.com/file/d/0B-0NVE9E8UJiX3IyQkJZVk82Vkk/view?usp=sharing

It turns out that problems like are readily convertible to Integer Linear Programs, and I needed a basic problem to learn how to use PuLP—a python interface for a variety of LP solvers—for a project of my own. It also turns out that PuLP is extremely easy to use, and the ungolfed LP builder worked perfectly the first time I tried it.

The two nice things about employing a branch-and-bound IP solver to do the hard work of solving this for me (other than not having to implement a branch and bound solver) are that

Purpose-built solvers are really fast. This program solves all 50000 problems in about 17 hours on my relatively low-end home PC. Each instance took from 1-1.5 seconds to solve.
They produce guaranteed optimal solutions (or tell you that they failed to do so). Thus, I can be confident that no one will beat my score in squares (although someone might tie it and beat me on the golfing part).

How to use this program

First, you'll need to install PuLP. pip install pulp should do the trick if you have pip installed.

Then, you'll need to put the following in a file called "c": https://drive.google.com/file/d/0B-0NVE9E8UJiNFdmYlk1aV9aYzQ/view?usp=sharing

Then, run this program in any late Python 2 build from the same directory. In less than a day, you'll have a file called "s" which contains 50,000 solved nonogram grids (in readable format), each with the total number of filled squares listed below it.

If you'd like to maximize the number of filled squares instead, change the LpMinimize on line 8 to LpMaximize instead. You will get output very much like this: https://drive.google.com/file/d/0B-0NVE9E8UJiYjJ2bzlvZ0RXcUU/view?usp=sharing

Input format

This program uses a modified input format, since Joe Z. said that we would be allowed to re-encode the input format if we like in a comment on the OP. Click the link above to see what it looks like. It consists of 10000 lines, each containing 16 numbers. The even numbered lines are the magnitudes for the rows of a given instance, while the odd numbered lines are the magnitudes for the columns of the same instance as the line above them. This file was generated by the following program:

from bitqueue import *

with open("nonograms_b64.txt","r") as f:
    with open("nonogram_clues.txt","w") as g:
        for line in f:
            q = BitQueue(line.decode('base64'))
            nonogram = []
            for i in range(256):
                if not i%16: row = []
                row.append(q.nextBit())
                if not -~i%16: nonogram.append(row)
            s=""
            for row in nonogram:
                blocks=0                         #magnitude counter
                for i in range(16):
                    if row[i]==1 and (i==0 or row[i-1]==0): blocks+=1
                s+=str(blocks)+" "
            print >>g, s
            nonogram = map(list, zip(*nonogram)) #transpose the array to make columns rows
            s=""
            for row in nonogram:
                blocks=0
                for i in range(16):
                    if row[i]==1 and (i==0 or row[i-1]==0): blocks+=1
                s+=str(blocks)+" "
            print >>g, s

(This re-encoding program also gave me an extra opportunity to test my custom BitQueue class I created for the same project mentioned above. It is simply a queue to which data can be pushed as sequences of bits OR bytes, and from which data can be popped either a bit or a byte at a time. In this instance, it worked perfectly.)

I re-encoded the input for the specific reason that to build an ILP, the extra information about the grids that were used to generate the magnitudes is perfectly useless. The magnitudes are the only constraints, and so the magnitudes are all I needed access to.

Ungolfed ILP builder

from pulp import *
total = 0
with open("nonogram_clues.txt","r") as f:
    with open("solutions.txt","w") as g:
        for k,line in enumerate(f):
            if k%2:
                colclues=map(int,line.split())
                prob = LpProblem("Nonogram",LpMinimize)
                seq = map(str,range(18))
                rows = seq
                cols = seq
                irows = seq[1:18]
                icols = seq[1:18]
                cells = LpVariable.dicts("cell",(rows,cols),0,1,LpInteger)
                rowseps = LpVariable.dicts("rowsep",(irows,icols),0,1,LpInteger)
                colseps = LpVariable.dicts("colsep",(irows,icols),0,1,LpInteger)
                prob += sum(cells[r][c] for r in rows for c in cols),""
                for i in rows:
                    prob += cells["0"][i] == 0,""
                    prob += cells[i]["0"] == 0,""
                    prob += cells["17"][i] == 0,""
                    prob += cells[i]["17"] == 0,""
                for i in range(1,18):
                    for j in range(1,18):
                        si = str(i); sj = str(j)
                        l = cells[si][str(j-1)]; ls = rowseps[si][sj]
                        prob += cells[si][sj] <= l + ls,""
                        prob += cells[si][sj] >= l - ls,""
                        prob += cells[si][sj] >= ls - l,""
                        prob += cells[si][sj] <= 2 - ls - l,""
                        l = cells[str(i-1)][sj]; ls = colseps[si][sj]
                        prob += cells[si][sj] <= l + ls,""
                        prob += cells[si][sj] >= l - ls,""
                        prob += cells[si][sj] >= ls - l,""
                        prob += cells[si][sj] <= 2 - ls - l,""
                for r,clue in enumerate(rowclues):
                    prob += lpSum([rowseps[str(r+1)][c] for c in icols]) == 2 * clue,""
                for c,clue in enumerate(colclues):
                    prob += lpSum([colseps[r][str(c+1)] for r in irows]) == 2 * clue,""
                prob.solve()
                print "Status for problem %d: "%(-~k/2),LpStatus[prob.status]
                for r in rows[1:18]:
                    for c in cols[1:18]:
                        g.write(str(int(cells[r][c].value()))+" ")
                    g.write('\n')
                g.write('Filled squares for %d: %d\n\n'%(-~k/2,value(prob.objective)))
                total += value(prob.objective)
            else:
                rowclues=map(int,line.split())
print "Total number of filled squares: %d"%total

This is the program that actually produced the "example output" linked above. Hence the extra long strings at the end of each grid, which I truncated when golfing it. (The golfed version should produce identical output, minus the words "Filled squares for ")

How it Works

cells = LpVariable.dicts("cell",(rows,cols),0,1,LpInteger)
rowseps = LpVariable.dicts("rowsep",(irows,icols),0,1,LpInteger)
colseps = LpVariable.dicts("colsep",(irows,icols),0,1,LpInteger)

I use an 18x18 grid, with the center 16x16 part being the actual puzzle solution. cells is this grid. The first line creates 324 binary variables: "cell_0_0", "cell_0_1", and so on. I also create grids of the "spaces" between and around the cells in the solution part of the grid. rowseps points to the 289 variables which symbolize the spaces that separate cells horizontally, while colseps similarly points to variables that mark the spaces that separate cells vertically. Here's a unicode diagram:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
  - - - - - - - - - - - - - - - -
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

The 0s and □s are the binary values tracked by the cell variables, the |s are the binary values tracked by the rowsep variables, and the -s are the binary values tracked by the colsep variables.

prob += sum(cells[r][c] for r in rows for c in cols),""

This is the objective function. Just the sum of all the cell variables. Since these are binary variables, this is just exactly the number of filled squares in the solution.

for i in rows:
    prob += cells["0"][i] == 0,""
    prob += cells[i]["0"] == 0,""
    prob += cells["17"][i] == 0,""
    prob += cells[i]["17"] == 0,""

This just sets the cells around the outer edge of the grid to zero (which is why I represented them as zeroes above). This is the most expedient way to track how many "blocks" of cells are filled, since it ensures that every change from unfilled to filled (moving across a column or row) is matched by a corresponding change from filled to unfilled (and vice versa), even if the first or last cell in the row is filled. This is the sole reason for using an 18x18 grid in the first place. It's not the only way to count blocks, but I think it is the simplest.

for i in range(1,18):
    for j in range(1,18):
        si = str(i); sj = str(j)
        l = cells[si][str(j-1)]; ls = rowseps[si][sj]
        prob += cells[si][sj] <= l + ls,""
        prob += cells[si][sj] >= l - ls,""
        prob += cells[si][sj] >= ls - l,""
        prob += cells[si][sj] <= 2 - ls - l,""
        l = cells[str(i-1)][sj]; ls = colseps[si][sj]
        prob += cells[si][sj] <= l + ls,""
        prob += cells[si][sj] >= l - ls,""
        prob += cells[si][sj] >= ls - l,""
        prob += cells[si][sj] <= 2 - ls - l,""

This is the real meat of the logic of the ILP. Basically it requires that each cell (other than those in the first row and column) be the logical xor of the cell and separator directly to its left in its row and directly above it in its column. I got the constraints that simulate an xor within a {0,1} integer program from this wonderful answer: https://cs.stackexchange.com/a/12118/44289

To explain a bit more: this xor constraint makes it so that the separators can be 1 if and only if they lie between cells which are 0 and 1 (marking a change from unfilled to filled or vice versa). Thus, there will be exactly twice as many 1-valued separators in a row or column as the number of blocks in that row or column. In other words, the sum of the separators on a given row or column is exactly twice the magnitude of that row/column. Hence the following constraints:

for r,clue in enumerate(rowclues):
    prob += lpSum([rowseps[str(r+1)][c] for c in icols]) == 2 * clue,""
for c,clue in enumerate(colclues):
    prob += lpSum([colseps[r][str(c+1)] for r in irows]) == 2 * clue,""

And that's pretty much it. The rest just asks the default solver to solve the ILP, then formats the resulting solution as it writes it to the file.


GolfScript 6D (v2: estimated score 101 * 0.63 ~= 64)

This is a very different approach to my earlier GolfScript answer, so it makes more sense to post it as a separate answer at v1 than to edit the other answer and make this v2.

~]:B;569'!EM,R.==|%NL2+^=1'{{32-}%95{base}:^~\^}:&~2/{~B=<}%2^10'#]8Y,;KiZfnnRsDzPsvQ!%4C&..z,g,$m'&=

Ungolfed

~]:B;
[30 183 21 378 31 381 7 461 113 543 15 568]
2/{~B=<}%2base
7060456576664262556515119565486100005262700292623582181233639882 10base
=

Explanation

The raw problem is classification of points in a 784-dimensional space. One standard approach is dimension reduction: identifying a small subset of dimensions which provide sufficient distinguishing power to do the classification. I evaluated each dimension and each possible threshold to identify 18 pairs of (dimension, range of threshold) which looked promising. I then picked the centre of each range of threshold, and evaluated 6-element subsets of the 18 pairs. Finally I optimised the threshold for each dimension of the best 6-D projection, improving its accuracy from 56.3% to 56.6%.

Because the projection is into 6 dimensions and for each dimension I apply a simple threshold, the final lookup table only needs 64 elements. It doesn't seem to be particularly compressible, so the main golfing is to base-convert both lookup tables (the list of dimension and thresholds; and the halfspace vector to digit map) and share the base-conversion code.


JavaScript (ES10), 159 bytes
Same logic as my original answer, but with the data stored as a string with several unprintable characters.

(v,r,g)=>[..."_Î^~248ÕScž"].flatMap(x=>(x=x.charCodeAt(),n+=x>>6,V=(120<<x/16%4)%683,R=~(x/2&7)*10%65,-R<r|x&g|(V-v)**2>V*V/100?[]:n+[R]),n=1)

Try it online!

JavaScript (ES10),  200 190 186  181 bytes
Expects (voltage, current, ground), where ground is a Boolean value. Returns an array of strings in NN-nn format.
(v,r,g)=>"0F5F1315CE02045E1214187E323438D519531519639E14181A".match(/../g).flatMap(x=>(x='0x'+x,n+=x>>6,V=(120<<x/16%4)%683,R=~(x/2&7)*10%65,-R<r|x&g|(V-v)**2>V*V/100?[]:n+[R]),n=1)

Try it online!
How?
Encoding format
Each outlet is encoded as a byte x whose bit-mask is DDVVRRRG with:

DD = difference between the leading outlet ID and the previous leading outlet ID
VV = voltage: [120,240,480,277] mapped to [0,1,2,3]
RRR = current rating: [20,30,50,60,15] mapped to [1,2,4,5,7]
G = flag set if there's no ground

For instance, the outlet 10-30 is encoded as 0xD5 = 0b11010101:
11 01 010 1
 |  |   | |
 |  |   | +--> no ground
 |  |   +----> rating 2 (30A)
 |  +--------> voltage 1 (240V)
 +-----------> previous ID + 3 (7 + 3 = 10)

The whole data is stored as a single string of two-nibble hexadecimal values, which are split with a match().
Decoding
The leading ID is updated with:
n += x >> 6

Because \$277\$ is \$960\bmod683\$, the voltage is decoded with:
V = (120 << x / 16 % 4) % 683

Because \$15\$ is \$80\bmod65\$, the current rating is decoded with:
R = -~(x / 2 & 7) * 10 % 65


generate a valid equation using specified operators

Perl, 129 160 151 chars

sub a{my($s,$t,$o)=splice@_,0,3;@_?map{a("$s $_","$t$o$_",@_)}1..9:
$o-eval$t||$o-eval"use integer;$t"||exit say$s}a"","","",split$",<>;say"NO SOLUTION"

Fun with recursion. The program exits upon finding the first valid tuple.

The eval has to be done twice, in and out of integer-only mode, in order to avoid invalid solutions like that given in example 5 in the description.


Haskell, 100 91 bytes
(>>= \x->last$[x]:[y|(z:y)<-words"aobo eunu iini oapi uiki AObo EUnu IIni OApi UIki",z==x])


Pseudo-quine polyglot language-detection counters

Python 2, Python 3, ><> (Fish)

#;n0
import sys
x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])n'
v=int(1/2*2)
sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])

Python explanation

The Python 2 and Python 3 interpreters work similarly except the v=int(1/2*2) variable gets different values (0 and 1) as Python 2 uses float division and Python 3 uses integer division.

In every run they add the expression +0*2 or +1*2  to the first line (after #;n) and to the x string (after the last write command). The ><> interpreter uses the first addition and the Pythons use the second one to create correct quines.

Code after B(A(B(B(x)))):

#;n+1*2+0*2+1*2+1*20
import sys
x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])+1*2+0*2+1*2+1*2n'
v=int(1/2*2)
sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])

><> (Fish) explanation

When you run the ><> interpreter the code pointer bounces back from the # wraps around the first line and starting from the end of the first line and heading West starts pushing numbers onto the stack. If an operator comes (+ or *) it pops the top two elements from the stack and pushes back the result. With this method we end up with the base2 representation of the previous runs (13 in the former example). This is the desired number so we output it with n and terminate with ;.


Intersection of circles – How can I reduce this golf code to 127 bytes?

Use Python 2's arg unpacking: 124 bytes

from math import*;circleIntersection=lambda(v,w),(x,y),r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(v-x,w-y)/r/2)//.5

Try it online!

Python 2 has parameter unpacking, allowing the input point arguments to be taken directly as pairs (v,w) and (x,y), where the input lists like [0,0] and [0,10] will be unpacked into the respective variables. This feature was removed in Python 3 -- a pity, in my opinion, since the old syntax seems more readable. But, the site has a Python 2 option, and nothing in your solution relies on Python 3.


CJam, 44 42 40 bytes

qN+ee_{Xa/~\+XW=eu__el=!\'@-*m<Xa+}fXWf=

Output contains a trailing linefeed.

Test it here.

Explanation

Instead of moving the letters through the string, I repeatedly remove a letter, rotate the string accordingly, and then reinsert the letter. There's one catch for doing this: we need to be able to distinguish the beginning of the string from the end of the string (which we can't after a simple rotation). That's why we insert a linefeed at the end as a guard (letter before the linefeed is the end of the string, letter after it is the beginning). The bonus is that this automatically returns the final string to the correct rotation where the linefeed actually is at the end of the string.

lN+     e# Read input and append a linefeed.
ee      e# Enumerate the array, so input "bob" would become [[0 'b] [1 'o] [2 'b] [3 N]]
        e# This is so that we can distinguish repeated occurrences of one letter.
_{      e# Duplicate. Then for each element X in the copy...
  Xa/   e# Split the enumerated string around X.
  ~     e# Dump the two halves onto the stack.
  \+    e# Concatenate them in reverse order. This is equivalent to rotating the current
        e# character to the front and then removing it.
  XW=   e# Get the character from X.
  eu    e# Convert to upper case.
  _     e# Duplicate.
  _el=! e# Check that convert to lower case changes the character (to ensure we have a
        e# letter).
  \'@-  e# Swap with the other upper-case copy and subtract '@, turning letters into 1 to
        e# 26 (and everything else into junk).
  *     e# Multiply with whether it's a letter or not to turn said junk into 0 (that means
        e# everything which is not a letter will be moved by 0 places).
  m<    e# Rotate the string to the left that many times.
  Xa+   e# Append X to the rotated string.
}fX
Wf=     e# Extract the character from each pair in the enumerated array.

To see why this ends up in the right position, consider the last iteration of the hi*bye example. After we've processed the e, the enumerated string is in this position:

[[4 'y] [6 N] [2 '*] [0 'h] [1 'i] [3 'b] [5 'e]]

First, we split around the linefeed and concatenate the parts in reverse order:

[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y]]

The linefeed would now be either at the beginning or the end of this string. But since the linefeed is just a guard that marks the end of the string, this means that the characters are actually in the right order. Now the linefeed is not a letter, so that the array is not rotated at all. Thus, when we append the linefeed, it goes where it belongs, and everything is in the order we're looking for:

[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y] [6 N]]

Some additional results if someone wants to compare longer test cases:

Hello, World!
,W oeHlo!lrld

Programming Puzzles & Code Golf
ago fgliPomomnrr elP& uC dezzsG

The quick brown fox jumps over the lazy dog
t eg chbi ko qfTounyzrj omw epx ueoahs rlvd

abcdefghijklmnopqrstuvwxyz
aqbrcdsetfguhivjwklxmnyozp

zyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyz

I like that last one. :)


PHP 23 bytes

#<?=md5(rand())&ÿÿÿÿÿÿ;

Where ÿ is character 255. Bitwise and will truncate the string returned from md5, which is already in hexadecimal format.


Pyth - 19 17 15 13 bytes
Thanks to @FryAmTheEggman for saving me two bytes.
ARRGH the special case for no answer. Solved that!
e_I#jL\|cL2.:

Test Suite.
e                Last element in list, this works out to longest one
  _I             Invariance under reverse, this detect palindrome
   #             Filter
   jL            Map join
    \|           By "|"
    cL2          Map chop in two pieces
     .:Q)        Substrings. Implicit Q). ) makes it do all substrings.


Context Free, 82 65 57 characters

rule T{9*[y 1]SQUARE[]2*{f 90}T{s.75y 8r 25}}startshape T

See: http://www.contextfreeart.org/gallery/view.php?id=3384

Golf'd further with help from Context Free Art users minimaleye, MtnViewJohn, and kipling.


Python 2, 90 bytes

g=lambda a:min(min(a))or-~g(map(lambda*c:map(max,(0,)+c[:-1],c,c[1:]),*a))
lambda a:g(a)/2

Try it online!

Accepts a matrix as a list of lists of 0 and 1.

How it works

g=lambda a:min(min(a))or…

If the smallest element of the matrix is 1 (it is completely infected), return 1; otherwise…

                        -~g(…                                            )

return 1 plus the recursive result on the following modified matrix…

                            map(lambda*c:…                           ,*a)

for each old column c…

                                         map(max,(0,)+c[:-1],c,c[1:])

produce a new row by zipping max over the down-shifted, original, and up-shifted versions of c.  (map fills in the gap at the end of c[1:] with None, which is falsy and smaller than both 0 and 1.)

Each iteration of g computes all vertical infections, then transposes the matrix.  This way, every 2 iterations of g compute all horizontal, vertical, and diagonal infections.

lambda a:g(a)/2

Because the base case of g with a fully infected matrix gave 1 rather than 0, the parity works out such that floored division by 2 always gives the correct result.


Javascript ES6 - 204

  Aim to type the fewest amount of Unicode characters in your code.

Not the shorter but probably the most obfuscated.

f=(a,b)=>{for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

If your browser do not support ES6 :

function f(a,b){for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

Copy/Paste that code into your browser console and try f('cow','moo'), f('pig','oink'), f('sheep','baa')

How it works ?

c is an array of 29 letters plus the animal and its sound (let call this our alphabet).
So, all the 31 characters fit in 5 bits (2^5 = 32).
A Unicode character is 16 bits long, so it can encode 3 characters of our alphabet with a padding bit.
The full text with the new lines is 186 characters of our alphabet, it can be encoded with 62 Unicode characters.

For example, Old is encoded like this :

alphabet value         O      l      d
alphabet index         11     20     15
unicode           0  01011  10100  01111  ===> \u2e8f (⺏)

If you have troubles to read some Unicode chars, install Code2000 font


Perl 6, 273 245 233 230 bytes

-28 bytes thanks to nwellnhof!

{S/rys/ries/}o{S:th(*)/\,/ and/}o{join ', ',map {$_~'s'x(.[0]>1)},grep *[0],(|[R,](.[0].polymod(10 xx 3)),|.skip Z <millennium century decade year month day hour minute second>)}o{~DateTime.new($_-62135596800)~~m:g/\d+/Z-(^6 X<3)}

Try it online!

I think there might be a trick or two I can use with EVAL to make this shorter. This solution takes into account leap seconds, so the last test case is a bit off. Both no longer applicable.

(Old) Explanation:

{                                      } # First code block
 DateTime.new($_-62135596800)  # Initialise a date time object with input amount of seconds
{  ...  }o    # Pass value to the next code block
 fmt(.year-1: "%04d").comb Z   # Zip each digit of the year with
                             <millennium century decade year>  # The appropriate word
 <month day hour minute second>.map:{  ...  }   # For each of these words
                                ".$^a".EVAL     # EVAL the method on the DateTime
                                           -(2>$++)     # -1 if month or day
                                                   ,$a  # Followed by the word itself
  grep +*[0],  # From these, filter out the ones with value 0
  map {$_~'s'x(.[0]>1)},    # Add plurals if greater than 1
  join ', ',                # Join with commas
 {  ...  }o         # Pass string to next code block
  S:th(*)           # Substitute the last instance of
         /\,/       # A comma
            / and/  # With ' and'
 {  ...  }o         # Pass to next code block
  S/rys/ries/       # Fix plural of century


Java, 626 539 536 529 bytes

-87 bytes by saving a few in a lot of places. Thanks goes to Mr Public for pointing some out.

-3 bytes because I can't manage to remove all the spaces first try (thanks mbomb007)

+8 bytes to fix for this case:

@v<v
^v^v
^v^<
^<

-15 bytes by front-loading variable declaration

s->{String o="",t;String[]p=s.split("\n");int h=p.length,w=p[0].length(),y=0,x,b=0,a,n,m;char[][]d=new char[h][w];for(;y<h;y++)for(x=0;x<w;x++){d[y][x]=p[y].charAt(x);if(d[y][x]=='@')d[y][x]=' ';}for(;b<h;b++)for(a=0;a<w;a++){t="";x=a;y=b;n=0;m=0;while(!(y<0|y>h|x<0|x>w||d[y][x]==' ')){if(y+m>=0&y+m<h&x+n>=0&x+n<w&&d[y+m][x+n]==d[y-m][x-n])d[y][x]=d[y-m][x-n];n=m=0;switch(d[y][x]){case'^':t+="W";m--;break;case'<':t+="A";n--;break;case'v':t+="S";m++;break;case'>':t+="D";n++;}x+=n;y+=m;}o=t.length()>o.length()?t:o;}return o;}

Readable version:

static Function<String,String> parser = snake -> {
    // declare all variables in one place to minimize declaration overhead
    String output = "", path;
    String[] split = snake.split("\n");
    int h=split.length, w=split[0].length(), y=0, x, startY=0, startX, dx, dy;
    char[][] board = new char[h][w];
    // setup char[][] board
    for (; y<h; y++)
        for (x=0; x<w; x++) {
            board[y][x]=split[y].charAt(x);
            if(board[y][x]=='@')board[y][x]=' ';
        }
    // find the longest possible path
    for (; startY<h; startY++)
        for (startX=0; startX<w; startX++) {
            path = "";
            x=startX; y=startY; dx=0; dy=0;
            while (!(y<0 | y>h | x<0 | x>w || board[y][x] == ' ')) {
                if (y + dy >= 0 & y + dy < h & x + dx >= 0 & x + dx < w
                        && board[y + dy][x + dx] == board[y - dy][x - dx]) {
                    board[y][x] = board[y - dy][x - dx];
                } dx = dy = 0;
                switch(board[y][x]) {
                    case '^':path+="W";dy--;break;
                    case '<':path+="A";dx--;break;
                    case 'v':path+="S";dy++;break;
                    case '>':path+="D";dx++;break;
                }
                x+=dx; y+=dy;
            }
            output = path.length()>output.length()?path:output;
        }
    return output;
};

Takes a String like v  @\n>>>^.
Creates a path starting at each coordinate, then returns the longest one.
The lookahead required for the overlapping paths was the hardest part.


D (419 chars)

enum c=q{string[string] m;import std.stdio;import std.array;void main(){foreach(string s;lines(stdin)){auto a=s.split;if(!a.length)goto e;switch(a[0]){case "*":m.clear;break;case "!":m.remove(a[1]);break;case "?":writeln(m.get(a[1],""));break;default:if(a.length<2){goto e;}m[a[0]]=a[1];}stdout.flush;}e:write("static this(){");foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v);write("}enum c=q{",c,"};mixin(c);");}};mixin(c);

formatted:

enum c=q{
    string[string] m;
    import std.stdio;
    import std.array;
    void main(){
        foreach(string s;lines(stdin)){
            auto a=s.split;
            if(!a.length)goto e;
            switch(a[0]){
                case "*":m.clear;break;
                case "!":m.remove(a[1]);break;
                case "?":writeln(m.get(a[1],""));break;
                default:if(a.length<2){goto e;}m[a[0]]=a[1];
            }
            stdout.flush;
        }
        e:write("static this(){");
        foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v);
        write("}enum c=q{",c,"};mixin(c);");
    }
};mixin(c);

variant of my D quine

the * command relies on m.clear; to work correctly which it doesn't in dmd 2.52 (bug in the compiler)

the need for stdout.flush; depends whether auto flush is enabled (it isn't on my machine)


How to golf evaluation of math expression in MySQL?

Score 69
select * from expressions
where elt(ord(operation)/2-20,a*b,a+b,a-b,a/b)=c

Takes inspiration from Marmite Bomber's use of elt, but uses a magic formula. Indexes into the list via ord(operation)2/-20, which buckets the four character codes across 1 to 4 by abusing elt's rounding behavior.
-1 thanks to Arnauld, who improved on the modulo reduction.
-1 thanks to Bubbler, who found a better non-modulo formula.
Score 73
select * from expressions
where elt(instr('*/-+',operation),a*b,a/b,a-b,a+b)=c

This is my best guess as to the 73 you mention other people have gotten in the question.


JavaScript (ES6), 201
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):''))

Less golfed
t=>(
  T=h=>String.fromCodePoint(128336+h%12),
  [h,m,s]=t.match(/\d+/g),
  'It is currently '+T(h-=~10)
   +(
      // if seconds is not 0, increment m else just convert to number
      // have to use '- -' to force conversion to number
     (m -= - !!-s)
-s?++m:m)
      ? ` with ${60-m ? 60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h)
      : ''
    )
)

Test

F=
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):'')
)

var tid=0

function getTime(t)
{
  var a=t.match(/\d+/g)
  if (a) {
    var [h,m,s]=a
    h|=0, s|=0, m|=0
    if(h>=0 & h<24 & m>=0 & m<60 & s>=0 & s<60)
      return [h,m,s]
  }
  return null
}

function update()
{
  clearTimeout(tid)
  var t=I.value, a=getTime(t)
  if (a) {
    O.textContent = F(t)
    tid = setTimeout(again,5000)
  }
  else {
    O.textContent = 'invalid ' + t
  }
}
function again()
{
  var t=I.value, a=getTime(t)
  if (a) {
    var [h,m,s]=a
    ++s>59?(s=0,++m>59?(m=0,++h):0):0
    h%=24
    s<10?s='0'+s:0
    m<10?m='0'+m:0
    t = h+(-m-s?':'+m+(-s?':'+s:''):'')
    I.value = t
    O.textContent=F(t)
    tid = setTimeout(again, 1000)
  }
}

update()
#O { font-size:16px }
Time <input id=I value='12' oninput='update()' onkeydown='update()'>
(modify current time as you wish - but use valid values)


Python 413
Pretty efficient, although it does sacrifice a small amount of speed for length, such as calculating things every pass of a small for loop rather than precalculating it. I̶t̶ ̶s̶t̶i̶l̶l̶ ̶o̶u̶t̶p̶u̶t̶s̶ ̶a̶l̶l̶ ̶t̶h̶e̶ ̶t̶e̶s̶t̶ ̶c̶a̶s̶e̶s̶ ̶i̶n̶ ̶w̶e̶l̶l̶ ̶u̶n̶d̶e̶r̶ ̶a̶ ̶s̶e̶c̶o̶n̶d̶.̶
Edit:
I had to fix a bug which now makes it significantly less efficient for larger inputs.
X,Y,L=input();S=sorted;T=type
def E(s,c):
 l=[[]]
 for h in s:
    if h==c:l+=[h]
    elif all(h!=[b,a][j]for a,b in L for j,n in[(0,a),(1,b)]if n==c):
     if T(l[-1])==str:l+=[[]]
     l[-1]=S(l[-1]+[h])
 if T(l[0])==T(l[-1])!=str:return[l[0]+l[-1]]+l[1:-1]+[len(l[-1])]
 return l+[0]
print any(0==cmp(*[[E(s,c)for c in S(set(s))]for s in [X[j:]+X[:j],Y[i:]+Y[:i]]])for i in range(len(Y))for j in range(len(X)))

Test Cases
"acb", "abc", [('a','b')]
True (0 ms)

'acabd','dcaba',[('a','b'),('a','c')]
True (1 ms)

'acabd','acdab',[('a','b'),('a','c')]
False (2 ms)

'cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
True (62 ms)

'cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
False (6963 ms)

The basic algorithm does the following. For each letter, L, present, loop through the string constructing a list; anytime it encounters L it appends it to the list, any group of adjacent letters which can not be switched with L it appends to the list sorted, letters which can be switched with L are ignored.
For example when considering 'acabd' with the pairs [('a','b'),('a','c')], we would construct:
a : a, a, [d]
b : [c], b, [d] *
c : c, [b,d]
d : [a,a,b,c], d

which is equivalent to the result we get when we apply this to 'cabad' ('dcaba' shifted)
*Note here that the [c] and [d] should be considered one list
What is basically being done, is confirming for each letter that the order of it and the letters it can't switch with are the same. Since they cannot switch, they cannot 'pass' each other, so if the first string has two as followed by two ds followed by one a followed by one d than no matter how it's manipulated it can't be transformed into a string which has three as followed by three ds. Of course the order of the letters that it can't switch with is not an issue (they might be paired with each other and switchable), but their counts are, hence the sorting of the lists before comparison. In addition it's clear that any letters that can be switched don't matter at all for the purposed of comparison.
Using this algorithm the program could be made significantly more efficient; currently it loops through every possible transposition of both strings and compares them due to some issues with comparing cases in which there were lists bordering the beginning and end.


Python 2, 318 315 271 bytes

Mr.Xcoder, ovs and Jonathan Frech saved a lot of bytes

p=range
def f(x,i=0,j=-1):z=len(x[0]);j+=1;i+=j/z;j%=z;return i<len(x)and(x[i][j]and-~min([f([[v,v[:j]+[2]*(r-j)+v[r:]][i<=y<=e]for y,v in enumerate(x)],i,j)for e in p(i,len(x))for r in p(j+1,z+1)if all(all(k[j:r])for k in x[i:e+1])]+[f(x,i,j)-1]*(x[i][j]>1))or f(x,i,j))

Try it online!


Ruby, 38 (46) characters

e=->n,k,r{k-=r;'\|'[r]*k+'|/'[r]*n-=k}

This function takes the direction as an integer (1 for right, 0 for left). A function that takes a string is 8 characters longer:

d=->n,k,r{n-=k;r<?r??\\*k+?|*n :?|*~-k+?/*-~n}

Usage examples:

puts e[10, 5, 1] # or d[10, 5, 'r']
||||//////
puts e[10, 5, 0] # or d[10, 5, 'l']
\\\\\|||||


JavaScript (ES6), 24 bytes
Expects (n)(d).

n=>g=d=>d?n++/d*g(d-1):1

Try it online!


Vim, 40 bytes
-2 bytes thanks to DJMcMayhem
9i_|␛r\I/␛qqYPxR /␛q8@qr^4jhR/o\␛jr/2hr\

You can see it in action in this GIF made using Lynn's python script