Perl - 557 532 511 490 482 384 363

($p,$t,$h)=@ARGV;%L=(H=>D,D=>H,C=>S,S=>C);$B=%L{$t};$_="\]$p$h\[";s/(.$t)/0$1/g;s/J$B/01$B/;s/0J/00/;s/J/R/g;s/9/Z/g;($T,@C)=split/\]\[/,$_;$s=$C[0];$s=~s/.+(.)/$1/;$s=~s/$t/0/;$X=(sort@C[0..2])[0];@M=@C[3..6];@F=(grep{/$s/}@M);@M=@F if@F;$w=(sort@M)[@M-1];push@M,$X;foreach$g(sort@M){$g ne$X?$b=$g:last}$_=$C[1]eq$X||!$b?$w:$b;s/.(..)/$1/;s/Z/9/;s/0|1|R/J/;print

How it works

Try it online!

First it reads args and finds the left-bauer's suit (jack of the same color as trump) with a hash lookup:

($p,$t,$h)=@ARGV;
%L=(H=>D,D=>H,C=>S,S=>C);
$B=%L{$t};

Then it combines all cards into one string and does some replacements, making the cards naturally sort in the correct order for euchre:

$_="\]$p$h\[";
s/(.$t)/0$1/g; # trump cards start with '0'
s/J$B/01$B/;   # left-bauer's 'J' changes to '01', making it trump
s/0J/00/;      # right-bauer's 'J' changes to '0'
s/J/R/g;       # all other jacks have 'J' changed to 'R'
s/9/Z/g;       # all 9s change to Z
($T,@C)=split/\]\[/,$_;

At the end of this block, the card string is then split on the brackets, which builds an array of all cards where:

index 0 = opponent's lead card
index 1 = teammate's card
index 2 = other opponent's card
indices 3-6 represent the hand

The lead suit is parsed from the first card, but the suit changes to '0' to represent trump if trump was led:

$s=$C[0];
$s=~s/.+(.)/$1/;
$s=~s/$t/0/;

The best card in-play is found by sorting the first three cards and retrieving the first card:

$X=(sort@C[0..2])[0];

The playable cards are found. If any cards in-hand match the lead suit, then only those cards remain. Otherwise all cards are considered playable:

@M=@C[3..6];
@F=(grep{/$s/}@M);
@M=@F if@F;

The 'throwaway' card is found by returning the last card in the sorted array of playable cards:

$w=(sort@M)[@M-1];

The lowest 'winning' card that can win the trick is found by adding the highest card in-play to the array of playable cards, sorting the array, and iterating over it until the highest card in-play is found. The 'winning' card is the card from the previous iteration:

push@M,$X;
foreach$g(sort@M){$g ne$X?$b=$g:last}

The correct play is then evaluated. The 'throwaway' card is chosen if any of the following are true:

The best card on the table has an index of 1 in the unsorted array of all cards, meaning it belongs to our teammate
The search for the lowest 'winning' card came up null, meaning our opponent's best card is higher than all cards in the hand

Otherwise the 'winning' card is returned:

$_=$C[1]eq$X||!$b?$w:$b;
s/.(..)/$1/; # remove the '0' that indicated trump
s/Z/9/;      # get those 9s back
s/0|1|R/J/;  # fix the jacks
print


Python 2, 62 61 58 bytes

Zero-based. I assume the L suffixes are acceptable.

lambda n:[5**(n*3/7-~i)/2**n%10for i in range(2**n/2or 1)]

Output:

0 [5]
1 [2]
2 [1, 6]
3 [3, 5, 8, 0]
4 [1, 7, 9, 5, 6, 2, 4, 0]
5 [3, 9, 7, 8, 1, 7, 5, 5, 8, 4, 2, 3, 6, 2, 0, 0]
6 [1, 9, 8, 4, 0, 3, 7, 7, 9, 7, 6, 1, 8, 1, 5, 5, 6, 4, 3, 9, 5, 8, 2, 2, 4, 2L, 1L, 6L, 3
L, 6L, 0L, 0L]
7 [4, 4, 2, 0, 1, 8, 3, 9, 8, 3, 5, 9, 5, 7, 7, 8, 2, 1, 9, 7, 9, 6, 1, 7, 6L, 0L, 3L, 6L,
3L, 5L, 5L, 5L, 9L, 9L, 7L, 5L, 6L, 3L, 8L, 4L, 3L, 8L, 0L, 4L, 0L, 2L, 2L, 3L, 7L, 6L, 4L,
 2L, 4L, 1L, 6L, 2L, 1L, 5L, 8L, 1L, 8L, 0L, 0L, 0L]

Previous solution:

lambda n:[5**int(n/.7-~i)/10**n%10for i in range(2**n/2or 1)]
lambda n:[str(5**int(n/.7-~i))[~n]for i in range(2**n/2)]or 5

Explanation:

def f(n):
    r = max(2**n / 2, 1)
    m = int(n/0.7 + 1)
    for i in range(r):
        yield (5**(m+i) / 10**n) % 10

The range(2**n/2) uses the observation that each cycle has length r = 2n-1 except when n = 0, so we just compute the n-th digits for 5m to 5m + r - 1.

The start of the cycle 5m is the first number larger than 10n. Solving 5m ≥ 10n gives m ≥ n / log10 5. Here we approximate log10 5 ≈ 0.7 which will break down when n = 72. We could add more digits to increase the accuracy:

| approximation             | valid until        | penalty   |
|---------------------------|--------------------|-----------|
| .7                        | n = 72             | +0 bytes  |
| .699                      | n = 137            | +2 bytes  |
| .69897                    | n = 9297           | +4 bytes  |
| .698970004                | n = 29384          | +8 bytes  |
| .6989700043               | n = 128326         | +9 bytes  |
| .6989700043360189         | too large to check | +15 bytes |
| import math;math.log10(5) | same as above      | +23 bytes |

The / 10**n % 10 in the loop simply extract the desired digit. Another alternative solution uses string manipulation. I used the trick ~n == -n-1 here to remove 1 byte.

An mentioned in the comment, the expression 5**(m+i) / 10**n can further be simplified this way, which gives the current 58-byte answer.

(The division x/2**n can be done using bitwise right-shift x>>n. Unfortunately, due to Python's operator precedence this does not save any bytes.) The fraction 3/7 can also be improved in similar mannar:

| approximation                   | valid until         | penalty   |
|---------------------------------|---------------------|-----------|
| n*3/7                           | n = 72              | +0 bytes  |
| n*31/72                         | n = 137             | +2 bytes  |
| n*59/137                        | n = 476             | +3 bytes  |
| n*351/815                       | n = 1154            | +4 bytes  |
| n*643/1493                      | n = 10790           | +5 bytes  |
| n*8651/20087                    | n = 49471           | +7 bytes  |
| int(n*.43067655807339306)       | too large to check  | +20 bytes |
| import math;int(n/math.log2(5)) | same as above       | +26 bytes |


Jelly, 18 bytes

ẎQṢ=€ẸƇZ$⁺œr€ɗ€0o⁶

Try it online!

Returns a list of pieces, where 1 represents a part of a piece, and ' ' is padding. Trailing ' 's are removed.


EOC Vault Password Rank 3 Puzzle - Vault Password

Python, 59 bytes
golf=lambda s:(9<len(s))*(s.lower()>s>s.upper())*'?'>min(s)

(Still) probably not optimal.


Ruby, 139 bytes
Lambda function, takes x and y as arguments and returns a string
->x,y{c=y-2*n=y-(x>y ?1:0)>>1
x+=-c/2*s=[x-n,c*3].max
x<n||x>n*2?'~<.,,>~~':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}

If a solution exists, it can be done with all koalas+commapillars or all koalas+crabs.
The principle is to use a minimum of commapillars. If the number is odd, we use 1 commapillar. if even we use 0 commapillars, unless there are more commas than periods, in which case we use 2.
The number of periods used in noncommapillars (crabs + koalas) is necessarily even, and the number of noncommapillars is half (number of periods)-(number of commapillars). If there are insufficient commas for all koalas, or too many for all crabs, no solution is possible. Otherwise, we return a solution.
Commented in test program
uses "fail" instead of chameleon for clarity
f=->x,y{c=y-2*n=y-(x>y ?1:0)>>1
#n=noncommapillars=y>>1 as they have 2 periods. c=commapillars=y-2*n, 1 for odd y, 0 for even y.
#if x>y there are too many commas to have 0 commapillars for even y. noncommapillars= y-1 >> 1, so 2 commapillars

x+=-c/2*s=[x-n,c*3].max
# s=number of commas allocated to commapillars. x-n to allow all noncommapillars to be koalas, but at least 3 per commapillar.
#-c/2 == -1 if there are commapillars, 0 if not (Ruby truncates toward -inf). Subtract commas for commapillars from x if necessary

x<n||x>n*2?'fail':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}
#if x<n (insufficient commas for all koalas) or x>n*2 (too many for all crabs) return fail. Else...
#return string off crabs, koalas, and (using % operator like sprintf) c commapillars (0..2), the second with 3 commas (if present) and the first with the rest.

10.times{|j|10.times{|i|puts "%-20s %s"%[?.*j+?,*i,f[i,j]]}}
#all x,y from 0..9

Output
,                    fail
,,                   fail
,,,                  fail
,,,,                 fail
,,,,,                fail
,,,,,,               fail
,,,,,,,              fail
,,,,,,,,             fail
,,,,,,,,,            fail
.                    fail
.,                   fail
.,,                  fail
.,,,                 <,,,.>
.,,,,                <,,,,.>
.,,,,,               <,,,,,.>
.,,,,,,              <,,,,,,.>
.,,,,,,,             <,,,,,,,.>
.,,,,,,,,            <,,,,,,,,.>
.,,,,,,,,,           <,,,,,,,,,.>
..                   fail
..,                  <.,.>
..,,                 ,<..>,
..,,,                fail
..,,,,               fail
..,,,,,              fail
..,,,,,,             <,,,.> <,,,.>
..,,,,,,,            <,,,,.> <,,,.>
..,,,,,,,,           <,,,,,.> <,,,.>
..,,,,,,,,,          <,,,,,,.> <,,,.>
...                  fail
...,                 fail
...,,                fail
...,,,               fail
...,,,,              <.,.> <,,,.>
...,,,,,             <.,.> <,,,,.>
...,,,,,,            <.,.> <,,,,,.>
...,,,,,,,           <.,.> <,,,,,,.>
...,,,,,,,,          <.,.> <,,,,,,,.>
...,,,,,,,,,         <.,.> <,,,,,,,,.>
....                 fail
....,                fail
....,,               <.,.> <.,.>
....,,,              ,<..>, <.,.>
....,,,,             ,<..>, ,<..>,
....,,,,,            fail
....,,,,,,           fail
....,,,,,,,          <.,.> <,,,.> <,,,.>
....,,,,,,,,         <.,.> <,,,,.> <,,,.>
....,,,,,,,,,        <.,.> <,,,,,.> <,,,.>
.....                fail
.....,               fail
.....,,              fail
.....,,,             fail
.....,,,,            fail
.....,,,,,           <.,.> <.,.> <,,,.>
.....,,,,,,          <.,.> <.,.> <,,,,.>
.....,,,,,,,         <.,.> <.,.> <,,,,,.>
.....,,,,,,,,        <.,.> <.,.> <,,,,,,.>
.....,,,,,,,,,       <.,.> <.,.> <,,,,,,,.>
......               fail
......,              fail
......,,             fail
......,,,            <.,.> <.,.> <.,.>
......,,,,           ,<..>, <.,.> <.,.>
......,,,,,          ,<..>, ,<..>, <.,.>
......,,,,,,         ,<..>, ,<..>, ,<..>,
......,,,,,,,        fail
......,,,,,,,,       <.,.> <.,.> <,,,.> <,,,.>
......,,,,,,,,,      <.,.> <.,.> <,,,,.> <,,,.>
.......              fail
.......,             fail
.......,,            fail
.......,,,           fail
.......,,,,          fail
.......,,,,,         fail
.......,,,,,,        <.,.> <.,.> <.,.> <,,,.>
.......,,,,,,,       <.,.> <.,.> <.,.> <,,,,.>
.......,,,,,,,,      <.,.> <.,.> <.,.> <,,,,,.>
.......,,,,,,,,,     <.,.> <.,.> <.,.> <,,,,,,.>
........             fail
........,            fail
........,,           fail
........,,,          fail
........,,,,         <.,.> <.,.> <.,.> <.,.>
........,,,,,        ,<..>, <.,.> <.,.> <.,.>
........,,,,,,       ,<..>, ,<..>, <.,.> <.,.>
........,,,,,,,      ,<..>, ,<..>, ,<..>, <.,.>
........,,,,,,,,     ,<..>, ,<..>, ,<..>, ,<..>,
........,,,,,,,,,    <.,.> <.,.> <.,.> <,,,.> <,,,.>
.........            fail
.........,           fail
.........,,          fail
.........,,,         fail
.........,,,,        fail
.........,,,,,       fail
.........,,,,,,      fail
.........,,,,,,,     <.,.> <.,.> <.,.> <.,.> <,,,.>
.........,,,,,,,,    <.,.> <.,.> <.,.> <.,.> <,,,,.>
.........,,,,,,,,,   <.,.> <.,.> <.,.> <.,.> <,,,,,.>


JavaScript (ES7), 22 bytes
Limited to \$2^{53}-1\$.

a=>eval(a.join`**`)%10

Try it online!


Python 2,  186 184 179 177 173 172  162 bytes
-10 thanks to ovs! (avoiding use of .items)

x=input()
from datetime import*
a=sorted(date(y,m,d)for y in x for m in x[y]for d in x[y][m])
print max(map(len,`[d+timedelta(1)in a for d in a*2]`.split('s')))/6

Try it online! Or see the test-suite.
Huh, how?
In Python 2 input implicitly attempts an eval on the string which, in this case, will produce a nested dictionary.
a is then a list of the dates in order (sorted(...)), this is formed by inspecting the nested dictionaries in a nested for loop, and passing the resulting parts of the dates to date(year, month, day).
[d+timedelta(1)in a for d in a*2] forms a list of booleans which identify whether the next date is present for each date in the sorted dates repeated twice, a*2.
Note that the final value of a will always be False. The reason for repeating a is to avoid something later (see the final paragraph).
`[...]` gets the Python string representation (AKA repr) of that list - for example, something like "[False, True, True, False, False, False, True, True, False, False]" for an input with three consecutive dates between two others.
.split('s') splits the resulting string at occurrences of the 's' character - so for the above, that would be ['[Fal', 'e, True, True, Fal', 'e, Fal', 'e, Fal', 'e, True, True, Fal', 'e, Fal', 'e]'].
map(len,...) simply gives us a list of the lengths of the strings in the above list - so for the above, that would be [4, 18, 6, 6, 18, 6, 2].
max(...) gives the maximum value of that list - so for the above, that would be 18.
To find the number of consecutive days we want to count how many Trues there were in that longest section and then add one. In the above example, we can simply divide by six (the length of either 'True, ' or 'e, Fal'), hence the /6 at the end.
If the longest run of consecutive dates is at the left of the sorted dates we'd get something like '[True, True, Fal' (or '[Fal' when no dates at all are consecutive), which would be two shy of what we need, so if we were to perform all of this across a rather than a*2 we'd need to add two before performing the integer division (e.g. (...+2)/6). This wouldn't affect any other results but costs one more byte than simply repeating a with a*2, whereupon we'll get the longer string later on - this is guaranteed by the fact that d+timedelta(1) for the maximal d will give False.


05AB1E, 8 7 6 bytes
Thanks to Magic Octopus Urn for saving a byte!
It somehow works, but honestly I have no idea why.
Code
Ÿvy.O=

Uses the 05AB1E encoding. Try it online!
Explanation
Ÿ          # Create the range [a, .., b] from the input array
 vy        # For each element
   .O      #   Push the connected overlapped version of that string using the
                 previous version of that string. The previous version initially
                 is the input repeated again. Somehow, when the input array is
                 repeated again, this command sees it as 1 character, which gives
                 the leading space before each line outputted. After the first
                 iteration, it reuses on what is left on the stack from the
                 previous iteration and basically attaches (or overlaps) itself
                 onto the previous string, whereas the previous string is replaced
                 by spaces and merged into the initial string. The previous string
                 is then discarded. We do not have to worry about numbers overlapping
                 other numbers, since the incremented version of a number never
                 overlaps entirely on the previous number. An example of 123 and 456:

                 123
                    456

                 Which leaves us "   456" on the stack.
     =     #   Print with a newline without popping


Coercing a string to an integer in GolfScript

There's an operator ~ in golfscript, which does the following: bitwise not, dump, eval.

Therefore, "1" will give the string "1" while "1"~ will evaluate that string (into the integer 1).

Then, all you need to do is "1"~7+.

Try it online!


HTML + Javascript + jQuery + jQuery UI

The input should be given in the text area and should be formatted as each command in a line. The commands are not case sensitive. All of the commands were fully implemented. I hope that you enjoy.

You can try it at http://jsfiddle.net/bCBfk/

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>Useless interpreter</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

Type here your program input:

      <textarea id="input" style="width: 400px; height: 150px;"></textarea>

        <button id="bt">Run the program</button>
        Running the program...

Here is the program output:

      <button id="cc" style="display: none;">Clear the output</button>

It has one new command:

   It is the 42 command which calculates the answer of the life, the universe and everything. The only quirk is that it takes 7.5 million years to finish.

Other spoilers:

   This entry has several features:

  You will really hate the FAIL command.
  BOOM! will screw up you "execution unit". At least the windows from DONTUSEME(n) are able to survive this.
  KABOOM! is really dangerous to world in several bad ways.
  DONTUSEME(n) always opens infinite unclosable empty windows, one each 0.8 seconds. But there is a hidden kill switch.
  DONTUSEME(n) survives NO., FAIL and even BOOM!. I just couldn't make it survive the KABOOM! though. The reason is that popup windows won't work as this is not the result of a click (and popups created by other ways are long banned in all major browsers), and could not use iframes too because of a violation of same-origin policy.
  INCLUDE-xxx can create any instruction, including DONTUSEME(n) or another INCLUDE-yyy instruction.
  If INCLUDE-xxx does generates an INCLUDE-yyy instruction, the yyy name is generated at random. If you grab the name of the generated command with firebug or something similar, you can use it.
  It handles malformed syntax and incomplete or empty input.


Python 3, 26 bytes

lambda x:max(x)/2+7>min(x)

Try it online!
The input is a list with both ages


triplegolf - not only the source code length counts!

Bash, 23 characters
Error:
bash: /: Is a directory

Source:
echo       $0-$01234;/;

Output:
/bin/bash-/bin/bash1234

Brainf*ck, 32 characters
This code executes for about 3 seconds and stops and displays the following error and output.
Error:
bff: out of memory (-2058691272)

Source:
+++++[......-]..+[>>>>>>>>>>>>-]

Output: (Hexdump)
0505 0505 0505 0404 0404 0404 0303 0303
0303 0202 0202 0202 0101 0101 0101 0000

C, 35 characters
Warning:
b.c:1:30: warning: division by zero

Source and Output:
main(){system("cat "__FILE__)/0;;;}

PHP, 50 characters
Warning:
PHP Warning:  Division by zero in /tmp/3 on line 1

Source and Output:
<?php echo (0/0).''.file_get_contents(__FILE__);?>


Variable declaration

Regular variable declaration takes 4 bytes (var) + 2 bytes/variable (i,).
You can declare variables as optional named parameters for your function and shave a few bytes.

f(){var i,j,k;} //Takes 15 bytes
g({i,j,k}){}  //Takes 12 bytes

Note: This doesn't work for non-constant values, for example:

f({i=List}){}  //Works
g({i=[]}){}  //Doesn't work

f({i=0,j=0}){}  //Works
g({i=0,j=i}){}  //Doesn't work


Python

Since implementing full PCRE is too much I implemented only an essential subset of it.

Supports |.\.\w\W\s+*(). Input regexp must be correct.

Examples:

$ python regexp.py
^\s*(\w+)$
   hello
Matches:     hello
Group 1 hello

$ python regexp.py
(a*)+
infinite loop

$ python regexp.py
(\w+)@(\w+)(\.com|\.net)
sam@test.net
Matches:  sam@test.net
Group 1 sam
Group 2 test
Group 3 .net

How it works:

For detailed theory read this Introduction to Automata Theory, Languages, and Computation.

The idea is to convert the original regular expression into a nondeterminist finite automata (NFA). Actually, PCRE regular expressions are at least context free grammars for which we need push-down automata, but we'll limit ourselves to a subset of PCRE.

Finite automatas are directed graphs in which nodes are states, edges are transitions and each transition has a matching input. Initially you start from a start node, predefined. Whenever you receive an input that matches one of the transition you take that transition  to a new state. If you reached a terminal node it is called that automata accepted input. In our case input is a matching function that returns true.

They are called nondeterminist automata because sometimes there are more matching transitions that you can take from the same state. In my implementation all transition to the same state must match the same thing, so I stored the matching function together with the destination state (states[dest][0]).

We transform our regexp to a finite automata using building blocks. A building block has a start node (first) and an end node (last) and matches something from the text (possible empty string).

The simplest examples include

matching nothing: True (first == last)
matching a character: c == txt[pos] (first == last)
matching end of string: pos == len(txt)(first == last`)

You will also need the new position in text where to match next token.

More complicated examples are (capital letters stand for blocks).

matching B+:

create nodes: u, v (matching nothing)
create transitions: u -> B.first, B.last -> v, v -> u
when you get to node v you already matched B. Then you have two options: go further, or try to match B again.

matching A|B|C:

create nodes: u, v (matching nothing)
create transitions: u -> A.first, u -> C.first, u -> C.first,
create transitions: A->last -> v, B->last -> v, C->last -> v,
from u you can go to any block

All regexp operators can be transformed like this. Just give a try for *.

The last part is to parse the regexp which requires a very simple grammar:

 or: seq ('|' seq)*
 seq: empty
 seq: atom seq
 seq: paran seq
 paran: '(' or ')'

Hopefully implementing a simple grammar (I think is LL(1), but correct me if I'm wrong) is much easier than building an NFA.

Once you have the NFA you need to backtrack until you reach terminal node.

Source code (or here):

from functools import *

WORDCHAR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_'

def match_nothing(txt, pos):
  return True, pos

def match_character(c, txt, pos):
  return pos < len(txt) and txt[pos] == c, pos + 1

def match_space(txt, pos):
  return pos < len(txt) and txt[pos].isspace(), pos + 1

def match_word(txt, pos):
  return pos < len(txt) and txt[pos] in WORDCHAR, pos + 1

def match_nonword(txt, pos):
  return pos < len(txt) and txt[pos] not in WORDCHAR, pos + 1

def match_dot(txt, pos):
  return pos < len(txt), pos + 1

def match_start(txt, pos):
  return pos == 0, pos

def match_end(txt, pos):
  return pos == len(txt), pos

def create_state(states, match=None, last=None, next=None, name=None):
  if next is None: next = []
  if match is None: match = match_nothing

  state = len(states)
  states[state] = (match, next, name)
  if last is not None:
    states[last][1].append(state)

  return state

def compile_or(states, last, regexp, pos):
  mfirst = create_state(states, last=last, name='or_first')
  mlast = create_state(states, name='or_last')

  while True:
    pos, first, last = compile_seq(states, mfirst, regexp, pos)
    states[last][1].append(mlast)
    if pos != len(regexp) and regexp[pos] == '|':
      pos += 1
    else:
      assert pos == len(regexp) or regexp[pos] == ')'
      break

  return pos, mfirst, mlast

def compile_paren(states, last, regexp, pos):
  states.setdefault(-2, [])   # stores indexes
  states.setdefault(-1, [])   # stores text

  group = len(states[-1])
  states[-2].append(None)
  states[-1].append(None)

  def match_pfirst(txt, pos):
    states[-2][group] = pos
    return True, pos

  def match_plast(txt, pos):
    old = states[-2][group]
    states[-1][group] = txt[old:pos]
    return True, pos

  mfirst = create_state(states, match=match_pfirst, last=last, name='paren_first')
  mlast = create_state(states, match=match_plast, name='paren_last')

  pos, first, last = compile_or(states, mfirst, regexp, pos)
  assert regexp[pos] == ')'

  states[last][1].append(mlast)
  return pos + 1, mfirst, mlast

def compile_seq(states, last, regexp, pos):
  first = create_state(states, last=last, name='seq')
  last = first

  while pos < len(regexp):
    p = regexp[pos]
    if p == '\\':
      pos += 1
      p += regexp[pos]

    if p in '|)':
      break

    elif p == '(':
      pos, first, last = compile_paren(states, last, regexp, pos + 1)

    elif p in '+*':
      # first -> u ->...-> last -> v -> t
      # v -> first (matches at least once)
      # first -> t (skip on *)
      # u becomes new first
      # first is inserted before u

      u = create_state(states)
      v = create_state(states, next=[first])
      t = create_state(states, last=v)

      states[last][1].append(v)
      states[u] = states[first]
      states[first] = (match_nothing, [[u], [u, t]][p == '*'])

      last = t
      pos += 1

    else:  # simple states
      if p == '^':
    state = create_state(states, match=match_start, last=last, name='begin')
      elif p == '$':
    state = create_state(states, match=match_end, last=last, name='end')
      elif p == '.':
    state = create_state(states, match=match_dot, last=last, name='dot')
      elif p == '\\.':
    state = create_state(states, match=partial(match_character, '.'), last=last, name='dot')
      elif p == '\\s':
    state = create_state(states, match=match_space, last=last, name='space')
      elif p == '\\w':
    state = create_state(states, match=match_word, last=last, name='word')
      elif p == '\\W':
    state = create_state(states, match=match_nonword, last=last, name='nonword')
      elif p.isalnum() or p in '_@':
    state = create_state(states, match=partial(match_character, p), last=last, name='char_' + p)
      else:
    assert False

      first, last = state, state
      pos += 1

  return pos, first, last

def compile(regexp):
  states = {}
  pos, first, last = compile_or(states, create_state(states, name='root'), regexp, 0)
  assert pos == len(regexp)
  return states, last

def backtrack(states, last, string, start=None):
  if start is None:
    for i in range(len(string)):
      if backtrack(states, last, string, i):
    return True
    return False

  stack = [[0, 0, start]]   # state, pos in next, pos in text
  while stack:
    state = stack[-1][0]
    pos = stack[-1][2]
    #print 'in state', state, states[state]

    if state == last:
      print 'Matches: ', string[start:pos]
      for i in xrange(len(states[-1])):
    print 'Group', i + 1, states[-1][i]
      return True

    while stack[-1][1] < len(states[state][1]):
      nstate = states[state][1][stack[-1][1]]
      stack[-1][1] += 1

      ok, npos = states[nstate][0](string, pos)
      if ok:
    stack.append([nstate, 0, npos])
    break
      else:
    pass
    #print 'not matched', states[nstate][2]
    else:
      stack.pop()

  return False

# regexp = '(\\w+)@(\\w+)(\\.com|\\.net)'
# string = 'sam@test.net'
regexp = raw_input()
string = raw_input()

states, last = compile(regexp)
backtrack(states, last, string)


Octave, 96 88 87 84 76 54 50 weights & biases

This 6-layer neural net is essentially a 3-step sorting network built from a very simple min/max  network as a component. It is basically the example network from wikipedia as shown below, with a small modification: The first two comparisons are done in parallel. To bypass negative numbers though the ReLU, we just add 100 first, and then subtract 100 again at the end.

So this should just be considered as a baseline as it is a naive implementation. It does however sort all possible numbers that do not have a too large magnitude perfectly. (We can adjust the range by replacing 100 with another number.)

Try it online!

max/min-component

There is a (considerably less elegant way more elegant now, thanks @xnor!) way to find the minimum and maximum of two numbers using less parameters:

$$\begin{align} \min &= a - ReLU(a-b) \\ \max &= b + ReLU(a-b) \end{align}$$

This means we have to use a lot less weights and biases.

Thanks @Joel for pointing out that it is sufficient to make all numbers positive in the first step and reversing it in the last one, which makes -8 weights. Thanks @xnor for pointing out an even shorter max/min method which makes -22 weights! Thanks @DustinG.Mixon for the tip of combining certain matrices which result in another -4 weights!

function z = net(u)
a1 = [100;100;0;100;100;0];
A1 = [1 0 0 0;0 0 1 0;1 0 -1 0;0 1 0 0;0 0 0 1;0 1 0 -1];
B1 = [1 0 -1 0 0 0;0 0 0 1 0 -1;0 1 1 0 0 0;0 0 0 0 1 1];
A2 = [1 0 0 0;0 1 0 0;1 -1 0 0;0 0 1 0;0 0 0 1;0 0 1 -1];
A3 = [1 0 -1 0 0 0;0 1 1 0 0 0;0 0 0 1 0 -1;0 1 1 -1 0 1;0 0 0 0 1 1];
B3 = [1 0 0 0 0;0 1 0 -1 0;0 0 1 1 0;0 0 0 0 1];
b3 = -[100;100;100;100];
relu = @(x)x .* (x>0);
id = @(x)x;
v = relu(A1 * u + a1);
w = id(B1 * v) ;
x = relu(A2 * w);
y = relu(A3 * x);
z = id(B3 * y + b3);
% disp(nnz(a1)+nnz(A1)+nnz(B1)+nnz(A2)+nnz(A3)+nnz(B3)+nnz(b3)); %uncomment to count the total number of weights
end

Try it online!


Jelly, score 9 + 0 = 9

 Z
       ⁶
      €
     ɗ
    o
   Ḣ
  ḟ
 Ṛ
Ỵ

From the top:

ỴZḟḢoɗ€⁶

Try it online! (or see it self-operate)

From the side:

ỴṚḟḢoɗ€⁶Z

Try it online! (or see it self-operate)

How?

Ỵ Z|Ṛ ḟḢoɗ€⁶ [Z]  - Link list of characters:
Ỵ                 - split at newline characters
  Z               - | top: transpose to get columns
    Ṛ             - | side: reverse the lines
           ⁶      - set the right argument to a literal space character
          €       - for each (x = column (top) OR line (side)):
         ɗ        -   last three links as a dyad - i.e. f(x, space)
      ḟ           -     filter discard (spaces from x)
       Ḣ          -     pop & yield the head (first remaining character or 0 if none left)
        o         -     logical OR (with space character) (replace a 0 with a space)
                  - | top: no code remaining
              Z   - | side: transpose (at this point a no-op since we have a flat list)


Perl, 112 80 78

s/\S*//;$c=cos$&;$s=sin$&;s/([^ ,]*),(\S*)/($1*$c-$2*$s).",".($1*$s+$2*$c)/ge

Run on command-line as perl -pe 'code here', p option counted in code size.
For reference, here's my previous approach.  But regexes are too damn powerful.
split/[ ,]/,<>;$_='A;Y,print$x*cos($a)-$y*sin$a,",",$x*sin($a)+$y*cos$a,$"whileX';s/[AXY]/\$\l$&=shift\@_/g;eval


MATL, 17 16 bytes

t&l[2K0]B2:&ZvZ+

Try it online!

(-1 byte thanks to @Luis Mendo.)

The main part of the code is creating a matrix \$ K \$ for convolution:

$$ \mathbf{K} = \begin{pmatrix}0&1&0&1&0\\1&0&0&0&1\\0&0&0&0&0\\1&0&0&0&1\\0&1&0&1&0\end{pmatrix} $$

(Relative to the centre of the matrix, each 1 is a valid knight's move.)

t&l - Form a nxn matrix of all 1s (where n is the input). Let this be M.

[2K0] - Push an array containing [2, 4, 0] on stack

B  - Convert all to binary, padding with 0s as needed

0 1 0
1 0 0
0 0 0

2:&Zv - Mirror that on both dimensions, without repeating the final row/column ("symmetric range indexing").
This gives us the required matrix K.

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

Z+ - Perform 2D convolution of K over the earlier matrix M (conv2(M, K, 'same')),
summing up the 1s at legal knight move targets for each position

Result matrix is displayed implicitly.


Pyth, 40 bytes

jd[z"and"Jw"have"/K-lzl.-rz0rJ0i=J*lzlJK"out of"/JiJK"chances of love.

The code is 70 bytes long and qualifies for the -30 bytes bonus.

Try it online.

  [                        Begin an array and fill it with the following:
   z                         The first line of input.
   "and"                     That string.
   Jw                        The second line of input, saved in J.
   "have"                    That string.
           rz0rJ0              Convert both lines to lowercase.
         .-                    Remove the characters form the second string
                               from the first, counting multiplicities.
        l                      Get the length.
     -lz                       Subtract it from the length of the first line.
    K                          Save in K.
                  =J*lzlJ      Save the lines' lengths' product in J.
                 i       K     Compute the GCD of J and K.
   /                         The quotient of K and the GCD.
   "out of"                  That string.
   /JiJK                     The quotient of J and the GCD of J and K.
   "chances of love.         That string.
jd                         Join the elements, separated by spaces.


Iterative Alliterative Additive Array Antics

Python 2, 71 bytes

def f(a,i,n):x=0;exec"x+=i;a[i]+=len(a)*(a[i]<1)-1;i=a[i];"*n;print x+i

Try it online!


PowerShell v2+, 120 116 114 108 bytes

2..10+[char[]]'JQKA'|%{$z=' '*(8-!($_-10));$x='_'*10;$y=' '*10;" $x
/$y\
| $_$z|";,"|$y|"*5;"|$z$_ |
\$x/"}

Constructs a range 2..10 and does array concatenation with char-array JQKA. Feeds that into a loop |%{...}. Each iteration, we set $z equal to an appropriate number of spaces (based on whether we're at card 10 or not), set $x to 10 underscores, and set $y to 10 spaces.

Then, we begin our placements. We're going to leverage the default Write-Output to insert a newline between pipeline elements, so we just need to get the stuff on the pipeline. Note that in most places, we're using a literal newline rather than closing and reopening our strings to save a couple bytes.

The first is just $x with two spaces, then $y with two slashes, then the | $_$z|" the pipe, a space, the appropriate number of spaces, and another pipe. This forms the top of the cards up to and including the value line.

We have to semicolon here, since the next uses an array. The ,"|$y|"*5 constructs a string-array, with the comma-operator, of the pipe with spaces - on output, each element of this array gets a newline for free.

Then, the "|$z$_ | for the bottom value marking, and finally $x with slashes for the bottom of the card.

Output Snippet

PS C:\Tools\Scripts\golfing> 2..10+[char[]]'JQKA'|%{$z=' '*(8,7)[$_-eq10];" $(($x='_'*10)) ";"/$(($y=' '*10))\";"| $_$z|";,"|$y|"*5;"|$z$_ |";"\$x/"}
 __________
/          \
| 2        |
|          |
|          |
|          |
|          |
|          |
|        2 |
\__________/
 __________
/          \
| 3        |
|          |
|          |
|          |
|          |
|          |
|        3 |
\__________/
 __________
/          \
| 4        |
...


Python 2, 34 32 bytes

Solution provided by @l4m2
-2 bytes thanks to @xnor

lambda n:`(100**n+1)**100**n`[n]

Try it online!

Very,  very slow.

Verification up to \$166\$ digits. The idea for this verification comes from @l4m2: calculates \$x^{100^n}\$ by calculating x=x**10 repeatedly (\$2n\$ times), each time truncating \$x\$ to a few left most digits (the TIO link uses \$500\$ digits). By changing the truncation to round down or up, we obtain the lower and upper bound for the result. If the lower and upper bound agree to \$n\$ leftmost digits, we know that the exact calculation will also result in those \$n\$ digits.

I have verified that this solution works up to \$n = 333\$, using MAX_DIGITS = 1000.

How

This solution uses the following well known approximation of \$e\$:
$$ e = \lim_{x \to \infty} \left(1 + \frac{1}{x} \right)^{x}$$
Substituting \$x = 100^n\$, we have:
$$ e = \lim_{n \to \infty} \left(1 + \frac{1}{100^n} \right)^{100^n} = \lim_{n \to \infty} \frac{\left(100^n + 1 \right)^{100^n}}{\left(100^n\right)^{100^n}}$$
Since the denominator is a power of \$10\$, we can ignore it entirely.

According to this analysis on Math SE, the worst case error of this approximation is:
$$ \Delta < \frac{3}{x} = \frac{3}{100^n}$$
which means roughly that every time \$n\$ increases by \$1\$, we gains 2 digits of precision.


70 68(JS) + 22(CSS) characters

setInterval('$(".s").append($(".s :first").hide().fadeIn(1e3))',5e3)

CSS:

img{position:absolute}

jsfiddle: http://jsfiddle.net/QACAY/

pure jQuery. The only browser-stuff is setInterval, which dates as far back as IE4. jQuery support doesn't reach that far. Javascript syntax here is ancient as well.

Of course, in practice, do not pass strings to setInterval! It is ten characters shorter (fewer with es6 arrow functions), but it's unreadable (madness? This is code golf!), it forces you into the global scope (which we don't mind here), it's slower (but we are far from being concerned with performance of calling jQuery code) and it won't pass any decent code review.

Works best if all images have the same shape. But, it will work just as fine with semitransparent images as long as visible stacking counts as fine and no more background is visible when any single image is removed.

Since this does not wait for DOM ready, there's a tiny chance that only some of the image elements inside a gallery are loaded when an interval fires. In this case, the stack of images will get reordered. I don't think it's a problem. In fact, I kinda like it.

After slight tweaking, it looks like code that could easily pass through a code review and get into production (also, be sure to modify the CSS to not be too aggressive):

$(function(){
  $(".s").each(function(_, s){
    setInterval(function(){
      $(":first", s).hide().appendTo(s).fadeIn(1000);
    }, 5000);
  });
});


Scala
Sure, it'd be easier to encode MIDI files, but who's got a bunch of MIDI files lying around? It's not 1997!
First things first: I've decided to interpret a "Unicode byte" as a "Unicode char" and use CJK characters, because:

It matches the image challenge
Twitter is cool with it
I really need those bits

There are a few tricks I use to squeeze every last drop of entropy from the sources:
Firstly, music is made with notes. Moreover, we generally regard the same note in a different octave as the same note (which is why a 12-string guitar sounds right), so we only have 12 possibilities to encode. (when I output B, for example, I actually output a chord, consisting solely of B in all the octaves, a bit like a 12-string guitar).
Next, I remember from high-school music class that most note transitions are small (up or down one note). Jumps are less common. This tells us that there's probably less entropy in the jump sizes than in the notes themselves.
So, our approach is to break our source into a number of blocks - I found 14 blocks per second worked well (side note, I'd always wondered why audio was encoded at 44100 Hz. It turns out that 44100 has lots of factors, so I could have chosen 1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 14, 15, 18, 20, 21, 25, 28 or 30 blocks per second, and it would have divided cleanly). We then FFT these blocks (well, technically not fast, as the library I used isn't fast for non-power-of-2 blocks. And technically I used a Hartley transform, not Fourier).
We then find the note that sounds loudest (I used A-weighting, with high and low cut-offs, mostly because it's easiest to implement), and either encode this note, or encode silence (silence detection is based on SNR - low SNR is silence).
We then translate our encoded notes into jumps, and feed them to an adaptive arithmetic coder. The process for translation to text is similar to the image compression question (but involves some abusive use of BigInteger).
So far, so good, but what if the sample has too much entropy? We use a crude psychoacoustic model to remove some. The lowest entropy jump is "no change", so we look at our FFT data to try to find blocks where the listener probably won't notice if we keep playing the previous note, by looking for blocks where the note from the previous block is almost as loud as the loudest note (where "almost" is controlled by the quality parameter).
So, we've got a target of 140 characters. We start by encoding at quality 1.0 (max quality), and see how many characters that is. If it's too many, we drop to 0.95 and repeat, until we get to 140 characters (or we give up after quality 0.05). This makes the encoder an n-pass encoder, for n <= 20 (although it's massively inefficient in other areas too, so m'eh).
The encoder/decoder expects audio in s16be mono format. This can be achieved using avconv as:
#decoding ogg to s16be, and keeping only the first 60s
avconv -i input.ogg -ac 1 -ar 44100 -f s16be -t 60s input.raw
#encoding s16be to mp3
avconv -f s16be -ac 1 -ar 44100 -i output.raw output.mp3

To run the encoder:
sbt "run-main com.stackexchange.codegolf.twelvestring.TwelveString encode input.raw encoded.txt"
sbt "run-main com.stackexchange.codegolf.twelvestring.TwelveString decode encoded.txt output.raw"

Full code at https://github.com/jamespic/twelvestring.
Pitfall to note: You'll need nayuki's Arithmetic Coding library, which doesn't currently have Maven artifacts available. Instead, you'll need to locally build and install developster's fork of it.
And here are some samples. They sound awful, but just about recognisable:

Beethoven's 5th: original, encoded - 刲檁囉罓佖镱賑皌蝩蔲恁峕逊躹呯兲搆摼蝺筶槛庬一掛獴趤笲銗娵纜喫覤粠僭嫭裵獄鱨蠰儏咍箪浝姑椻趕挍呪白鸞盙宠埘謭擆闯脲誜忘椐笸囃庣稨俖咛脔湙弻籚砌鍖裏橈镙訁鹻塿骱踠筟七趇杅峇敖窈裞瘫峦咰呹櫬茏蛏姆臸胝婁遼憀麁黦掏毈喙眝綄鴀耢椚筤菮蟞斗俼湛营筬禴籙嬧窻丄
Fur Elise: original, encoded - 訖忢擫鏝拪纒铇鯪薯鉰孝暱埛痏絘僌莻暆鴈屖鳮絒婘譮蠣託騶腀饚緂柤碠瞢碩脅歙棆敗辦冏鄔酾萖苯劺誺軩忇穤锳婁伉巠桭晘酉筟緵俅怚尵鎽蜓崁飿嘔但鈐謽酝屮呤誥俊覊鶮龔癸埙煂臙牎繬肜摲炚雗頨款驦燈菩凧咁楾媡夥俰欓焵韀冊嗥燠鱧駟髉
Twinkle Twinkle Little Star: original, encoded - 欠悺矜莳錥鷗谴裴皽鳺憝漿箔皇殤鸧蜻猻丱
A fun chiptune: original, encoded - 简詐諥尘牿扫鲑龮箫颫齰蠏騁煟靸阒萎囦鮇雝愯訖芉馄鈿鬦嶏觲沠丆贀蛑蛀漥荤侲咔麑桬鲠僵擕灼攲陇亄鹘琾業纟鵼牤棌匩碆踬葫鶙懲欃铳樯柇鋡疡衻澯伅墇搢囻荸香貱夹咽蟽籐屈锂蛉袒貊屨鈦夜镤沄鍡唦魮骬乔蚖醶矕咻喸碋利褼裊匎嶮窢幘六沧鼝瞮坡葍帷锆邵旻符琨鱴郤栱烇仾椃騋荄嘵統篏珆罽

Update
I tweaked the silence threshold in the code, and re-encoded. The encodings have been updated accordingly. Also, I added another song (technically not open source, but I doubt the original copyright holder will feel their IP is under threat), just for fun:

Imperial March: original, encoded - 岼讶湠衢嫵焅喋藭霔憣嗗颟橳蕖匵腾嗅鈪芔区顕樭眀冂常僠寝萉乹俚戂闤灈蟑拷邢音褈霈媬盒萳璥唂焰銯艉鶱縩巻痭虊窻熲紆耺哅淙苉嘏庸锺禒旇蘄籷遪刨繱蕖嬯摺祑仰軈牰杊瘷棏郖弘卄浕眮騜阖鏴鶺艂税寛柭菸採偋隆兎豅蚦紛襈洋折踜跅軩树爺奘庄玫亳攩獼匑仡葾昐炡瞱咏斎煟价藭恐鷖璌榍脅樐嬨勀茌愋

More Updates
I've tweaked the encoder a little, and it's had a surprising impact on quality (I'd forgotten that in DHT, out-of-phase signals are effectively negative, so I was ignoring out-of-phase signals).
An earlier version of the code just took the larger of these out-of-phase signals, but we now take the RMS. Also, I added a fairly conservative window function to the encoder (Tukey, alpha 0.3), to try to combat artifacting.
Everything's updated accordingly.


Paint by Numbers (using programming, not numbers)

Spectral airbrushing (Python, PIL, scipy)

This uses a sophisticated mathematical algorithm to produce colourful nonsense. The algorithm is related to Google's PageRank algorithm, but for pixels instead of web pages.

I took this approach because I thought that unlike flood-fill based methods it might be able to cope with images like the chicken and the tree, where there are shapes that aren't entirely enclosed by black lines. As you can see, it sort of works, though it also tends to colour in different parts of the sky in different colours

For the mathematically minded: what it's doing is essentially constructing the adjacency graph of the while pixels in the image, then finding the top 25 eigenvectors of the graph Laplacian. (Except it's not quite that, because we do include the dark pixels, we just give their connections a lower weight. This helps in dealing with antialiasing, and also seems to give better results in general.) Having found the eigenvectors, it creates a random linear combination of them, weighted by their inverse eigenvalues, to form the RGB components of the output image.

In the interests of computation time, the image is scaled down before doing all this, then scaled back up again and then multiplied by the original image. Still, it does not run quickly, taking between about 2 and 10 minutes on my machine, depending on the input image, though for some reason the chicken took 17 minutes.

It might actually be possible to turn this idea into something useful, by making an interactive app where you can control the colour and intensity of each of the eigenvectors. That way you could fade out the ones that divide the sky into different sections, and fade in the ones that pick up on relevant features of the image. But I have no plans to do this myself :)

Here are the output images:

(It didn't work so well on the pumpkins, so I omit that one.)

And here is the code:

import sys
from PIL import Image
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spl
import os
import time

start_time = time.time()

filename = sys.argv[1]
img = Image.open(filename)
orig_w, orig_h = img.size

# convert to monochrome and remove any alpha channel
# (quite a few of the inputs are transparent pngs)
img = img.convert('LA')
pix = img.load()
for x in range(orig_w):
    for y in range(orig_h):
        l, a = pix[x,y]
        l = (255-a) + a*l/255
        a = 255
        pix[x,y] = l,a
img = img.convert('L')

orig_img = img.copy()

# resize to 300 pixels wide - you can get better results by increasing this,
# but it takes ages to run
orig_w, orig_h = img.size
print "original size:", str(orig_w)+ ', ' + str(orig_h)
new_w = 300
img = img.resize((new_w, orig_h*new_w/orig_w), Image.ANTIALIAS)

pix = img.load()
w, h = img.size
print "resizing to", str(w)+', '+str(h)

def coords_to_index(x, y):
    return x*h+y

def index_to_coords(i):
    return (int(i/h), i%h)

print "creating matrix"

A = sp.lil_matrix((w*h,w*h))

def setlink(p1x, p1y, p2x, p2y):
    i = coords_to_index(p1x,p1y)
    j = coords_to_index(p2x,p2y)
    ci = pix[p1x,p1y]/255.
    cj = pix[p2x,p2y]/255.
    if ci*cj > 0.9:
        c = 1
    else:
        c =  0.01
    A[i,j] = c
    return c

for x in range(w):
    for y in range(h):
        d = 0.
        if x>0:
            d += setlink(x,y,x-1,y)
        if x<w-1:
            d += setlink(x,y,x+1,y)
        if y>0:
            d += setlink(x,y,x,y-1)
        if y<h-1:
            d += setlink(x,y,x,y+1)
        i = coords_to_index(x,y)
        A[i,i] = -d

A = A.tocsr()

# the greater this number, the more details it will pick up on. But it increases
# execution time, and after a while increasing it won't make much difference
n_eigs = 25

print "finding eigenvectors (this may take a while)"
L, V = spl.eigsh(A, k=n_eigs, tol=1e-12, which='LA')

print "found eigenvalues", L

out = Image.new("RGB", (w, h), "white")
out_pix = out.load()

print "painting picutre"

V = np.real(V)
n = np.size(V,0)
R = np.zeros(n)
G = np.zeros(n)
B = np.zeros(n)

for k in range(n_eigs-1):
    weight = 1./L[k]
    R = R + V[:,k]*np.random.randn()*weight
    G = G + V[:,k]*np.random.randn()*weight
    B = B + V[:,k]*np.random.randn()*weight

R -= np.min(R)
G -= np.min(G)
B -= np.min(B)
R /= np.max(R)
G /= np.max(G)
B /= np.max(B)

for x in range(w):
    for y in range(h):
        i = coords_to_index(x,y)
        r = R[i]
        g = G[i]
        b = B[i]
        pixval = tuple(int(v*256) for v in (r,g,b))
        out_pix[x,y] = pixval

out = out.resize((orig_w, orig_h), Image.ANTIALIAS)
out_pix = out.load()
orig_pix = orig_img.load()

for x in range(orig_w):
    for y in range(orig_h):
        r,g,b = out_pix[x,y]
        i = orig_pix[x,y]/255.
        out_pix[x,y] = tuple(int(v*i) for v in (r,g,b))

fname, extension = os.path.splitext(filename)
out.save('out_' + fname + '.png')

print("completed in %s seconds" % (time.time() - start_time))


Mathematica CJam, 108 95 46 35 30 bytes

Edit: Ported to CJam! The original and ungolfed Mathematica code is at the bottom and explains the algorithm quite well.

li,{)Kb65430s2046sm*$f=0s*ip}/

And now I know CJam. :D Thanks to Dennis for some golfing improvements.

After analysing them a bit to determine how many there are below one quadrillion, I came to the conclusion that all eban numbers are basically base-1000 numbers using only a set of 20 digits:

0, 2, 4, 6, 30, 32, 34, 36, 40, 42, 44, 46, 50, 52, 54, 56, 60, 62, 64, 66

So we enumerate them by converting the input to base 20, picking the right digit from the set and build a base 1000 number from it.

This is how the code works in detail:

li                             "Read from STDIN, convert to integer n";
li,                            "Turn into a range array [0 ... n-1]";
li,{                        }/ "For each number execute a block";
li,{)                       }/ "Increment";
li,{)K                      }/ "K is initialised to 20, push that";
li,{)Kb                     }/ "Convert to base 20";
li,{)Kb65430s               }/ "Push a string with possible multiples of 10";
li,{)Kb65430s2046s          }/ "Push a string with possible least significant digits";
li,{)Kb65430s2046sm*        }/ "Take the Cartesian product of the two character
                                arrays, generating the 20 'digits'";
li,{)Kb65430s2046sm*$       }/ "Sort the result";
li,{)Kb65430s2046sm*$f=     }/ "For each digit in our base-20 number, get the
                                base-1000 digit from the list";
li,{)Kb65430s2046sm*$f=0s   }/ "Push a '0' character";
li,{)Kb65430s2046sm*$f=0s*  }/ "Join all the digits, with that '0' as the delimiter";
li,{)Kb65430s2046sm*$f=0s*ip}/ "Convert to an integer and print the result";

Here was the original Mathematica code, which doesn't encode the digit list and is hence fairly readable:

{0,2,4,6,30,32,34,36,40,42,44,46,50,52,54,56,60,62,64,66}[[IntegerDigits[#,20]+1]]~FromDigits~1000 & /@ Range @ # &


Implement Shamir's Secret Sharing reconstruction

bash, 271 chars

r(){
[ ${1/0/} ]&&{ r $(($2%$1)) $1;((t=u,u=v-$2/$1*u,v=t));}
}
read
((N=1928049029,n=0))
while read x[$n] y[$n]
do((n++))
done
for((i=n;z=(z+l)%N,i--;))do
for((j=n,l=y[i];j--;))do
((u=0,v=1,d=x[j]-x[i],M=N+d))
r M N
[ ${d/0/} ]&&((l=l*x[j]%N*(u+N)%N))
done
done
echo $z

The newlines could be replaced in most cases with semicolons, but I don't think there's any unnecessary whitespace.

(I hadn't realised before today that bash's integers are 64-bit - very helpful).

For bash the recursive GCD (exploiting global state) seems to be more compactible than the iterative one. This is mostly straightforward; the interesting trick is [ ${d/0/} ]&&foo which is effectively if [ $d -ne 0 ];then foo;fi


Python 2.7, 503 Bytes
This isn't particularly golfed, nor is it particularly efficient; it's just a relatively condensed enumeration of feasible strings that are brute-forced.  I don't think it would be too hard to create an admissible heuristic to use with A*, which would probably be a bit quicker.  I didn't bother doing that, though, because this method solves all of the examples in about 47 seconds on my laptop.
import re
v=lambda l,s:sum([len([m.start() for m in re.finditer('(?=%s)'%u,s)])*v for u,v in l])
def m(n,l,e):
 if len(e)==n:
  yield e
 else:
  u=1
  for s,v in sorted(l,key=lambda j:j[1],reverse=True):
   for i in range(len(s)-1,0,-1):
    if len(e)+len(s)-i <= n and e.endswith(s[:i]):
     for r in m(n,l,e+s[i:]):
      u=0;yield r
   if len(e)+len(s)<=n:
    for r in m(n,l,e+s):
     u=0;yield r
  if u:
   yield e
def p(n,l):
 b,r=-1,0
 for s in m(n,l,''):
  a=v(l,s)
  if a>b:b,r=a,s
 return r

To test it:
if __name__ == "__main__":
    for n, l in [
            (1, [("A", 7), ("B", 4), ("C", 100)]),     # => C
            (2, [("A", 2), ("B", 3), ("AB", 2)]),      # => AB
            (2, [("A", 1), ("B", 2), ("CD", 3)]),      # => BB
            (2, [("AD", 1), ("B", 2), ("ZB", 3)]),     # => ZB
            (3, [("AB", 2), ("BC", 1), ("CA", 3)]),    # => CAB
            (3, [("ABC", 4), ("DEF", 4), ("E", 1)]),   # => DEF
            (4, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => AAAA or ABAB or BABA or ABCD
            (5, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => BABCD or BABAB
            (5, [("ABC", 3), ("DEF", 4), ("CDG", 2)]), # => ABCDG
            (5, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABCAB
            (6, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABABAB
            (8, [("AA", 3), ("BA", 5)]),               # => BAAAAAAA
            (10, [("ABCDE", 19), ("ACEBD",  18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]) # => ACEBDACEBD
    ]:
        print p(n, l)

Explanation
The v function simply calculates the value of a given string by searching for all occurrences of the substrings in L.  The m function enumerates all strings of length n with prefix e that can be generated from the substrings in l.  m recursively calls itself; the first call should pass in '' for e.  For example:
>>> for s in m(4, [("A", 1), ("BAB", 2), ("ABCD", 3)], ''):print s
ABCD
BABA
ABCD
ABAB
AAAA

The p function simply loops through all possible strings (as enumerated by m) and returns the one with highest value (as determined by v).
Note that the m function actually prioritizes the enumeration by sorting based on substrings' values.  This turns out to be unnecessary to ensure optimality, and it actually hinders efficiency a bit; I could save ~20 or so bytes by removing it.


Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible

Bash + ImageMagick: 35 33
Default font, default text size, default colours:
convert label:Hello\ world! a.png

and here's the result:

Thanks to DigitalTrauma and sch for the help :-D


One Bad Ternary Operator Deserves Another

Ruby, 210 characters
Similar to @Jan Dvorak's solution but a bit more functional and a bit shorter.
f=FailSafe
e=[f&1,f&2,f&4,f&8,1-f].zip(["Detection zones staying in a given state","Bad visibility","Initialization","Bad configuration","No technical alarms"]).map{|a,b|a>0&&b}-[!0]
e[0]||="Unknown"
e.join"; "


Write a Polish notation interpreter, then change it to RPN in shortest number of chars

Python - 100!

I'm pretty sure I've met all the criteria. I don't think its possible to make it more identical, without just having a big ol' if block, which would violate the criteria. Using cmp(), and what @PeterTaylor pointed out you can determine the direction you need to go. Rather than use an if/then which would violate the spirit of the challenge, this get the position of the first number and operator and compares those. While the list comprehensions use an if this is just to safely filter the indices and doesn't direct help determine if we are doing forward or reverse polish notation, but this does bend the rules a bit.

Rule-bending program: Both prefix and reverse Polish notation

s = raw_input().strip()                          # Get input
ops = "*-+/^"                                    # A string of operators
num="0123456789"                                 # A string of numbers
p_num= min([s.index(n) for n in num if n in s])  # Find the first number
p_op = min([s.index(o) for o in ops if o in s])  # Find the first operator
                                                 # We use the above 2 lines to determine what
                                                 #   direction we are going on line '2' below

                          #  Just like the original below
s=s.split()                  #  1. Split the input
d = cmp(p_op,p_num)          #  2. Set the direction... depending on what comes first!
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

If the above is too rule bendy, here is the code I had before that scored 99.

Original program: Polish prefix notation

s = raw_input().split(" ")   #  1. Get input
d = 1                         # 2. Set the direction to forwards
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

Modified to produce: Reverse polish notation

s = raw_input().split(" ")
d = -1                        # 2. Set the direction to backwards
def f(i):
 if s[i] in "*-+/^":
  a = f(i+d)
  b = f(i+d)
  c = [a,b,a]
  inf = c[d-1]+s.pop(i)+c[d]
  return "("+inf+")"
 return s.pop(i)
print f([0,-1,42][d-1])       #11. No change, but this pulls the second last (-2) element
                              #    Hence, why we bump it to 3 elements long.

Differences (not including the comments):

Line 2: 1 char, added - to change from +1 to -1

For a total of 1 character changed, which in Polish notation, gives

- 100 1 = 99


Python 66

print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real

Output

>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
121
110000000000
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
1000
316227766017

   This solution uses Spiral of Theodorus on a complex plane to achieve the result.


JavaScript (ES7),  236 ... 193  185 bytes

Outputs by modifying the input matrix.

m=>(g=(d,x,y,v,r=m[y],h=_=>++r[x]<9?g(d,x,y,v)||h():r[x]=0)=>r&&1/(n=r[x])?x|y|!v?n?g(d='21100--13203-32-21030321'[n*28+d*3+7&31],x+--d%2,y+--d%2,v+=n<7||.5):h():!m[v**.5|0]:0)(0,0,0,0)

Try it online!

(includes some post-processing code to print the result both as a matrix and as a flat list compatible with the visualization tool provided by the OP)

Results

Test case #1
Test case #2
Test case #3

How?

Variables

\$g\$ is a recursive function taking the current direction \$d\$, the current coordinates \$(x,y)\$ and the number of visited cells \$v\$.

The following variables are also defined in the scope of \$g\$:

\$r\$ is the current row of the matrix.

r = m[y]

\$h\$ is a helper function that tries all values from \$1\$ to \$8\$ for the current cell and invokes \$g\$ with each of them. It either stops as soon as \$g\$ succeeds or sets the current cell back to \$0\$ if we need to backtrack.

h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0

Initial checks

We first make sure that our current location is valid and we load the value of the current cell into \$n\$:

r && 1 / (n = r[x]) ? ... ok ... : ... failed ...

We test whether we're back to our starting position, i.e. we're located at \$(0,0)\$ and we've visited at least a few cells (\$v>0\$):

x | y | !v ? ... no ... : ... yes ...

For now, let's assume that we're not back to the starting point.

Looking for a path

If \$n\$ is equal to \$0\$, we invoke \$h\$ to try all possible values for this tile.

If \$n\$ is not equal to \$0\$, we try to move to the next tile.

The tile connections are encoded in a lookup table, whose index is computed with \$n\$ and \$d\$, and whose valid entries represent the new values of \$d\$.

d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31]

The last 8 entries are invalid and omitted. The other 4 invalid entries are explicitly marked with hyphens.

For reference, below are the decoded table, the compass and the tile-set provided in the challenge:

   | 1 2 3 4 5 6 7 8
---+-----------------
 0 | 0 - - 1 3 - 3 1          1
 1 | - 1 - - 2 0 2 0        0 + 2
 2 | 2 - 1 - - 3 1 3          3
 3 | - 3 0 2 - - 0 2

We do a recursive call to \$g\$ with the new direction and the new coordinates. We add \$1/2\$ to \$v\$ if we were on a tile of type \$7\$ or \$8\$, or \$1\$ otherwise (see the next paragraph).

g(d, x + --d % 2, y + --d % 2, v += n < 7 || .5)

If \$d\$ is invalid, \$x\$ and \$y\$ will be set to NaN, forcing the next iteration to fail immediately.

Validating the path

Finally, when we're back to \$(0,0)\$ with \$v>0\$, it doesn't necessarily mean that we've found a valid path, as we may have taken a shortcut. We need to check if we've visited the correct number of cells.

Each tile must be visited once, except tiles \$7\$ and \$8\$ that must be visited twice. This is why we add only \$1/2\$ to \$v\$ when such a tile is visited.

In the end, we must have \$v = N^2\$. But it's also worth noting that we can't possibly have \$v > N^2\$. So, it's enough to test that we don't have \$v < N^2\$, or that the \$k\$th row of the matrix (0-indexed) does not exist, where \$k=\lfloor\sqrt{v}\rfloor\$.

Hence the JS code:

!m[v ** .5 | 0]

Formatted source

m => (
  g = (
    d,
    x, y,
    v,
    r = m[y],
    h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0
  ) =>
    r && 1 / (n = r[x]) ?
      x | y | !v ?
        n ?
          g(
            d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31],
            x + --d % 2,
            y + --d % 2,
            v += n < 7 || .5
          )
        :
          h()
      :
        !m[v ** .5 | 0]
    :
      0
)(0, 0, 0, 0)


I know URL shorteners are cheaty but since everyone else is using them I probably should.

Bash, with bc and URL shortener: 67 62 60 58 54

bc<<<`wget x.co/4Ccg3 -qO-|grep -oP "(?<='>)[0-9]+"`*2

Downloads the relevant page to STDOUT, then searches for '> followed by a sequence of digits - it misuses the fact that in the page's source code, single quotes are only rarely used; in fact the sequence '> occurs twice, and only once followed by a number, which is the number of edits. Using the Perl-style lookbehind, the '> isn't actually included in the match.

The -o option makes grep output only the matched string rather than the entire line containing it (there is a h1 on the same line and I don't want that).

The resulting number of edits is concatenated with *2 and sent to bc.

@11684 pointed out that you start out with 1 reputation, but the asker clearly forgot that so it's not mentioned in the question (it would break existing answers if it was). If you want to add that in just put in +1 at the end of the code, adding 2 chars.

SHELF, 36 - doesn't count as the language was created after the question

, `W x.co/4Ccg3|t "(?<='>)[0-9]+"`*2

SHELF is a golfed version of Bash, like PYG is for Python.


Java

Let's calculate the absolute value of a number. Java has Math.abs for this purpose, however the number we're using could be null sometimes. So we need a helper method to deal with that case:

public class NPE {
    public static Integer abs(final Integer x) {
        return x == null ? x : Math.abs(x);
    }

    public static void main(final String... args) {
        System.out.println(abs(null));
    }
}

If x is null, return null, else use Math.abs().
The code is very simple and clear, and should work fine... right?

By the way, using this line instead:

return x == null ? null : Math.abs(x);

works correctly. I thought about making this a spoiler, but.. I think it's just as puzzling :)

Ok, an explanation:

   First, Math.abs does not take an Integer, but an int (there are also overloaded methods for other numeric types) and also returns an int. In java, int is a primitive type (and can not be null) and Integer is its corresponding class (and can be null). Since java version 5, a conversion between int and Integer is performed automatically when needed. So Math.abs can take x, automatically converted to int, and return an int.

 Now the weird part: when the ternary operator (?:) has to deal with 2 expressions where one has a primitive type and the other one has its corresponding class (such as int and Integer), one would expect that java would convert the primitive to the class (aka "boxing"), especially when the type it needs (here for returning from the method) is the reference (class) type, and the first expression is also of the reference type. But java does exactly the opposite: it converts the reference type to the primitive type (aka "unboxing"). So in our case, it would try to convert x to int, but int can not be null, thus it throws a NPE.

 If you compile this code using Eclipse, you will actually get a warning: "Null pointer access: This expression of type Integer is null but requires auto-unboxing"

 Also see:
 https://stackoverflow.com/questions/7811608/java-npe-in-ternary-operator-with-autoboxing
 https://stackoverflow.com/questions/12763983/nullpointerexception-through-auto-boxing-behavior-of-java-ternary-operator


C + PicoSAT, 2345 995 952 bytes

#include<picosat.h>
#define f(i,a)for(i=a;i;i--)
#define g(a)picosat_add(E,a)
#define b calloc(z+1,sizeof z)
#define e(a,q)if(a)A[q]^A[p]?l[q]++||(j[++k]=q):s[q]||(i[q]=p,u(q));
z,F,v,k,n,h,p,q,r,C,*x,*A,*i,*l,*s,*j,*m;u(p){s[m[++n]=p]=1;e(p%F-1,p-1)e(p%F,p+1)e(p>F,p-F)e(p<=F*v-F,p+F)}t(){f(q,k)l[j[q]]=0;f(q,n)s[m[q]]=0;k=n=0;i[p]=-1;u(p);}main(){void*E=picosat_init();if(scanf("%d,%d",&F,&v)-2)abort();z=F*v;for(x=b;scanf("%d,%d,%d",&r,&p,&q)==3;g(p),g(0))x[p=F-p+q*F]=r;f(p,F*v-F)if(p%F)g(p),g(p+1),g(p+F),g(p+F+1),g(0);for(A=b,i=b,l=b,s=b,j=b,m=b;!C;){picosat_sat(E,C=h=-1);f(p,F*v)A[p]=picosat_deref(E,p)>0,i[p]=0;f(p,F*v)if(x[p])if(i[q=p]){for(g(-q);i[q]+1;)q=i[q],g(-q);g(C=0);}else if(t(),r=n-x[p]){f(q,r<0?k:n)g(r<0?j[q]:-m[q]);g(C=0);}f(p,F*v)if(!i[p])if(t(),A[p]){g(-++z);f(q,k)g(j[q]);g(C=0);f(q,n)g(-m[q]),g(z),g(0);}else{C&=h++;f(q,k)g(-j[q]);g(++z);g(++z);g(0);f(q,F*v)g(s[q]-z),g(q),g(0);}}f(p,F*v)putchar(A[p]?35:46),p%F-1||puts("");}

Try it online!

(Warning: this TIO link is a 30 kilobyte URL that contains a minified copy of PicoSAT 965, so you might not be able to load it in some browsers, but it loads in at least Firefox and Chrome.)

How it works

We initialize the SAT solver with a variable for each cell (land or water), and only the following constraints:

Every numbered cell is land.
Every 2×2 rectangle has at least one land.

The rest of the constraints are difficult to encode directly into SAT, so instead we run the solver to get a model, run a sequence of depth-first searches to find the connected regions of this model, and add additional constraints as follows:

For every numbered cell in a land region that’s too big, add a constraint that there should be at least one water cell among the current land cells in that region.
For every numbered cell in a land region that’s too small, add a constraint that there should be at least one land cell among the current water cells bordering that region.
For every numbered cell in the same land region as another numbered cell, add a constraint that there should be at least one water cell along the path of current land cells between them (found by walking the parent pointers left over from the depth-first search).
For every land region including no numbered cells, add constraints that either

all of those current land cells should be water, or
at least one of the current water cells bordering that region should be land.

For every water region, add constraints that either

all of those current water cells should be land, or
every cell other than those current water cells should be land, or
at least one of the current land cells bordering that region should be water.

Taking advantage of the incremental interface to the PicoSAT library, we can immediately rerun the solver including the added constraints, preserving all the previous inferences made by the solver.  PicoSAT gives us a new model, and we continue iterating the above steps until the solution is valid.

This is remarkably effective; it solves 15×15 and 20×20 instances in a tiny fraction of a second.

(Thanks to Lopsy for suggesting this idea of interactively constraining connected regions in an incremental SAT solver, a while back.)

Some larger test cases from puzzle-nurikabe.com

A random page of 15×15 hard puzzles (5057541, 5122197, 5383030, 6275294, 6646970, 6944232):

15,15 1,5,1 3,9,1 5,4,2 1,6,2 2,11,2 2,2,3 3,9,3 2,4,4 1,10,4 5,12,4 3,1,5 1,3,5 3,8,5 1,13,5 5,5,6 1,12,6 1,2,8 2,9,8 1,1,9 2,6,9 6,11,9 3,13,9 5,2,10 2,4,10 4,10,10 1,5,11 2,12,11 2,3,12 2,8,12 5,10,12 1,5,13 1,9,13 1,6,14 1,8,14
15,15 4,2,0 2,5,0 1,3,1 2,14,2 1,3,3 2,11,3 1,13,3 1,5,4 11,7,4 1,9,4 1,4,5 1,8,5 2,10,5 12,14,5 3,5,6 1,4,7 2,10,7 3,9,8 4,0,9 1,4,9 1,6,9 3,10,9 1,5,10 1,7,10 8,9,10 1,1,11 10,3,11 2,11,11 6,0,12 1,11,13 2,9,14 1,12,14
15,15 2,2,0 8,10,0 2,3,1 2,14,2 2,3,3 3,5,3 3,9,3 2,11,3 5,13,3 6,0,4 3,7,4 3,3,5 2,11,5 2,6,6 1,8,6 1,4,7 2,10,7 1,6,8 2,8,8 5,3,9 2,11,9 2,7,10 7,14,10 2,1,11 4,3,11 2,5,11 1,9,11 2,11,11 2,0,12 4,6,13 1,11,13 3,4,14 1,12,14
15,15 2,0,0 2,4,0 3,6,1 2,10,1 1,13,1 2,5,2 2,12,2 3,0,3 2,2,3 4,7,3 2,9,3 1,14,3 1,4,4 1,8,4 2,12,5 4,2,6 3,4,6 1,14,6 7,7,7 1,10,8 2,12,8 3,2,9 2,14,9 2,0,10 2,6,10 1,10,10 2,5,11 4,7,11 2,12,11 1,14,11 3,2,12 3,9,12 1,1,13 2,4,13 3,8,13 2,10,14 5,14,14
15,15 1,3,0 1,14,0 3,7,1 3,10,1 2,13,1 3,1,2 4,5,2 2,12,3 3,3,4 1,8,4 1,1,5 3,5,5 1,9,5 5,13,5 3,3,6 1,8,6 2,2,7 2,12,7 1,6,8 1,8,8 2,11,8 2,1,9 4,5,9 2,9,9 2,13,9 2,6,10 4,11,10 1,2,11 3,9,12 2,13,12 3,1,13 2,4,13 3,7,13 1,0,14
15,15 2,8,0 2,4,1 2,7,1 1,10,1 6,4,3 1,1,4 12,5,4 3,11,4 5,13,4 3,10,5 3,0,6 1,6,6 2,8,6 4,13,7 2,3,8 1,6,8 3,8,8 2,14,8 2,4,9 5,1,10 4,3,10 1,9,10 6,13,10 3,8,11 1,10,11 3,4,13 2,7,13 3,10,13 1,6,14 1,14,14

A random page of 20×20 normal puzzles (536628, 3757659):

20,20 1,0,0 3,2,0 2,6,0 1,13,0 3,9,1 3,15,1 2,7,2 3,13,2 3,0,3 2,3,3 3,18,3 3,5,4 2,9,4 2,11,4 2,16,4 1,0,5 2,7,5 1,10,5 1,19,5 3,2,6 1,11,6 2,17,6 2,0,7 3,4,7 5,6,7 2,9,7 4,13,7 3,15,7 1,3,8 1,10,8 1,14,9 2,18,9 3,1,10 2,4,10 1,8,10 1,10,10 3,12,10 3,16,10 1,9,11 1,17,11 2,19,11 2,0,12 2,2,12 1,4,12 4,6,12 2,13,12 2,15,12 1,14,13 2,17,13 1,3,14 2,5,14 4,7,14 2,15,14 3,0,15 1,2,15 2,13,15 3,18,15 3,7,16 7,10,16 1,17,16 2,0,17 2,3,17 2,5,17 3,11,17 3,15,17 1,0,19 1,2,19 1,4,19 2,6,19 5,8,19 1,11,19 1,13,19 3,15,19 2,18,19
20,20 1,0,0 1,4,0 5,8,0 1,17,0 1,19,0 2,17,2 3,6,3 2,10,3 2,12,3 4,14,3 6,0,4 3,4,4 4,7,4 1,11,4 1,18,4 1,6,5 3,12,5 4,15,5 4,4,6 2,16,6 2,19,6 6,0,7 3,10,7 2,12,8 2,17,8 3,3,9 2,5,9 4,8,9 2,10,9 3,0,10 1,2,10 5,14,10 2,16,10 2,19,10 7,7,11 3,12,12 2,17,12 2,2,13 4,4,13 3,6,13 4,14,13 3,0,14 1,3,14 1,5,14 3,16,14 1,2,15 1,9,15 2,11,15 5,13,15 3,19,15 1,4,16 3,6,16 1,3,17 1,12,17 1,14,17 1,16,17 6,0,19 2,2,19 3,5,19 2,7,19 5,9,19 1,11,19 2,13,19 1,15,19 4,17,19


Python, 127 bytes

Creates a Sierpinski triangle.

import Image
f=1e3
a=Image.new('RGB',(f,f))
p=a.load()
r=range(f)
for i in r:
 for j in r:p[i,j]=(i*16&j*16,)*3
a.save('s.png')


Python - 202 Bytes

D=lambda p:[i*p[i]for i in range(1,len(p))]
A=lambda p,x:p>[]and p[0]+x*A(p[1:],x)
def N(p):f=D(p);s=D(f);x=1.;y=-x;exec'x-=A(f,x)/A(s,x);y-=A(f,y)/A(s,y);'*99;return A(p,x),A(p,y)
print min(N(input()))

11 bytes saved due to @xnor.

Input is taken from stdin, and is expected to be in the following format: [x0, x1, x2, ...]. For example, the sample in the problem description would be entered as [-12, 0, 0, 4, 0, 0, 6].

Functions

D - Calculates the derivative of a polynomial p.
A - Applies a polynomial p to the value x.
N - Uses Newton's Method to calculate local minima/maxima of a polynomial p.

Note: For higher order polynomials, there may be several local minima. In these cases, this function is not guaranteed to find the global minimum.

Sample Usage

$ echo [-12, 0, 0, 4, 0, 0, 6] | python poly-min.py
-12.6666666667


Calculate a check digit using the Damm algorithm

CJam, 54 characters

q_o{A,s&},{~0"끼´慜䪝膞䝮芜㮜ꡞ靓渏縰蒆㣉倔쵶"2G#bAb+A/T==:T;}/T

There is one unprintable character in there, so you might want to use the permalink below.

Test it here.

Explanation

The interim digit is being tracked in  T, which CJam initialises to 0.

q_o                                  "Read STDIN, duplicate it and print it.";
   {A,s&},                           "Filter out all non-digit characters.";
          {                     }/   "For each digit character.";
           ~                         "Eval to get the digit itself.";
            0                        "Push a zero.";
             "..."2G#b               "Push that long string and interpret the character
                                      codes as the digits of a base-2^16 number.";
                      Ab+            "Get base-10 digits and prepend the 0.";
                         A/          "Split into rows of 10.";
                           T=        "Select row based on interim digit.";
                             =       "Select column based on current digit.";
                              :T;    "Store in T and discard.";
                                   T "Push the interim digit to be printed.";


Calculate the bitruncated cubic distance between two points

Golfscript, 10 13 characters
~{$~\-}%$~+\;

input: a space-separated array of three two-element arrays of integers, wrapped in square brackets. Each pair of integers denotes the coordinates of both octahedra in one axis. If half-coordinate inputs are to be supported, the input should be scaled up by an even factor (say, 10).
output: a single integer, scaled up by the same amount as the input
reads: "eval the input, for each axis: {sort both coordinates, then subtract the smaller from the larger}, sort the differences, then dump them onto the stack (resulting in three separate numbers), add the top two (= largest two coordinates) and discard the element just below".
proof:
the algorithm to reach a destination in this amount of steps is:

If all three coordinate differences are nonzero, make a diagonal step. This reduces all three differences by 0.5, meaning their order doesn't change and the sum of the largest two differences reduces by 1
If only one coordinate difference is nonzero, make an orthogonal step. This reduces the largest difference by 1
If two of the difference are nonzero, either of these steps can be chosen.

Thus, this algorithm never underestimates the distance. Also, it is not possible to reduce the sum of top largest two differences by more than 1 in a single step, meaning this algorithm never overestimates either. Thus, the algorithm "sum of the largest two absolute values of coordinate differences" is correct.
example:
;"[[20 0] [30 0] [20 -20]]"
~{$~\-}%$~+\;
#70

test: http://golfscript.apphb.com/?c=OyJbWzIwIDBdIFszMCAwXSBbMjAgLTIwXV0iCn57JH5cLX0lJH4rXDs%3D


Jelly, 127 bytes

“£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘
OḄ;407;270;“ọḷḊḲɦ‘%/i@“¡Ṙ×!⁸Ọ5`ỊV-ṙQȷṖÞ(sĿȮ^k³M"ɓmEf¤*0C[ạƇŻȥ#BṚñİmZẓeȦUƈ!ċ€@Ȧʋ)ƙḅyẉ’b158¤ị¢

Try it online!

Test Cases

How it Works

Essentially, this tries to convert the ords of the characters input into a binary value, for example "joel" -> [106, 111, 101, 108]-> 2^3*106 + 2^2*111 + 2^1*101 + 2^0*108.

Then, this value is taken mod 407, then mod 270, then [a few more mods], then mod 160. This is useful because it maps all 66 string inputs to integers between 0 and 158 (lucky on final mod).

The integer is indexed from the integer list “ọḷḊḲɦ...ƙḅyẉ’b158¤ to find the value of n such that the input has the n-th least number of chapters. Joel happens to have the 7-th least number of chapters.

This value of n is further indexed into the list “£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘ to find the exact number of chapters.

Possible improvement: inputs with the same number of chapters can hash to the same value from the mods (0% collision is not necessary), but I did not account for that in my program to determine the sequence of mods.


What code compiles in the most number of languages?

3 Languages - C, C++, and Python

#ifdef _cplusplus
    #include <iostream>
    #define print() int main(){cout << "Hello world! -- from C++" << endl;}
#elif (defined __STDC__) || (defined __STDC_VERSION__)
    #include <stdio.h>
    #define print() int main(){printf("Hello world! -- from C\n");}
#else
import builtins
print = lambda : builtins.print("Hello world! -- from Python")
#endif

print()

Something different is printed in each language. In C & C++, lines starting with '#' are preprocessing directives, but those same lines are comments in Python.


Ruby, 310 311 characters
h=Hash[(?a..?z).zip %w{e bub kut dud i fuf jug hash ay jag kak lul mum nun o pup kwak rut sus tut yu vuv waks eks yak zuz}]
h["rd"]="ruddud"
h.keys.each{|k|h[k[0]+k]="skwer"+h[k]}
h.keys.each{|k|h[k.upcase]=h[k].upcase}
h=h.invert if b=getc==?1
i=gets
print b ?0:1;(k=i;k=k.chop until h[k]||!k[1];$><<(h[k]||k);i[k]="")until i==""

Correctly handles:

squared uppercase (unfix by merging iterations gains 18 characters)

if AA should turn into skwerE, swap lines #3 and #4
I also assume aA and Aa should turn into eE and Ee respectively

rrd translates to `skwerruddud (unfix gains 3 characters)
in cubes the first pair is reported as a square. rrrd turns into skwerrutruddud. rrrrd becomes skwerrutskwerruddud
the output is now a valid input. It is, indeed, required by the spec
uses newline as input terminator

Input requires there be no newline between the indicator and the string, output puts it there (fix: 1 character). Console output suppressed at this point to prevent mixing with STDIN. Unfix free, it's just a little bit uglier.
Example input:
0Hello

Output:
1
HASHiskwerlulo


Find the Intersection of 2 Sets in Unioned Interval Notation

Mathematica, 41 bytes - 15% = 34.85

Mathematica has a built-in function for interval intersection.

List@@IntervalIntersection@@Interval@@@#&

Example:

In[1]:= List@@IntervalIntersection@@Interval@@@#&[{{{-90, -4}, {4, Infinity}}, {{-50,Infinity}}}]

Out[1]= {{-50, -4}, {4, Infinity}}


JavaScript (ES6),  38 37  36 bytes
Expects an array of Boolean values, with false for + and true for -. Returns an integer.

a=>a.map(c=>a=a++?c?a-2:a%10:9>>c)|a

Try it online!
Commented
It's important to note that a++ with a = [ true ] is evaluated to NaN because it's first coerced to the string "true" and then to a number. That's why we can safely re-use the array a[] to store the temperature even when we get the singleton [ true ] as input.
a =>             // a[] = input array, re-used to store the temperature
  a.map(c =>     // for each command c in a[]:
    a =          //   update the temperature:
      a++ ?      //     if a is numeric and not equal to 0
                 //     (increment it afterwards):
        c ?      //       if this is a '-':
          a - 2  //         subtract 2
        :        //       else:
          a % 10 //         apply a modulo 10
      :          //     else:
        9 >> c   //       yield 4 if this is a '-', or 9 if this is a '+'
  ) | a          // end of map(); return the final result


Include a JavaScript script with JavaScript

49 bytes

document.write`<script src=//v.ht/KvtI></script>`

no one clearly said: you should keep current page content


Ruby (130) (121) (113) (102)

EDIT: Saved 9 characters, thanks to Howard.

EDIT 2: Another 8 characters, courtesy of Howard.

EDIT 3: Saved 11 more characters after learning how to use Ruby's % operator for sprintf.

b=(0..4).map{gets.to_i 2}
32.times{|x|z=0;k=b.map{|i|x=z^i^31&(x<<1^x>>1)^z=x;'%05b'%z}
puts k if x<1}

Accepts 5 lines of input from stdin. Outputs all solutions as 5x5 grids as specified, though there are no extra line breaks between solutions (or between the input and the solutions).

Solutions are found by iterating through all 32 possibilities for the top row, since the top row determines the switches that must be flipped in the following rows.

Input:

00000
00000
00110
01000
00101

Output:

00000
00000
00000
00110
00001
01110
10101
11011
10011
01111
10101
10101
00000
10011
10100
11011
00000
11011
00110
11010


Chess - Find all legal moves (except castling and en passant)

C - 391 bytes
Takes input as command line arguments and prints to stdout with the squares labeled from 0 to 63.
OK, I had a few minutes so I tried to delete all the bits relating to the detection of check. I think it is now not very efficient though...
O(x,y){return((x&7)-(y&7))/5;}
B[64],*b=B,J=32,M,L,x,*X,N;
main(int c,char**V){
for(;x=*V[1]++;c=J&2**V[2])
x>56?*b++=x:x>47?b+=x-48:0;
for(;b-->B;)
for(M=-1,N=*b%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*b|J);*b&&*b&J^c&&(M=M<0?*++*V%J:-M,**V<96);)
for(x=b-B,L=N?9^*b&8:1+(x/8==1+c/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^c&&N|(!*X^M&1&&M<0^!c)?printf("%d-%d ",b-B,x),L*!*X:0)
X=B+(x+=M);}

478 byte check-detecting version
O(x,y){return((x&7)-(y&7))/5;}
B[64],*b=B,c,I,J=32;
main(int C,char**V){
int*D,M,L,t,x,*X,N;
for(;b-B<64;C=c=J&2**V[2])
(t=*V[1]++)>56?*b++=t:t>47?b+=t-48:0;
for(D=b;D-->B;)
for(M=-1,N=*D%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*D|J);*D&&*D&J^C&&(M=M<0?*++*V%J:-M,**V<96);)
for(x=D-B,L=N?9^*D&8:1+(x/8==1+C/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^C&&N|(!*X^M&1&&M<0^!C)?c^C?I|=*X%J==11:(*X=*D,*D=I=0,main(C^J,V+1),*D=*X,I||printf("%d-%d ",D-B,x)),L*!(*X=t):0)
X=B+(x+=M),t=*X;}


Python 3, 65 bytes · 0.8 = 52.0

from ipaddress import*
n=4**64
while n:n-=1;print(IPv6Address(n))


JavaScript (ES6), 51 49 45 bytes

1-indexed.

f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k

Demo

f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k

for(n = 1; n <= 20; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

Formatted and commented

f = (                         // f = recursive function taking:
  n,                          //   n = input
  s = k = ''                  //   s = string of concatenated squares, k = counter
) =>                          //
  n ?                         // if we haven't reached the n-th term yet:
    f(                        //   do a recursive call with:
      n - !!s.match(++k * k), //     n decremented if k² is an early bird square
      s + k * k               //     s updated
    )                         //   end of recursive call
  :                           // else:
    k                         //   return k

Non-recursive version, 53 bytes

This one does not depend on your engine stack size.

n=>{for(k=s='';n-=!!(s+=k*k).match(++k*k););return k}

Try it online!


Tesco's Burger Relish Best Before End date number

PowerShell, 74 70 67 bytes

param($y,$m,$d)-join"$y 00$((date "$m/$d/$y"|% d*r)-1)"[2,3+-3..-1]

Try it online!

Exactly what it says on the tin (but formatted weirdly). Takes in $year, $month, $day, plucks out the last two digits of the $year, gets a .NET datetime object of the specified day, then gets the dayofyear (with |% d*r) thereof. Subtracts one to make it zero-indexed, then uses string formatting and slicing to make it three-padded (e.g., 000 instead of 0), and then -joins it all together into a single string with implicit output.

Note this is culture dependent due to the datetime formatting. This works in en-us, which is what TIO also uses.

-3 bytes thanks to mazzy


Python 3, 294 301 287 356 bytes

import random as r
r=r.randint
k=[r(i)+1for i in[20]*r(5,11)]
p=print
if 7in k:k=[i-1for i in k]
p(k)
if 0in k:k=[i+1for i in k]
p(k)
i=k.find(13)
if not~i:k=k[:i]
p(k)
if 2in k:k=[i for i in k if~i%2]
p(k)
a=0
z=len(k)>2and k[2]%2
if 20in k:a=20*len(k)**z
if~z:p(k)
while sum(k)>50:k=k[:-1]
if~z:p(k)
if a:p(a)
else:a=sum(k);p(a,hex(a)*(16in k))
if~z:p(k)

I don't know how you're going to prevent people circumventing the rules, but this one uses the procedure specified.

+7 bytes; thanks to @YamB for saving a few bytes; added a lot more to fix a previous error.
-14 bytes thanks to @RootTwo and myself and also corrected the error.
+83 bytes; this is getting horribly long because OP keeps changing the  rules.
-some number of bytes thanks to @ZacharyT


Pip, score = 38
eyli:
"Once
when0
I was
si01x
year5
old I
0sMw1
1M 0"
X1RMh
Rnsxy
iR:'M
'aiR
:5'si

Alphabet:  "'015:IMORXacdehilnorswxy
(I sure would hate to try this in a real programming language.)
Explanation:
eyl      Statements consisting of single variables are no-ops
i:       Assign to i the following:
"Once
when0
I was
si01x
year5
old I
0sMw1
1M 0"    ...this string
X1       ...repeated once (no-op to get alignment right)
RMh      ...with all 1s and 0s removed (h is preinitialized to 100)
Rns      ...and all newlines replaced with spaces.
xy       More no-ops
iR:'M'a  Replace every M with a, assigning result back to i
iR:5's   Replace every 5 with s, assigning result back to i
i        Auto-print i


Find the rate of change at a point on a polynomial

Mathematica, 6 bytes
#'@#2&

(Beat THAT, MATL and 05AB1E)
The first argument must be a polynomial, with # as its variable and with & at the end (i.e. a pure function polynomial; e.g. 3 #^2 + # - 7 &). The second argument is the x-coordinate of the point of interest.
Explanation
#'

Take the derivative of the first argument (1 is implied).
... @#2&

Plug in the second argument.
Usage
#'@#2&[4 #^3 - 2 #^4 + 5 #^10 &, 19] (* The first test case *)

16134384838410


Create a square of increasing size by replicating the initial code

Pyth, 2 bytes

5

Try it online! Also Try it doubled, tripled!

How does that work?

\n is the command that prints its argument with a trailing newline, while returning it simultaneously. So, each time you make an insertion, you turn the integer literal 5 into a number containing N copies of 5 concatenated, and the leading newlines basically make sure it's printed the appropriate number of times, thus keeping it square.


QuadR, 77 75 bytes
-2 thanks to Neil.
our
(i|y)se
ae|oe
([aeiou]l)l
([^aeiou])re\b
xion\b
or
\1ze
e
\1
\1er
ction

Try it online!
The first half of the strings are PCRE patterns while the latter half are their substitutions.


Perl 6, 27 bytes

{+minmax [\+] @_ Z<=>0,|@_}

Try it online!
Explanation
@_ Z<=>0,|@_ uses the zip metaoperator (Z) with the compare operator (<=>) to zip the list with itself offset by 1 and return the result of the comparison., e.g. [43, 48, 48, 48, 52, 50, 48, 50] -> (More More Same Same More Less Less More)
[\+] Reduces the list by summing over it (More = 1, Same = 0, Less = -1), however the \ does a 'triangular reduction' which produces a list of each calculation instead of the end result, e.g. (More More Same Same More Less Less More) -> (More 2 2 2 3 2 1 2)
minmax returns the range of smallest..largest, effectively removing duplicates. (More 2 2 2 3 2 1 2) -> Order::More..3
+ just returns the length of this range (list), which is the result


The number of possible numeric outcomes of parenthesizations of 2^2^...^2

Python 2.7

This approach takes advantage of the following considerations:

Any integer can be represented as a sum of powers of two.  The exponents in the powers of two can also be represented as powers of two.  For example:

8 = 2^3 = 2^(2^1 + 2^0) = 2^(2^(2^0) + 2^0)

These expressions that we end up with can be represented as sets of sets (in Python, I used the built-in frozenset):

0 becomes the empty set {}.
2^a becomes the set containing the set representing a.  E.g.: 1 = 2^0 -> {{}} and 2 = 2^(2^0) -> {{{}}}.
a+b becomes the concatenation of the sets representing a and b.  E.g., 3 = 2^(2^0) + 2^0 -> {{{}},{}}

It turns out that expressions of the form 2^2^...^2 can easily be transformed into their unique set representation, even when the numerical value is much too large to be stored as an integer.

For n=20, this runs in 8.7s on CPython 2.7.5 on my machine (a bit slower in Python 3 and much slower in PyPy):

"""Analyze the expressions given by parenthesizations of 2^2^...^2.

Set representation:  s is a set of sets which represents an integer n.  n is
  given by the sum of all 2^m for the numbers m represented by the sets
  contained in s.  The empty set stands for the value 0.  Each number has
  exactly one set representation.

  In Python, frozensets are used for set representation.

  Definition in Python code:
      def numeric_value(s):
          n = sum(2**numeric_value(t) for t in s)
          return n"""

import itertools

def single_arg_memoize(func):
    """Fast memoization decorator for a function taking a single argument.

    The metadata of <func> is *not* preserved."""

    class Cache(dict):
        def __missing__(self, key):
            self[key] = result = func(key)
            return result
    return Cache().__getitem__

def count_results(num_exponentiations):
    """Return the number of results given by parenthesizations of 2^2^...^2."""
    return len(get_results(num_exponentiations))

@single_arg_memoize
def get_results(num_exponentiations):
    """Return a set of all results given by parenthesizations of 2^2^...^2.

    <num_exponentiations> is the number of exponentiation operators in the
    parenthesized expressions.

    The result of each parenthesized expression is given as a set.  The
    expression evaluates to 2^(2^n), where n is the number represented by the
    given set in set representation."""

    # The result of the expression "2" (0 exponentiations) is represented by
    # the empty set, since 2 = 2^(2^0).
    if num_exponentiations == 0:
        return {frozenset()}

    # Split the expression 2^2^...^2 at each of the first half of
    # exponentiation operators and parenthesize each side of the expession.
    split_points = xrange(num_exponentiations)
    splits = itertools.izip(split_points, reversed(split_points))
    splits_half = ((left_part, right_part) for left_part, right_part in splits
                                           if left_part <= right_part)

    results = set()
    results_add = results.add
    for left_part, right_part in splits_half:
        for left in get_results(left_part):
            for right in get_results(right_part):
                results_add(exponentiate(left, right))
                results_add(exponentiate(right, left))
    return results

def exponentiate(base, exponent):
    """Return the result of the exponentiation of <operands>.

    <operands> is a tuple of <base> and <exponent>.  The operators are each
    given as the set representation of n, where 2^(2^n) is the value the
    operator stands for.

    The return value is the set representation of r, where 2^(2^r) is the
    result of the exponentiation."""

    # Where b is the number represented by <base>, e is the number represented
    # by <exponent> and r is the number represented by the return value:
    #   2^(2^r) = (2^(2^b)) ^ (2^(2^e))
    #   2^(2^r) = 2^(2^b * 2^(2^e))
    #   2^(2^r) = 2^(2^(b + 2^e))
    #   r = b + 2^e

    # If <exponent> is not in <base>, insert it to arrive at the set with the
    # value: b + 2^e.  If <exponent> is already in <base>, take it out,
    # increment e by 1 and repeat from the start to eventually arrive at:
    #   b - 2^e + 2^(e+1) =
    #   b + 2^e
    while exponent in base:
        base -= {exponent}
        exponent = successor(exponent)
    return base | {exponent}

@single_arg_memoize
def successor(value):
    """Return the successor of <value> in set representation."""
    # Call exponentiate() with <value> as base and the empty set as exponent to
    # get the set representing (n being the number represented by <value>):
    #   n + 2^0
    #   n + 1
    return exponentiate(value, frozenset())

def main():
    import timeit
    print timeit.timeit(lambda: count_results(20), number=1)
    for i in xrange(21):
        print '{:.<2}..{:.>9}'.format(i, count_results(i))

if __name__ == '__main__':
    main()

(The memoization decorator's concept is copied from http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/ .)

Output:

8.667753234
0...........1
1...........1
2...........1
3...........2
4...........4
5...........8
6..........17
[...]
19.....688366
20....1619087

Timings for different n:

 n    time
16    0.240
17    0.592
18    1.426
19    3.559
20    8.668
21   21.402

Any n above 21 results in a memory error on my machine.

I'd be interested if anyone can make this faster by translating it into a different language.

Edit: Optimized the get_results function.  Also, using Python 2.7.5 instead of 2.7.2 made it run a bit faster.


CJam, 61 59 43 40 38 36 bytes

{{_N/eeSf.*:sW%zsS-\{_' >{;(}&+}/}*}

This is an anonymous function that expects a string and an integer on the stack.

Thanks to @jimmy23013 for golfing off 19 bytes.

Try it online in the CJam interpreter.

Idea

We can assign an order to the printable characters of the checkerboards by reading them eastwards, then southwards.

This way, the original and rotated checkerboard

            G                                  B
           . G                                B B
          G G G                              B B B
         G G . G                            B . B B
B B B B . . Y G . Y . Y Y          P P P . . . B . . G G . G
 B B B . . G . . . Y Y Y            P P P P . . . . . G G G
  B . B . . . . . Y . Y              P P . . . . . G Y . G
   B . . . . . . . . Y                P . . . . . . . G G
    . . . . . . . . .                  . . . . . . . . .
   . P . . . . . O O .                R . . . . . . . . Y
  P P . . . . . . . O O              R . R R . . . . Y Y .
 P P P . . . R . . O O .            R R R . . . O . . . Y Y
P P P P . . R . . O O O O          R . R R . . . O . Y Y Y Y
         R . R R                            O O O .
          R R R                              O O O
           R .                                O .
            R                                  O

become

G.GGGGGG.GBBBB..YG.Y.YYBBB..G...YYYB.B.....Y.YB........Y..........P.....OO.PP.......OOPPP...R..OO.PPPP..R..OOOOR.RRRRRR.R

and

BBBBBBB.BBPPP...B..GG.GPPPP.....GGGPP.....GY.GP.......GG.........R........YR.RR....YY.RRR...O...YYR.RR...O.YYYYOOO.OOOO.O

respectively.

We can find the second sequence in the first checkerboard by reading its characters northeastwards, then southeastwards.

To achieve this in code, we start by prepending n - 1 spaces to the nth row of the checkerboard (shown on the left). Then, we reverse the order of the rows (shown on the right).

            G                                                       R
            . G                                                   R .
            G G G                                               R R R
            G G . G                                           R . R R
    B B B B . . Y G . Y . Y Y                       P P P P . . R . . O O O O
      B B B . . G . . . Y Y Y                       P P P . . . R . . O O .
        B . B . . . . . Y . Y                       P P . . . . . . . O O
          B . . . . . . . . Y                       . P . . . . . O O .
            . . . . . . . . .                       . . . . . . . . .
            . P . . . . . O O .                   B . . . . . . . . Y
            P P . . . . . . . O O               B . B . . . . . Y . Y
            P P P . . . R . . O O .           B B B . . G . . . Y Y Y
            P P P P . . R . . O O O O       B B B B . . Y G . Y . Y Y
                      R . R R                       G G . G
                        R R R                       G G G
                          R .                       . G
                            R                       G

Finally, we transpose rows with columns:

            B

           BB

          BBB

         B.BB

    PPP...B..GG.G

    PPPP.....GGG

    PP.....GY.G

    P.......GG

    .........

   R........Y

  R.RR....YY.

 RRR...O...YY

R.RR...O.YYYY

OOO.

OOO

O.

O

The whitespace is all over the place, but the printable characters are in the correct order if we read them eastwards, then southwards.

All that's left to do is replacing the nth printable character of the original checkerboard by the nth printable character of the last modification.

Code

                                   e# Stack: String B, Integer A
{                               }* e# Repeat A times:
 _N/                               e#   Push a copy of B and split it at linefeeds.
    ee                             e#   Enumerate the lines of B.
      Sf.*:s                       e#   Execute S.*s for each line:
                                   e#     [4 "abc"] -> "    abc"
            W%                     e#   Reverse the order of line lines.
              z                    e#   Zip; transpose rows with columns.
               s                   e#   Flatten the arrays of strings.
                S-                 e#   Remove spaces.
                                   e#   This pushes a string L.
                  \{          }/   e#   For each character C in the unmodified B:
                    _' >           e#     Check if C is bigger than ' '.
                        {  }&      e#     If it is:
                         ;(        e#      Discard C and shift out a char from L.
                             +     e#     Append a char (C or from L) to L.
                                   e#  L is B rotated by 60 degrees. Set L := B.


130 121 bytes

-9 bytes thanks to Ørjan Johansen

type family a+b where s a+b=a+s b;z+b=b
type family a*b where s a*b=a*b+b;z*b=z
class(a#b)c|a b->c
instance a*b~c=>(a#b)c

Try it online!

This defines closed type families for addition (+) and multiplication (*). Then a type class (#) is defined that uses the (*) type family along with an equality constraint to convert from the world of type familes to the world of typeclass prolog.


Score: 387

string a(string s,int n){return string.Join(s,new string[n+1]);} (64)
int b(int n){bool p=true;for(int i=2;i<n;i++)if(n%i<1)p=false;return n<2?0:b(n-1)+(p?1:0);} (91)
object[]c(object[]l){return l.Where(x=>x!=null).ToArray();} (59)
int d(int n){return(n+1)*n/2;} (30)
char e(char c){return(char)(c<97?c+32:c-32);} (45)
bool f(string s,int n){return s.Length%n<1;} (44)
bool g(string s){return s.SequenceEqual(s.Reverse());} (54)

Total: 387


APL (66)

{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}

The left argument is the maximum iteration count and the right argument is the start number.

Explanation:

∆←⍺{...}⍕⍵: pass the left argument as a number and the right argument as a string to the function that calculates the list of numbers, and store it in ∆:

(1<⍴⍵)∧⍺>0:: if the amount of digits is more than 1 and the amount of iterations left is more than 0:

⍎¨⍵: evaluate each digit
2+/: sum each pair
⍕¨: format each number as a string
∆←,/: concatenate the strings and store in ∆
∆,(⍺-1)∇⊃∆: return ∆, followed by the result of applying this function to ∆ with one less iteration allowed

⋄⍬: if not, return the empty list

∆,⍪⍳⍴∆: pair each element of ∆ with its index in ∆
{...}/: for each pair:

(⍕⍵),': ',⍺: return a string with the index, followed by :, followed by the number

↑¯5↑: turn the list of strings into a matrix so they display on separate lines, and take the last 5 items

Test:

      5{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
1: 895
2: 1714
3: 885
4: 1613
5: 774
      50{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
6: 1411
7: 552
8: 107
9: 17
10: 8