text:
Find the Semordnilaps
Semordnilaps (also known as heteropalindromes, semi-palindromes, half-palindromes, reversgrams, mynoretehs, reversible anagrams, word reversals, or anadromes) are words which are also words when spelled backwards. A few examples are:

Ward <=> Draw
Mined <=> Denim
Parts <=> Strap

Given a positive integer N (via function argument or STDIN), return / output a list of  semordnilaps from this list of English words, that have exactly N letters. The list of words can be saved locally on your computer as a text file called: w.txt. You can also get the list from the url, but it will be included in the byte count.
Rules:

Palindromes are not semordnilaps! Therefore, the words "noon", "rotor" and "radar" should not be included in the list.
Only one of the words (in a semordnilap pair) should be included in the list. Therefore, if "dog" is in the list, "god" should not be (it doesn't matter which one is included.)
If there are no semordnilaps, the output should be an empty string, 0, FALSE or something else indicating that there were no results. The function must work even if there are no results.

This is code golf so the shortest code in bytes wins!

Leaderboard
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=42090,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Very important N = 9 example.

Shouldn't the singular be Emordnilap and the plural be Semordnilap? ;)

"Palindromes are not semordnilaps!" Wow, that sentence / bullet couldn't be more unclear, but now I see what you mean. Words which are themselves when reversed are not semordnilaps.

Pyth, 23 (18 code, 5 necessary STDIN)
J'f&qlTQ&}_TJ>_TTJ

This is a fairly straightforward solution.
J stores the list of words. Then we filter over the list of words (f          J) on the length of the word being the input (qlTQ), the reversed word being in the list (}_TJ), and the reversal of the word being greater than the word (>_TT). The last condition ensures T is not palindromic, and that only one of the pair is printed. The resultant list is printed.
The way Pyth works, the only way to open a file is to receive its name on STDIN. This is why I have counted 5 of the STDIN bytes, w.txt, in my score.
Example run:
$ pyth -c "J'f&qlTQ&}_TJ>_TTJ" <<< '6
w.txt'
['animal', 'denier', 'diaper', 'drawer', 'pupils', 'recaps', 'redraw', 'sleets', 'snoops', 'sports']

Ruby, 74 bytes
f=->n{i=IO.read('w.txt').split
p *i&[f.reverse]if f.size==n while f=i.pop}

Iterates over the list by removing elements, which avoids both palindromes and outputting both "stressed" and "desserts". Using the same variable name for the function and the iterator gets around a Ruby syntax quirk: even though f=i.pop is evaluated before f.reverse, the line won't parse unless f already means something. I could also use p.

Python, 126 125 120 bytes
N=input()
J=open("w.txt").read().split()
for c in set(J):
 if N==len(c)and c!=c[::-1]and c[::-1]in J:print c;J.remove(c)

Pretty straightforward solution.

It appears to be shorter to define k=c[::-1]. Also, couldn't you call set() only the second time? I don't think there are repeats in the file?

@FryAmTheEggman: Actually it would take 11 characters to assign k (9 for definition plus 1 for newline plus 1 for space), but I would only save 10 characters (take out [::-1] for 6 but add 1 cause I then need a space). About the set, I need J to be a set because I remove the used words from it to satisfy the no-dupe rule

switching to N==len(c)and saves a space.

@isaacg: Ah yes, ty

You're short an = - should be ==.

You can call remove on a regular list! :)

@FryAmTheEggman: Oh haha indeed! I didn't know that. thanks =)

c!=c[::-1]in J should work. (This works for the same reason 1<2<3 works)

Actually the whole condition could be if N^len(c)<(c!=c[::-1]in J): I believe. The exclusive or will only be 0 when N==len(c) and the less-than will only be true when the xor is 0 and the bool is 1.

bash 134 157 118 bytes
f () { comm -12 <(sort w.txt) <(rev w.txt|sort)|while read w; do ((${#w}==$1))&&[[ $w<$(rev<<<$w) ]]&&echo $w; done; }
This is not a serious entry, but rather in response to Brian's Bash answer. This is how I tend to think about programming this sort of thing in Bash--by using Bash itself for as little as possible, and letting the built-in tools do all the work.

You will get both the word and its reflection from comm anyway, you could just echo "$w" and don't bother with extra sort and tail. If you do that, the result should already be sorted, so the final sort can also be removed.

I don’t follow. How do I do the dedupe in your approach?

Also, I completely forgot to remove the palindromes. Fixed.

Sorry, sleep deprivation... you do indeed need to compare with the reverse to keep only one of them, but you don't have to care about palindromes and the rest of my comments are still valid. And now that you mention it, bash has a string comparison operator, so &&[[ $w > $(rev<<<$w) ]]&& echo $w still avoids sort|tail -1. With that, I think you can even drop the final sort and unique, because it removes palindromes and only outputs one of the words.

Also, a useless cat at the beginning: <(sort w.txt) is ok.

Ok, added your improvements.

CJam, 48 47 45 42 38 bytes
Since the URL has to be counted, I'm using the same URL shortener as Optimizer.
"ri.ms/§"gDcN+/{,ea~i=},_Wf%&{_W%>},N*

The § is part of extended ASCII, so each character in the code can be encoded in a single byte.
As in Optimizer's case, you'll have to use the Java interpreter and run this locally from a file, say semordnilap.cjam, and then
java -jar cjam-0.6.2.jar semordnilap.cjam <N>

so the input is given as a command-line argument.
How it works (slightly outdated):
"Prepare word list:";
"ri.ms/§"gDcN+/
"ri.ms/§"g      "Fetch list from shortened URL.";
          DcN+  "Create \r\n string.";
              / "Split input into lines.";

"Process input:";
{,ea~i=},
{      }, "Filter the list.";
 ,        "Get word length.";
  ea      "Push command-line arguments.";
    ~     "Unwrap array.";
     i    "Convert to integer.";
      =   "Check equality.";

"Find all palindromes and semordnilaps:";
_Wf%&
_     "Duplicate list.";
 Wf%  "Reverse each line.";
    & "Set intersection.";

"Remove duplicates and palindromes:";
{_W%>},N*
{    },   "Filter list.";
 _W%      "Duplicate word, reverse.";
    >     "Check lexicographic order.";
       N* "Join with newlines.";

The resulting string is automatically printed at the end of the program.

Java, 280 218 bytes
Compared to the rest of the competition, I have absolutely no idea if this is a good score.
void a(int n)throws Exception{List<String>l=Files.readAllLines(Paths.get("w.txt"));for(String s:l){String c=new StringBuilder(s).reverse()+"";if(s.length()==n&&c.compareTo(s)>0&&l.contains(c)){System.out.println(s);}}}

Expanded:
void a(int n)throws Exception{
    List<String>l=Files.readAllLines(Paths.get("w.txt"));
    for(String s:l){
        String c=new StringBuilder(s).reverse()+"";
        if(s.length()==n&&c.compareTo(s)>0&&l.contains(c)){
            System.out.println(s);
        }
    }
}

Uses compareTo() to simultaneously ignore palindromes and duplicates.

Java will always blow in a golf contest.

I've never seen Files.readAllLines(Paths.get("w.txt")) before. That's a useful trick.

Ruby, 95 bytes
f=->n{l=[]
(a=IO.read"w.txt").split.map{|w|a[w]=?.
w.size==n&&a[/^#{r=w.reverse}\s$/]&&l<<w}
l}

Explanation

Input is taken as the argument to a lambda. It expects an Integer.
Read the file into memory as a String (a).
Loop trough an Array of all words (without newlines).

Remove the word from a.
Add qualifying words to the Array l.

Return l.

An empty Array is returned when no qualifying words were found.

CJam, 68 bytes
"www.ri.ms/§"gDc-N/{_,ea~~=\_W%=!*},:Q{_W%aQ\/,({Q\a-:Q;1}{;0}?},N*

You will have to download the Java version of the compiler from here and save the above code in a file called words.cjam (can be any name). Then run the code like
java -jar cjam-0.6.2.jar <file_name> <input_number> [> <output_file_name>]

For example, for N = 8,
java -jar cjam-0.6.2.jar words.cjam 8 > out.txt

Java–that's not an acronym. Please don't spell it JAVA.

@FUZxxl this much is self-editable ..

I'm not a police officer. People have different opinions about spelling and I respect your opinion. I merely suggest you to not spell Java as if it was an acronym, I do not want to force a different spellin on you.

@FUZxxl I really don't mid :D

K, 59 bytes
{*+?{x@<x}'+(w;r)@\:&(x=#:'w)&(~w~'r)&w in r:|:'w:0:`w.txt}

Pretty straightforward. Read the list, construct the reverse list, take their intersection, filter out the palindromes, filter in the required count, sort and dedupe the pairs.

Node.js, 172 bytes
Function:
function d(n){return(require('fs').readFileSync("w.txt")+"").match(RegExp(("b"+Array(n+1).join("(.)")+"b(?=(.|s)*b"+"87654321".substr(-n)+"b)").replace(/\w/g,"\\$&"),"g"))}

Testing:
console.log(d(+process.argv[2]));
// run from command line like this:
// node main 4
// where
//   main is js file name
//   4    is length

Mathematica, 105 bytes
F[f_,n_]:=(W=StringSplit@Import@f;Select[W,StringLength@#==n&&MemberQ[W,r@#]&&Order[r@#,#]==1&&r@#!=# &])

Sometimes Import will automatically split the text into list of list of lines, or treat it as CSV or TSV. At other times, Import will read the contents of the file into a string. Import did the latter for the test data.

Node.js, CoffeeScript, 132 Bytes
f=(n)->(require('fs').readFileSync('w.txt')+'').split('\n').filter((s,i,f)->s.length==n&&f.indexOf(s.split('').reverse().join(''))>i)

Node.js, 162 Bytes
function a(n){return(require('fs').readFileSync('w.txt')+'').split('\n').filter(function(s,i,f){return s.length==n&&f.indexOf(s.split('').reverse().join(''))>i})}

Chrome Dev Tools Console, 111 Bytes
(On the download page)
f=(n=>$('pre').innerText.split('\n').filter((x,i,a)=>x.length==n&&a.indexOf(x.split('').reverse().join(''))>i))

All versions return an array of all Semordnilaps of length n.
Node.js, 162 Bytes
Prints all semordnilaps:
function a(n){(require('fs').readFileSync('w.txt')+'').split('\n').map(function(s,i,f){s.length==n&&f.indexOf(s.split('').reverse().join(''))>i&&console.log(s)})}

Julia, 101 bytes
k=split(readall("w.txt"))
for(i=k)
([]!=(l=find(x->x==reverse(i)&&x!=i,k)))&&(println(i);k[l]="")
end

This should actually work...

BASH
f() {
  w=($(cat "${1}"))
  for ((i=0;i<=${#w[@]};i++)); do
    if ((${#w[$i]} == $2)); then
      r=
      for((x=${#w[$i]}-1;x>=0;x--)); do
        r="$r${w[$i]:$x:1}";
      done
      if [[ ${w[$i]} != ${r} ]] && grep -qw $r "${1}"; then
        echo "${w[$i]}, ${r}"
      fi
      unset w[$i]
    fi
  done
}

tests...
f /usr/share/dict/words 5

debut, tubed
decaf, faced
decal, laced
deeps, speed
denim, mined
devil, lived
draws, sward
faced, decaf
keels, sleek
knits, stink
laced, decal
lager, regal
leper, repel
lever, revel
lived, devil
loops, spool
loots, stool
mined, denim
parts, strap
peels, sleep
pools, sloop
ports, strop
rebut, tuber
regal, lager
remit, timer
repel, leper
revel, lever
sleek, keels
sleep, peels
sloop, pools
smart, trams
snaps, spans
snips, spins
spans, snaps
speed, deeps
spins, snips
spool, loops
spots, stops
sprat, tarps
stink, knits
stool, loots
stops, spots
strap, parts
straw, warts
strop, ports
sward, draws
tarps, sprat
timer, remit
trams, smart

I guess this isn't very golfed..? This would be a nice answer on Stack Overflow (if it had some comments and explanations).

Agreed, this was my first iteration at solving this in bash. I tired to make it as readable as possible. but as far as golf goes. it's more like I shot a 9 on a par 3 : - )


text:
Mutual Negative Quines
This was inspired by Print a Negative of your Code and Golf a mutual quine.

Consider a rectangle of characters, that meet the following restrictions:

Consists solely of printable ASCII characters
Dimensions both greater than 1
Each row and each column contains at least one space.
Each row and each column contains at least one non-space character.

For example, the following is a valid 6x4 rectangle:
%n 2e
1  g 3
 &* __
 3

A negative for this rectangle is defined to be a rectangle of equal dimensions, with all spaces replaced by non-space characters, and all non-space characters replaced by spaces. A negative of the above rectangle could be:
  f  ^
 33 >
9  $
^ }|Q'

Any non-space printable ASCII character may be used to replace a space.
Task
Your task is to write a program with rectangular source code, that outputs a valid negative to itself. The negative outputted must also be a valid program, in the same language as the original, and it must output the source of the original.
No trailing whitespace may be added or removed, except for a single trailing newline at the end of either output, which is optional.
Neither program is permitted to read the source code of either; nor may REPL environments be assumed.
Scoring
Your score is the product of the dimensions of your code (i.e. if your source code is in a 12 by 25 rectangle, your score is 12*15=180). Additionally, for each character used in a comment, your score increases by 2 (If you use /* .. */ once in your code, and your code is in a 10 by 10 rectangle, your score would be 10*10+8*2=116).
The lowest score wins.
If there is a tie, the submission with the least number of spaces in the program (either the original or the negative, whichever has fewer spaces) wins.
If there still remains a tie, the earlier answer shall win.
There is a bonus of -52%, if combining the original and the negative together produces a normal quine. For example:
Original   Negative   Combined
 A A       B B        BABA
A A         B B       ABAB

@Optimizer That's the reason I didn't make the bonus mandatory.

I am talking about just the negative mutual quine part ;)

@MartinBüttner Ah, my bad. I was thinking in weird terms.

Can anyone do this in c? +1 to whoever will first!

is whitespace (the lang) allowed

CJam, (51 49 47 46 45 42 x 2) * 48% = 40.32
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
                                         R

Running the above code gives this output:
                                         R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~

running which, prints back the original source.
The source and the output are simply swapped lines.
Now comes the magic.
Overlapping the source and the output results into the following code:
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R

which is a perfect quine!
Try them online here

How it works
All the printing logic is in the first line itself which handles all three cases explained later.
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
{                                     }_~   "Copy this code block and execute the copy";
 ]                                          "Wrap everything before it in array";
  )                                         "Pop the last element out of it";
   "_~"+                                    "Append string '_~' to the copied code block";
        S41*                                "Create a string of 41 spaces";
            'R+                             "Append character R to it";
               @,                           "Rotate the array to top and get its length";
                 [{   }{   }{     }]=~      "Get the corresponding element from this"
                                            "array and execute it";

The array in the last line above is the array which has code blocks corresponding to all three cases.
Case 1
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
                                         R

In this case, the length of remaining stack was 0 as when the block was executed, it only had the copy of the block itself, which was initially popped out in the third step above. So we take the index 0 out of the last array and execute it:
 {N@S}          "Note that at this point, the stack is something like:"
                "[[<code block that was copied> '_ '~ ] <41 spaces and R string>]";
  N             "Add newline to stack";
   @            "Rotate the code block to top of stack";
    S           "Put a trailing space which negates the original R";

In this case, the second line is a no-op as far as printing the output is concerned.
Case 2
                                         R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~

In this case, the stack already contained an empty string, so when the copied code block was executed, it had 2 elements - an empty string and the code block itself. So we take the index 1 out of the last array and execute it:
{SN@}            "Note at this point, the stack is same as in case 1";
 SN              "Push space and newline to stack";
   @             "Rotate last three elements to bring the 41 spaces and R string to top";

Case 3
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R

In this case, the stack has 6 elements. So after popping the last code block, remaining array length is 5. We take the index 5 out of the array and execute it. (Note that in a array of 3 elements, index 5 is index 5%3 = 2)
{W=N]_}          "Note at this point, the stack is same as in case 1";
 W=              "Take the last character out of the 41 spaces and R string, i.e. R";
   N]            "Add a new line to stack and wrap the stack in an array";
     _           "Copy the array to get back the source of Case 3 itself";

Python, 97x2 + 2 = 196
Not a great solution to start off, but at least it works (I think).
c='o=1-%d;print("%%97s\\n%%97s"%%("#","c=%%r;exec(c%%%%%%d)\\40"%%(c,o),"#")[o:][:2])';exec(c%1)
                                                                                #

Output:
                                                                                #
c='o=1-%d;print("%%97s\\n%%97s"%%("#","c=%%r;exec(c%%%%%%d)\\40"%%(c,o),"#")[o:][:2])';exec(c%0)

+1 for the only submission so far to use a real language

It doesn't seem to be too far off from the bonus either.

CJam, (58 56 54 48 46 x 2) * 48% = 44.16
{`"_~"+{_,94\m2/S*a_+\*
                       N/23f/Wf%N*}_`'"#)!*}_~

which prints
                       {`"_~"+{_,94\m2/S*a_+\*
N/23f/Wf%N*}_`'"#)!*}_~

The non-space characters in each line remain the same between the two mutual quines.
But now the really sweet part:
{`"_~"+{_,94\m2/S*a_+\*{`"_~"+{_,94\m2/S*a_+\*
N/23f/Wf%N*}_`'"#)!*}_~N/23f/Wf%N*}_`'"#)!*}_~

is a quine! :)
Test it here.
How it works
I recommend you read the explanation on my other submission first, as it explains the basics of quining in CJam in general.
This one is a bit trickier. For the mutual quine, as in the other case, I modify the string representation of the block by adding spaces before or after each line, and swapping a 0 with a 2, so that the resulting program puts the spaces at the opposite end.
Note that the spaces don't affect the mutual quines at all. In the first one, they are in a block, which isn't really used, and in the second they are around the entire code.
To obtain a regular quine when combining both, we need to find a way to avoid doing all that modification. Notice that the structure of the whitespace and code means that by combining both, we insert the entirety of one quine into the other. So if we put the entire modification code in a block, we can run that block depending on its actual contents.
So now I've got this block... for the mutual quines, it only contains the code I actually want to run. For the combined quine, it also contains the entire quine again, in a random position, which doesn't make any sense... but since it's a block, it's not run automatically. So we can determine whether to modify the string based on the contents of that block. That's what _`'"#)! is for. It duplicates the block, converts it to a string, searches for the character " (which, in the mutual quines, only appears outside the block) - the search returns -1 if the character isn't found and a positive integer otherwise -, increments the result and negates it logically. So if a " was found this yields 0 otherwise it yields 1. Now we just do *, which executes the block once, if the result was 1 and not at all otherwise.
Finally, this is how the modifying code works:
_,94\m2/S*a_+\*N/23f/Wf%N*
_,                         "Duplicate the quine string and get its length.";
  94\m                     "Subtract from 94.";
      2/                   "Divide by two.";
        S*                 "Create a string with that many spaces. This will be
                            an empty string for the first mutual quine, and contain
                            23 spaces for the second mutual quine.";
          a_+              "Create an array that contains this string twice.";
             \*            "Join the two copies together with the quine string.";
               N/          "Split into lines.";
                 23f/      "Split each line into halves (23 bytes each).";
                     Wf%   "Reverse the two halves of each line.";
                        N* "Join with a newline.";

Claiming the Bounty, (12 x 10) * 48% = 57.6
Turns out that this code can be split over more lines very easily with some modifications. We add 2 characters, to get 48 in a row, which we can then conveniently divide by 8, so that we have 8 lines with 6 characters of code and 6 spaces. To do that we also need to change a few numbers, and to rearrange an operator or two, so they aren't split over both lines. That gives us a working version with size 12 x 8... one off the requirement. So we just add two lines that don't do anything (push a 1, pop a 1, push a 1, pop a 1...), so get to 12 x 10:
{`"_~"
      +{129X
$,m2/S
      *a_+\*
N/6f/1
      ;1;1;1
;1;1;1
      ;Wf%N*
}_`'"#
      )!*}_~

As the previous one this produces
      {`"_~"
+{129X
      $,m2/S
*a_+\*
      N/6f/1
;1;1;1
      ;1;1;1
;Wf%N*
      }_`'"#
)!*}_~

(Side note: there is no need to keep alternating left and right on the intermediate lines, only the position of the first and last line are important. Left and right can be chosen arbitrarily for all other lines.)
And through pure coincidence, the full quine also still works:
{`"_~"{`"_~"
+{129X+{129X
$,m2/S$,m2/S
*a_+\**a_+\*
N/6f/1N/6f/1
;1;1;1;1;1;1
;1;1;1;1;1;1
;Wf%N*;Wf%N*
}_`'"#}_`'"#
)!*}_~)!*}_~

(I say coincidence, because the part that takes care of not executing the inner code now gets weirdly interspersed with the other quine, but it still happens to work out fine.)
That being said, I could have just added 44 lines of 1; to my original submission to fulfil the bounty requirement, but 12 x 10 looks a lot neater. ;)
Edit: Haha, when I said "pure coincidence" I couldn't have been more spot on. I looked into how the final quine now actually works, and it's absolutely ridiculous. There are three nested blocks (4 actually, but the innermost is irrelevant). The only important part of the innermost of those 3 blocks is that it contains a " (and not the one that it did in the original submission, but the very '" that is used at the end to check for this same character). So the basic structure of the quine is:
{`"_~"{`"_~"+{___'"___}_`'"#)!*}_~)!*}_~

Let's dissect that:
{`"_~"                               }_~ "The standard CJam quine.";
      {`"_~"+                  }_~       "Another CJam quine. Provided it doesn't do
                                          anything in the rest of that block, this
                                          will leave this inner block as a string on
                                          the stack.";
                                  )      "Slice the last character off the string.";
                                   !     "Negate... this yields 0.";
                                    *    "Repeat the string zero times.";

So this does indeed do some funny magic, but because the inner block leaves a single string on the stack, )!* happens to turn that into an empty string. The only condition is that the stuff in the inner block after + doesn't do anything else to the stack, so let's look at that:
             {___'"___}                  "Push a block which happens to contain
                                          quotes.";
                       _`'"#)!*          "This is from the original code and just
                                          removes the block if it does contain
                                          quotes.";

TLDR; upvote ;)

Shouldn't it be Y/2 in the combined quine?

"And through pure coincidence" nah ;)

@Timtech See my edit. Pure coincidence was not an understatement. ^^

CJam, 42 37 33 x 2 = 66
{`As_W%er"_~"+S 33*F'Lt1{\}*N\}_~
               L

which prints
               L
{`As_W%er"_~"+S 33*F'Lt0{\}*N\}_~

(The lines are swapped, and a 1 turns into a 0.)
Test it here.
How it works
First, you should understand the basic CJam quine:
{"_~"}_~

The braces simply define a block of code, like a function, that isn't immediately executed. If an unexecuted block remains on the stack, it's source code (including braces) is printed. _ duplicates the block, and ~ executes the second copy. The block itself simply pushes the string containing _~. So this code, leaves the stack in the following state:
Stack: [{"_~"} "_~"]

The block and the string are simply printed back-to-back at the end of the program, which makes this a quine.
The beauty of this is that we can do whatever we want in the block, and it remains a quine, because each piece of code will automatically be printed in the block contents. We can also modify the block, by obtaining it's string representation with ` (which is just a string of the block with braces).
Now let's look at this solution. Notice that either part of the mutual quine contains of the quine-like block with _~, and an L. The L pushes an empty string onto the stack, which doesn't contribute to the output. So here is what the block does:
`                             "Convert block to its string representation.";
 As                           "Push 10 and convert to string.";
   _W%                        "Duplicate and reverse, to get another string 01.";
      er                      "Swap 0s and 1s in the block string.";
        "_~"+                 "Append _~.";
             S 33*            "Push a string with 33 spaces.";
                  F'Lt        "Set the character at index 15 to L.";
                      1{ }*   "Repeat this block once.";
                        \     "Swap the code string and the space string.";
                           N\ "Push a newline and move it between the two lines.";

So this will do the quine part, but exchange a 1 for a 0, and it will also prepend another line with an L, where the code above has a space. The catch is that the order of those two lines is determined by the swapping inside { }*. And because the outer part of the mutual quine has the 0 in front of it replaced by a 1, it never executes this swap, and hence produces the original order again.

CJam, 27 × 2 = 54
{ ` " _ ~ " + N - ) 2 * ' '
 > @ t s G B + / N * } _ ~

Output:
 { ` " _ ~ " + N - ) 2 * '
' > @ t s G B + / N * } _ ~

'A'B> compares the characters A and B. ' '\n > returns 1 because 32>10 and ' \n' > returns 0 because the two spaces are equal.

CJam, 30 29 x 2 = 58
{"_~"SN]_,4=S28*'R+\{N@}*}_~
                            R

Outputs:
                            R
{"_~"SN]_,4=S28*'R+\{N@}*}_~

which outputs the original source.
This is based on the same principal as my other solution.
Try it online here

Klein, 2*96 = 192
 \                                                                                1
< (!.:!.?!|84*:999*+2+$<::::::]]]]]]]77*55+<)!.:!.?!>(84*2+@*77]]]]]]]::::::<$*77:*48+55+2*48 <"

Try it online!
< 84*2+55+84*:77*$<::::::]]]]]]]77*@+2*48(>!?.!:.!)<+55*77]]]]]]]::::::<$+2+*999:*48|!?.!:.!( <"
 1                                                                                1

Try it online!

Do you think this is possible in Lost?

@emanresuA I think it is.  It would be pretty hard though.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Compute the shortest decimal representation of a IEEE 754 double-precision binary floating-point number
Format
The format is a 64 bit value x representing a IEEE-754 double-precision binary floating-point number (a.k.a "a double"). x is assumed to represent a real number (not a NaN or Infinity).
Goal
The goal is to print/output the shortest string containing a decimal representation for which x is the closest IEEE 754 representation. Scientific notation is allowed. You can choose whether or not to allow a missing 0 in front of the ".".
x = 0x4000CCCCCCCCCCCD could be represented as "2.10000000000000008881784197001" but also as "2.1", which is much shorter. x = 0x3DDB7CDFD9D7BDBB can be represented as "1e-10" which is much shorter than alternative representation "1.0000000000000000364321973155E-10"
Rules
In addition to being correct, the program must run in a reasonable amount of time on a modern CPU, ruling out some forms of exhaustive search.
This being code-golf entries should be judged by concision, but voters should feel free to attribute points based on a discretionary judgment of elegance, and efficiency.
A few test cases
In these test cases, I represent the input as an hexadecimal number to make it clear that a IEEE 754 double 64 is passed. You can pass it as a double if the language supports it, or as a 64 bit integer, at your convenience.
f(0x4000CCCCCCCCCCCD) == "2.1"
f(0x3DDB7CDFD9D7BDBB) == "1e-10"
f(0x40934A456D5CFAAD) == "1234.5678" // N.B. not 1.2345678e3
f(0x3FEFFFFFFAA19C47) == "0.99999999"
f(0xC088A8CF13CEE9DD) == "-789.101112"`

If by "C will parse" you're talking about C compilers, the standard says that "the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner." If you're talking about scanf there is still implementation-specific behaviour with regards to rounding.  To make this question answerable, I think it needs to be rewritten to talk not about C's parsing but about the string-to-double conversion of the language used in the answer.

The cleanest way of expressing it is probably to require that the answer be a function (whose length is counted for the score) and also include a test framework (length not counted) which demonstrates that the string returned by the function round-trips to the original value.

OK I'll edit in a few hours with a few test cases.
The requirement isn't compiler specific, it's a standard. But I'll replace with what the standard actually says...

Can I submit an entry for Python 3.1 with f=str? Because Python will always choose the shortest representation.

I suppose that technically counts, though I'd prefer to see an implementation of Dragon4

@KennyTM, no.

@PeterTaylor: All 3 current answers are effectively just f=str though.

@ArthurB: Also may I suggest adding a test case for f(0x400921fb54442d18) == "3.141592653589793"?

I don't think this challenge is worthwhile unless solutions that are effectively calls to printf are disqualified.

Pretty much. Very efficient solutions require long pieces of code, but there are some simple ones which can be implemented concisely.

C - 47 45 characters
Counting just the function f, and not including #includes and main.
In C, the %g fprintf specifier will always choose the shortest format. Add a precision specifier equal to the usual maximum precision of double and a bit of casting hocus-pocus to coerce int64 to double and Bob's your uncle.
#include <assert.h>
#include <stdint.h>
#include <stdio.h>

// The following line is what I'm counting...
f(int64_t u){printf("%.14g\n",*(double*)&u);}

int main()
{
    assert(sizeof(int64_t) == sizeof(double));

    f(0x4000CCCCCCCCCCCD);
    f(0x3DDB7CDFD9D7BDBB);
    f(0x40934A456D5CFAAD);
    f(0x3FEFFFFFFAA19C47);
    f(0xC088A8CF13CEE9DD);

    return 0;
}

Output is as per specs:
2.1
1e-10
1234.5678
0.99999999
-789.101112

Summary: C rocks!

You can save a character by using uint64_t in place of long long, or even 2 characters if you use int64_t.

@PaulR - Thank you, will try that out!

You may pass the test set, but not the general requirement. %g picks the shortest of %f or %e, but %f will not always reproduce all the digits necessary to represent the number.

@ArthurB - %14g will propagate the 14 to %f or %e. /YR

Which doesn't help you particularly.

Maximum (round-tripping) precision of double is 15 decimal places, and to print unambiguous representation of every given binary number you need up to 17.

Common Lisp - 138 bytes
 (ql:quickload'(ieee-floats cl-ppcre))(lambda(x)(#1=ppcre:regex-replace"e0$"(#1#"\\.?d"(format()"~a"(ieee-floats:decode-float64 x))"e")""))

(138 = 101 for the actual function + 37 for quickload'ing libraries)
Ungolfed
The default representation of floating-points in CL is already quite close to the requested output. However, there are some discrepancies. For example, double-precisions numbers are written with a d exponent character (e.g., 2.10d0).
That is why I modify the output of the formatted string with regexes:
(ql:quickload '(ieee-floats cl-ppcre))
(lambda (x)
  (cl-ppcre:regex-replace  ; remove "e0" at end of string
     "e0$"
     (cl-ppcre:regex-replace ; change ".d" and "d" to "e"
       "\\.?d"
       (format nil "~a" (ieee-floats:decode-float64 x))
       "e")
     ""))

Example
;; NB: * is set by the REPL to the last returned value.
;; Here, we store the previously defined lambda:
(defparameter *fun* *)

;; Test cases
(defparameter *sample*
  '(#x4000CCCCCCCCCCCD
    #x3DDB7CDFD9D7BDBB
    #x40934A456D5CFAAD
    #x3FEFFFFFFAA19C47
    #xC088A8CF13CEE9DD))

;; Default representation
(mapcar #'ieee-floats:decode-float64 *sample*)
=> (2.1d0 1.d-10 1234.5678d0 0.99999999d0 -789.101112d0)

;; Custom conversion
(mapcar *fun* *sample*)
=> ("2.1" "1e-10" "1234.5678" "0.99999999" "-789.101112")

Round-trip
Here, we convert the printed representations back to IEEE-754 doubles.
;; read values as double-precision numbers
(let ((*read-default-float-format* 'double-float))
  (mapcar #'read-from-string *))
=> (2.1 1.e-10 1234.5678 0.99999999 -789.101112)

;; Encode
(mapcar #'ieee-floats:encode-float64 *)
=> (4611911198408756429 4457293557087583675 4653144502051863213 4607182418709945415 13873524259458836957)

;; Check
(equal * *sample*)
=> T

Julia, 20 characters
r(h)=hex2num(hex(h))

Function to test the results for correctness:
function decrep()
    tests=[0x4000CCCCCCCCCCCD 0x3DDB7CDFD9D7BDBB 0x40934A456D5CFAAD 0x3FEFFFFFFAA19C47 0xC088A8CF13CEE9DD]
    results=[2.1 1e-10 1234.5678 0.99999999 -789.101112]

    for i=1:length(tests)
        println("input   : $(hex(tests[i]))")
        println("result  : $(r(tests[i]))")
        println("expected: $(results[i])")
        println("$(r(tests[i]) == results[i])")
    end
end

Executing the test function:
julia> decrep()
input   : 4000cccccccccccd
result  : 2.1
expected: 2.1
true
input   : 3ddb7cdfd9d7bdbb
result  : 1.0e-10
expected: 1.0e-10
true
input   : 40934a456d5cfaad
result  : 1234.5678
expected: 1234.5678
true
input   : 3feffffffaa19c47
result  : 0.99999999
expected: 0.99999999
true
input   : c088a8cf13cee9dd
result  : -789.101112
expected: -789.101112
true

If the output absolutely has to be a string, then the solution would be:
s(h)=string(hex2num(hex(h)))

with 28 characters.
julia> h=0x4000cccccccccccd
0x4000cccccccccccd

julia> s(h)=string(hex2num(hex(h)))
s (generic function with 1 method)

julia> s(h)
"2.1"

Summary: Julia rocks, too ;)

authors: علیرضا یعقوبی

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Create icy avatar images for the winter season

It's winter, and the time of year has come for it to start getting cold (and for strange colorful headcloths to start appearing... soon). Let's write some code to make avatar pictures and other images frozen over, to fit the theme!
Input
The input to submissions to this challenge should be an image (the image to make frozen) and a number (the threshold, which will be explained later).
You may input the image in any way your language supports them (a file path or URL as an argument, taking it from the clipboard, dragging and dropping an image, etc.) and in any format listed here that expresses colors in RGB (you can support / require RGBA instead if you want, but this is not a requirement).
You can input the number in any way you would like as well (command line argument, STDIN, input dialog, etc.), with the exception of hardcoding it into your program (ex. n=10). If you use a file path / URL for the image, it must be input in this manner as well.
Output
The program must process the image according to the description below and then output it in any way you would like (to a file, showing it on screen, putting it on the clipboard, etc.).
Description
Submissions should process the image with the following three steps. n refers to the number that your program received as input along with the image.

Apply a blur of radius n to the input image by replacing each pixel's R, G, and B values with the average R, G, and B values of all pixels within a Manhattan distance of n pixels, ignoring all out-of-bounds coordinates. (I.e. all pixels where the sum of the difference in X and the difference in Y is less than or equal to n.)
(note: I used a Gaussian blur for the images above because there was a convenient built-in function for it, so your images might look a little different.)
Set each pixel to a random pixel within a distance of n/2 pixels ("distance" is defined the same way as in the previous step).
This should be done by looping through the image and setting each pixel to a random pixel in this range, so some pixels might disappear entirely and some might be duplicated.
All changes must apply at the same time. In other words, use the old values of the pixels (after step 1 but before this step), not the new values after setting them to a random pixel.
Multiply the "blue" RGB value of each pixel by 1.5, capping it at 255 (or whatever the maximum value for a band of pixels is) and rounding down.

Rules

You may use image libraries / image processing-related functions built into your language; however, you may not use any functions that perform one of the three major tasks mentioned in the description. For example, you can't use a blur function, but a getPixel function is fine.
This is code-golf, so the shortest code in bytes wins!

Step 1 has two points which need clarifying. Firstly, which metric? You say Manhattan (L-1) and describe L-infinity. Secondly, how should image boundaries be handled: no wrapping, reducing the denominator to average only over pixels inside the boundary? Step 2 has one point which needs clarifying: is the sampling from a copy of the image after step 1, or can changes from early in step 2 propagate? For step 3, capping at 255 is only appropriate in a 24-bit colour model, and the question doesn't anywhere require that.

@PeterTaylor I've tried to clarify all of those points, except for the first one. I don't really understand what you're saying; dx <= n && dy <= n is an accurate representation of Manhattan distance, is it not?

No, Manhattan distance is |dx| + |dy| <= n.

@PeterTaylor Alright, thanks, I've fixed that as well.

Is 2D convolution with a matrix considered "image processing-related"?

@COTO It doesn't matter, since it doesn't perform one of the three major tasks mentioned in the description. (See the first bullet point of the "rules" section.)

You can use it to perform the blur in step one. Just make the kernel a diamond of 1's.

@COTO It still doesn't perform that task; it only helps in doing so.

is n/2 rounded or floored?

@TheBestOne People in Florida did too, but it's not cold here. They're just Floridians.

@stokastic I think "within a distance of n/2 pixels" is a perfectly valid statement without rounding/flooring n/2 at all (so effectively, "floored", I think).

@stokastic Just to verify, yes, Martin's interpretation is correct.

Python 2 - 326 339 358
Takes input from the user. File first, then n.
from PIL.Image import*;from random import*
a,N=input()
i=open(a)
d=list(i.getdata())
x,y=i.size
R=range(x*y)
m=lambda p,n,r:[p[i]for i in R if abs(n%x-i%x)+abs(n/y-i/y)<=r]
k=d[:]
for p in R:t=map(lambda x:sum(x)/len(x),zip(*m(k,p,N)));d[p]=t[0],t[1],min(255,t[2]*3/2)
i.putdata([choice(m(d,p,N/2))for p in R])
i.save('t.png')

This could probably be golfed much more :P Thanks to @SP3000 for golf ideas!
Sample input:
(Windows)
"C:/Silly/Optimizer/Trix/Are/For/Kids.png",7

Edit: Bug fixed where blue was being propagated (Martin with n=20 is no longer a river ;_; )
Martin with n=2:

Martin with n=10:

Martin with n=20:

Python 2 - 617 Bytes
EDIT: golfed some, looks like FryAmTheEggMan has me beat though :)
from PIL import Image
import sys,random
j,i,n=sys.argv
n=int(n)
i=Image.open(i)
w,h=i.size
o=Image.new("RGB",(w,h))
D=list(i.getdata())
D=[D[i*w:i*w+w] for i in range(h)]
O=[]
d=n/2
z=range(-n,n+1)
M=lambda n:[[x,y] for x in z for y in z if abs(x)+abs(y)<=n]
m=M(n)
L=w*h
for i in range(L):
 y,x=i/w,i%w;c=r=g=b=0
 for q in m:
  try:C=D[y+q[1]][x+q[0]];r+=C[0];g+=C[1];b+=C[2];c+=1
  except:pass
 r/=c;g/=c;b/=c
 O.append((r,g,min(b*3/2,255)))
R=lambda:random.randint(-d,d)
for i in range(L):
 x,y=i%w,i/w;u=R();v=R()
 while not(0<x+u<w and 0<y+v<h):u=R();v=R()
 O[y*w+x]=O[(y+v)*w+(x+u)]
o.putdata(O)
o.save("b.png")

Java - 1009 bytes
eh, I thought I could do better than this...
import java.awt.*;import java.io.*;import java.util.*;import javax.imageio.*;class r{public static void main(String[]v)throws Exception{java.awt.image.BufferedImage i=ImageIO.read(new File("y.png"));int n=Byte.valueOf(v[0]),w=i.getWidth(),h=i.getHeight();for(int z=0;z<w*h;z++){int x=z/h,y=z%h,r=0,g=0,b=0,c=0,x2,y2,k;for(x2=x-n;x2<=x+n;x2++){for(y2=y-n;y2<=y+n;y2++){if(Math.abs(x2-x)+Math.abs(y2-y)<=n&&x2>=0&&x2<w&&y2>=0&&y2<h){k=i.getRGB(x2,y2); r+=(k>>16)&0xFF;g+=(k>>8)&0xFF;b+=k&0xFF;c++;}}}i.setRGB(x,y,new Color(r/c,g/c,b/c).getRGB());}int[]t=new int[w*h];for(int z=0;z<h*w;z++){int x=z/h,y=z%h,x2,y2;ArrayList<Integer>e=new ArrayList<>();for(x2=x-n;x2<=x+n;x2++){for(y2=y-n;y2<=y+n;y2++){if(Math.abs(x2-x)+Math.abs(y2-y)<=n/2&&x2>=0&&y2>=0&&x2<w&&y2<h)e.add(i.getRGB(x2,y2));}}int p=e.get((int)(Math.random()*e.size())),b=(int)((p&0xFF)*1.5);t[x*h+y]=new Color((p>>16)&0xFF,(p>>8)&0xFF,b>255?255:b).getRGB();}for(int d=0;d<w*h;d++){i.setRGB(d/h,d%h,t[d]);}ImageIO.write(i,"PNG",new File("n.png"));}}

import java.awt.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
class IceBlur{
    public static void main(String[]v)throws Exception{
        java.awt.image.BufferedImage i=ImageIO.read(new File("blah.png"));
        int n=Byte.valueOf(v[0]),w=i.getWidth(),h=i.getHeight();
        for(int z=0;z<w*h;z++){
            int x=z/h,y=z%h,r=0,g=0,b=0,c=0,x2,y2,k;
            for(x2=x-n;x2<=x+n;x2++){
                for(y2=y-n;y2<=y+n;y2++){
                    if(Math.abs(x2-x)+Math.abs(y2-y)<=n&&x2>=0&&x2<w&&y2>=0&&y2<h){
                        k=i.getRGB(x2,y2);
                        r+=(k>>16)&0xFF;
                        g+=(k>>8)&0xFF;
                        b+=k&0xFF;
                        c++;}}}i.setRGB(x,y,new Color(r/c,g/c,b/c).getRGB());}
        int[]t=new int[w*h];
        for(int z=0;z<h*w;z++){
            int x=z/h,y=z%h,x2,y2;
            ArrayList<Integer>e=new ArrayList<>();
            for(x2=x-n;x2<=x+n;x2++){
                for(y2=y-n;y2<=y+n;y2++){
                    if(Math.abs(x2-x)+Math.abs(y2-y)<=n/2&&x2>=0&&y2>=0&&x2<w&&y2<h)e.add(i.getRGB(x2, y2));}}
            int p=e.get((int)(Math.random()*e.size())),b=(int)((p&0xFF)*1.5);
            t[x*h+y]=new Color((p>>16)&0xFF,(p>>8)&0xFF,b>255?255:b).getRGB();}
        for(int d=0;d<w*h;d++){i.setRGB(d/h, d%h, t[d]);}
        ImageIO.write(i,"PNG",new File("blah2.png"));}}

Martin with n=5:

n=20:

Me with 10:

It's been a while since I java'd anything, but couldn't you do k&0xFF00? Furthermore, couldn't you use 255 in place of 0xFF?

C, 429 (391 + 38 for define flags)
i,R,G,B,q;char*c,t[99];main(r,a,b,k,z,p){scanf("%*[^ ]%d%*6s%d%[^N]%*[^R]R\n",&a,&b,t);int j=a*b,d[j],e[j];F(c=d;c<d+j;*c++=getchar());F(;i<j;e[i++]=X<<24|B/q<<16|G/q<<8|R/q,R=G=B=q=0)F(k=0;k<j;)p=d[k++],D<r&&(++q,R+=p&X,G+=p>>8&X,B+=p>>16&X);F(i=!printf("P7\nWIDTH %d\nHEIGHT %d%sNDHDR\n",a,b,t);i<j;d[i++]=e[k])F(;k=rand()%j,D>r/2;);F(c=d;q<j*4;i=(q%4-2?2:3)*c[q]/2,putchar(i>X?X:i),++q);}

Input format: pam file with no comments or extra whitespace in header, contents passed via STDIN.
n arguments are required (they can be anything).
Output format: pam file in STDOUT.
To compile:
gcc -DX=255 -DF=for "-DD=z=abs(k-i),z/b+z%a" -Wl,--stack,33554432 -funsigned-char icyavatars.c -o icyavatars

-Wl,--stack,33554432 increases the stack size; this may be changed or removed, depending on the size of the picture being processed (the program requires a stack size greater than twice the number of pixels times 4).
-funsigned-char has gcc use unsigned char instead of signed char for char. The C standards allows for either of these options, and this option is only needed here because gcc uses signed char by default.
To run (n=5):
./icyavatars random argument here fourth fifth < image.pam > output.pam

Note: If compiling on Windows, stdio.h, fcntl.h and io.h must be included, and the following code added to the start of main() in order for the program to read/write to STDIN/STDOUT as binary, not text, streams (this is irrelevant on Linux, but Windows uses \r\n instead of \n for text streams).

setmode(fileno(stdin), _O_BINARY);
setmode(fileno(stdout), _O_BINARY);

Commented version
int i,R,G,B,q;
char *c,t[99];
main(r,a,b,k,z,p){
    // read all of header
    // save a large chunk to t, save width to a, save height to b
    scanf("%*[^ ]%d%*6s%d%[^N]%*[^R]R\n", &a, &b, t);
    // create arrays for holding the pixels
    int j = a * b, d[j], e[j];
    // each pixel is 4 bytes, so we just read byte by byte to the int arrays
    for(c = d; c < d + j; ++c)
        *c=getchar();

    // calculating average rgb
    for(i = 0; i < j; ++i){
        // check every pixel; add r/g/b values to R/G/B if manhattan distance < r-1
        for(k = 0; k < j; ++k){
            // pixel being checked
            p = d[k];
            // manhattan distance
            z = abs(k - i)/b + abs(k - i)%a;
            if(z < r){
                // extract components and add
                ++q;
                R += p & 255;
                G += p >> 8 & 255;
                B += p >> 16 & 255;
            }
        }
        // set pixel in e (not d) to average RGB and 255 alpha
        e[i]= 255<<24 | B/q<<16 | G/q<<8 | R/q;
        // clear temporary variables
        R = G = B = q = 0;
    }

    // print header
    printf("P7\nWIDTH %d\nHEIGHT %d%sNDHDR\n",a,b,t);
    // choose random pixels
    for(i = 0; i < j; ++i){
        // loop until randomly generated integer represents a pixel that is close enough
        do{
            k = rand() % j;
            // manhattan distance
            z = abs(k - i)/b + abs(k - i)%a;
        }while(z > r/2);
        // set d to the new pixel value
        d[i] = e[k];
    }
    // apply blue scaling and output
    for(c = d, q = 0; q < j * 4; ++q){
        // 3/2 if blue component, 1 otherwise
        i = (q % 4 - 2 ? 2 : 3)*c[q]/2;
        // cap components at 255
        putchar(i > 255 ? 255 : i);
    }
}

Martin with n=10:

Martin with n=20:

Martin with n=100:

R, 440 chars
f=function(n,p){a=png::readPNG(p);b=a;N=nrow(a);M=ncol(a);r=row(a[,,1]);c=col(a[,,1]);for(i in 1:N)for(j in 1:M)b[i,j,]=apply(a,3,function(x)mean(x[abs(r-i)+abs(c-j)<=n]));for(i in 1:N)for(j in 1:M){g=which(abs(r-i)+abs(c-j)<=n/2,arr.ind=T);o=sample(1:nrow(g),1);b[i,j,]=b[g[o,1],g[o,2],]};b[,,3]=b[,,3]*1.5;b[b>1]=1;png(w=M,h=N);par(mar=rep(0,4));plot(0,t="n",xli=c(1,M),yli=c(1,N),xaxs="i",yaxs="i",ax=F);rasterImage(b,1,1,M,N);dev.off()}

With line breaks for legibility:
f=function(n,p){
    a=png::readPNG(p) #use readPNG from package png
    b=a
    N=nrow(a)
    M=ncol(a)
    r=row(a[,,1])
    c=col(a[,,1])
    for(i in 1:N){ #braces can be deleted if all is contained in one line
        for(j in 1:M){
            b[i,j,]=apply(a,3,function(x)mean(x[abs(r-i)+abs(c-j)<=n]))
            }
        }
    for(i in 1:N){ #i'm sure this loop could be shortened
        for(j in 1:M){
            g=which(abs(r-i)+abs(c-j)<=n/2,arr.ind=T)
            o=sample(1:nrow(g),1)
            b[i,j,]=b[g[o,1],g[o,2],]
            }
        }
    b[,,3]=b[,,3]*1.5 #readPNG gives RGB values on a [0,1] range, so no need to round
    b[b>1]=1
    png(w=M,h=N)
    par(mar=rep(0,4))
    plot(0,t="n",xli=c(1,M),yli=c(1,N),xaxs="i",yaxs="i",ax=F)
    rasterImage(b,1,1,M,N)
    dev.off()
    }

Sample input: f(2,"avatar.png")
Results with n=2

... with n=10

... with n=20

authors: Николай Булашев


text:
Convert numbers to binary... but you're allowed to use twos as well
Based on the "binary, but with twos" notation mentioned in this numberphile video, write a function that takes a single number as input and outputs all variations of that number in a "binary" system where twos are allowed.
Rules

Code must only be a function/method, not a full program
Input is an integer passed as the sole parameter to the function
Output is all valid variations of the input number converted to "binary, but with twos" notation
Output is the return value of the function, but can be in whatever format is convenient as long as it's obvious (eg, 3 ints, 3 strings, comma/space delimited string, array of ints, etc), order is unimportant
In the unlikely event that a language happens to contain a built-in function to achieve the result, it's disallowed
Shortest code in bytes is the winner

Explanation of the output
By example, if you're passed the number 9, you can convert it to binary as 1001, but if you allowed 2s in each position, you could also write it as 201 (i.e. 2*4 + 0*2 + 1*1), or 121 (i.e. 1*4 + 2*2 + 1*1), as shown in this table:
+----+----+----+----+
| 8s | 4s | 2s | 1s |
+----+----+----+----+
|  1 |  0 |  0 |  1 |
|  0 |  2 |  0 |  1 |
|  0 |  1 |  2 |  1 |
+----+----+----+----+

So, if passed 9, your function would need to return the three numbers, 1001, 201 and 121.
Format and order are irrelevant, so long as it's obvious (i.e. [121,201,1001], "0201 0121 1001", ("1001","121","201") are valid results when given an input of 9).
Examples

2 => 10, 2
9 => 1001, 201, 121
10 => 1010, 210, 202, 1002, 122
23 => 2111, 10111
37 => 100101, 20101, 100021, 20021, 12101, 12021, 11221

There's no such thing as two.

Two? In binary? Is this quantum computing?

GolfScript (25 bytes) / CJam (19 17 bytes)
GolfScript:
{:^.*,{3base}%{2base^=},}

This creates an anonymous function (see meta discussion about permissibility of anonymous functions).
Online demo
A straight translation into CJam is (with thanks to Martin Büttner for shaving a couple of characters)
{:X_*,3fb{2bX=},}

Dissection
{             # Function boilerplate
  :^          # Store parameter as variable ^
  .*          # Square parameter - see detailed explanation below
  ,{3base}%   # Produce an array of 0 to ^*^-1 in ternary
  {2base^=},  # Filter to those which evaluate to ^ in binary
}

The reason for the squaring operation is that we need to iterate up to the largest possible value whose ternary representation, interpreted in binary, is equal to ^. Since 2 = 10, the "normal" binary representation of ^ is the one which matters. If we convert that to ternary, we find that the "worst" cases are powers of 2. An optimal approach would be to take the argument to the power of ln 3/ln 2 ~= 1.585, but squaring is much shorter.

I bet a CJam translation will be lot smaller.

@Optimizer go ahead ;-)

GolfScript? man I'm such a noob

Python 2 (59 bytes)
S=lambda n,B="":[B][n:]or~n%2*S(n/2-1,"2"+B)+S(n/2,`n&1`+B)

(Much thanks to @grc, @xnor and @PeterTaylor for helping out in chat)
Simple recursion, call with S(23) or similar.
Explanation
The general idea is that if n's binary expansion ends in a 1, then any pseudo-binary ("binary, but with twos") expansion must also end with a 1. Otherwise it could end with 0 or 2.
Hence we look at the last bit of n, divide out and branch accordingly.
Dissection
S=lambda n,B="":           # Lambda expression
[B][n:]or                  # Short circuit, return [B] if n==0 else what follows
~n%2*                      # Keep next list result if n is even else turn into []
S(n/2-1,"2"+B)             # Add a "2" to B, recurse
+
S(n/2,`n&1`+B)             # Add "0" or "1" to B depending on n's last bit, recurse

Variables:

n: The number we want to find pseudo-binary expansions of
B: A pseudo-binary string being built right-to-left

Bash+coreutils, 77
f()(seq `dc -e2o$1p`|sed '/[3-9]/d;s/.*/&n9P2i&pAi/'|dc|grep -Po ".*(?= $1)")

(That is a TAB character in the grep expression.)
This is bending this rule a bit:
"In the unlikely event that a language happens to contain a built-in function to achieve the result, it's disallowed"
It turns out that dc has the reverse of what we need built in.  For instance if we set the input base to 2 and input a binary number with twos, it will correctly parse it.  (Similarly if the input mode is base 10, then A-F are parsed as decimal "digits" 10-15).
seq creates a list of all decimal numbers up to the standard binary representation of n, parsed as a decimal.  Then all numbers that contain anything other than {0,1,2} are filtered out.  Then dc parses the remaining numbers as binary to see which evaluate back to n.
Bash functions can only "return" scalar integers 0-255.  So I'm taking the liberty of printing the list to STDOUT as my way of "returning".  This is idiomatic for shell scripts.
Output:
$ f 2
2
10
$ f 9
121
201
1001
$

Haskell, 82
t n=[dropWhile(==0)s|s<-mapM(\_->[0..2])[0..n],n==sum[2^(n-i)*v|(i,v)<-zip[0..]s]]

this is just a brute-force solution. it is very inefficient, because it is expected to crunch through 3^n possibilities.

Jelly, 10 bytes, language postdates challenge
ṗ@3Ḷ¤Ḅ=¥Ðf

Try it online!
A bruteforce solution up to a number of hyperbits equal to the input (this format is known as "hyperbinary"). As such, it's incredibly inefficient, running in O(3n).
Explanation
ṗ@3Ḷ¤Ḅ=¥Ðf
ṗ@            Construct all lists with the given length, and elements taken from
  3Ḷ¤         the list [0,1,2]
        Ðf    then take only those elements which
     Ḅ=¥      when interpreted as binary, equal {the original number}

PHP, 138 Bytes
function p($v,$i=0,$r=""){global$a;if($v==0)$a[]=$r?:0;elseif($v>0)for(;$l<3;)p($v-2**$i*$l,$i+1,+$l++.$r);}p($argv[1]);echo join(",",$a);

Breakdown
function p($v,$i=0,$r=""){
    global$a;
    if($v==0)$a[]=$r?:0;  # fill result array
    elseif($v>0) # make permutations
        for(;$l<3;)
            p($v-2**$i*$l,$i+1,+$l++.$r); #recursive
}
p($argv[1]);
echo join(",",$a); # Output

C++, 159 bytes
void c(int x,string r){int i,t=0,s=r.size();if(s<8){if(r[0]>48){for(i=0;i<s;i++)t+=(r[s-i-1]-48)*1<<i;if(t==x)cout<<r<<" ";}for(char n=48;n<51;n++)c(x,r+n);}}

Test it here

157 bytes

k, 21 bytes
Uses the same method as Peter Taylor's Golfscript answer
{X@&x=2/:'X:3\:'!x*x}

Examples:
k) {X@&x=2/:'X:3\:'!x*x}9
(1 2 1;2 0 1;1 0 0 1)
k) {X@&x=2/:'X:3\:'!x*x}10
(1 2 2;2 0 2;2 1 0;1 0 0 2;1 0 1 0)

Haskell, 80 bytes
f 0=[[]]
f n=((++[n-2*d])<$>f d)++[x|n==2*d,x<-(++[2])<$>(f$d-1)]where d=n`div`2

Try it online!
Recursive solution, and my first Haskell golf.
-- recursive definition
-- base case: a sum of 0 is possible as simply a 0-length "binary-with-two" string
f 0=[[]]
-- f n=all possibilities to form n
f n =
-- like normal binary, can have a last digit of 0 or 1 if even or odd, respectively
-- consider n`mod'`2 = n-2*d
  (
    (++[n-2*d])<$> -- add that last digit to each
    f d -- possibility from n/2
  )
-- additional possibility of last digit 2, only if n is even
     n==2*d -- if n is even:
  [x|      ,x<-(++[2])<$>(f$d-1)] -- add that last digit 2 to each possibility from (n-2)/2
  where d=n`div`2

authors: كونترول الحملات


text:
Algorithm - Costliest Possible Route in Grid Puzzle
Objective
Find the most expensive path from the top-left of a square grid to the bottom-right such that its total cost is below a given threshold.
Scenario

You are given a square NxN grid.
You are given a maximum cost.
Every cell in the grid has a cost. The top-left cell has cost 0.
The cost of a path is the sum of the costs of the cells in the path. Its "cost surplus" is the result of subtracting its cost from the maximum cost.
Movement is always either right one cell or down one cell.
The starting point is the top-left cell of the grid and the goal is the bottom-right cell.
You must output the smallest cost surplus of any path with a non-negative cost surplus, or -1 if there is no such path (The maximum cost is not enough).

Input restrictions

N will be between 1 and 20 inclusive.
The maximum cost will be between 1 and 200 inclusive.
The cost of each cell will be between 0 and 10 inclusive.

Examples

Maximum cost: 9
Grid:
0 1 5
2 3 2
2 3 2

Expected output: 0
Explanation: there is a path 0 2 2 3 2 with cost 9 and cost surplus 0.
Maximum cost: 15
Grid:
0 1 5
2 3 2
2 3 2

Expected output: 5
Explanation: the most expensive path is 0 1 5 2 2 with cost 10 and cost surplus 5.
Maximum cost: 6
Grid:
0 1 5
2 3 2
2 3 2

Expected output: -1
Explanation: the least expensive path is 0 1 3 2 2 with cost 8, which is greater than 6.

@Sp3000 added the code-golf tag! thanks!

@Sp3000 OK so for the first one the maximum number will be down-right-right-down so it will be 9 - (0+2+3+2+2) = 0 and for the second one will be down-right-down-right so it will be 15 - (0+2+3+3+2) = 10

@Sp3000 OP basically wants the costliest possible route..

@Optimizer That would be more easy to understand then! I already changed the title.

Oh right, sorry I got a little confused as to whether we were minimising or maximising. If that's the case I'm a little confused about the maximum step - is that allowed to go negative? It seems to me that rather than having a maximum step you could just find the path which scores the most "points", so to speak.

@Sp3000 No it won't be allowed to be negative. You will need to backtrack if the value goes to negative.

@Sp3000 steps here are money. Each cell has cost. You can only go right or bottom, so total cells u visit is constant. You go further only when you have money.

Am I correct to assume that the cost of a path includes both the cost of the top-left cell and the cost of the bottom-right cell?

@PeterTaylor Yes! But let's just assume the top left will always be 0

GolfScript (53 bytes)
~.,[1]*\{[[\]0\zip{~2$|2@?*}/](;}/-1=2.$)?|2base\~>1?

Expects input in the format
15 [[0 1 5][2 3 2][2 3 2]]

Online demo which covers three test cases.
The approach is to build up a list of possible running totals to each cell as a bitmask, extract the relevant lower bits, base-convert to a list of 0 and 1, and look for the index of the first 1.
Dissection
~              # Eval input: puts N and grid on the stack
.,[1]*         # Set up initial row cost bitmask: 2^0 for each column
\{             # For each row in grid:
  [            #   Stack: N prev-row-bitmask this-row-cost
    [\]0\zip   #   Pair up prev-row-bitmask and this-row-cost and push 0 under them
    {          #   For each pair:
      ~        #     Stack: N left-cell-bitmask cost up-cell-bitmask
      2$|2@?*  #     this-cell-bitmask = (left-cell-bitmask | up-cell-bitmask) << cost
    }/
  ](;          #   Gather row into an array and drop the 0 we inserted for the -1th cell
}/
-1=            # Take the bitmask of the bottom-right cell. Stack: N bottom-right-bitmask
2.$)?|         # Or 2^N to ensure that we get enough bits from the base conversion
2base          # Base conversion
\~>            # Take the last (least significant) N+1 bits
1?             # Find the first index (hence smallest cost surplus) of the value 1

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

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

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

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

Nice one! how can I change the size of the grid? you will automatically change it to square?

@nayoso Yes, I expect a flat square grid.

I tested  "50 [0 1 5 7 2 3 4 2 3 9 2 9 9 9 9 9]"  and the output was 17.  I believe it should be 9

@bubalou Ughh, I forgot to sort in the latest revision. Fixed now.

VBScript 191
This assumes that the array is in a variable called A and the cost is in a variable called c.
Dim M
Sub f(s,i,j,v)
If i>s And j=s And v<=c And M<v Then M=v
If i>s Or j>s Then Exit Sub
f s,i+1,j,v+A(i)(j)
f s,i,j+1,v+A(i)(j)
End Sub
f UBound(A),0,0,0
If M=0Then MsgBox-1 Else MsgBox c-M

To run it put the following lines at the top of a file called x.vbs then paste in the code above and just double click or execute cscript x.vbs
A=Array(Array(0,1,5),Array(2,3,2),Array(2,3,2))
c=6

CJam, 71 69 68 bytes
I didn't look at anything from Optimizer's answer, except its size and input format... so the size is complete coincidence. But I think this can be golfed a fair bit.
l~:L,mqi(:X2*2\#:Y[{IY+2b(;_:+X={0_@{X*)+_L=@+\}/}*;}fI]f-{W>},$W+0=

Test it here.
The input on STDIN is in the form of the maximum steps and the unrolled grid as a CJam array:
9 [0 1 5 2 3 2 2 3 2]

Explanation:
"Prepare input:";
l~:L,mqi(:X2*2\#:Y
l~                    "Read and eval input.";
  :L                  "Store grid in L.";
    ,mqi(:X           "Get length, square root, cast to int, decrement, store in X.";
           2*2\#:Y    "Multiply by 2, raise 2 to this power, store in Y.";

[{...}fI]             "For I in 0 to Y-1. Collect in array.";

"Determine path:";
IY+2b(;_:+X=
IY+                   "I + Y.";
   2b                 "Convert to base 2.";
     (;               "Drop leading 1.";
       _:+            "Duplicate and sum.";
          X=          "Check for equality with X.";

{...}*                "If equals, execute this (otherwise, don't).":

"Determine remaining weight:";
0_@{X*)+_L=@+\}/
0                     "Push 0. This is the sum.";
 _                    "Push another 0. This is the current position in the grid.";
  @                   "Pull up path description. 1 -> down, 0 -> right.";
   {          }/      "For each step...";
    X*)               "Multiply by X, increment.";
       +              "Add to current position.";
        _L=           "Duplicate and extract grid element.";
           @+         "Pull up sum and add.";
             \        "Swap with position.";

;                     "Pop... either the invalid path or the last position.";

f-                    "Subtract each sum from the maximum step number.";
  {W>},               "Filter out negative results.";
       $              "Sort.";
        W+            "Append a -1.";
          0=          "Take the first element.";


text:
Use threes to count the threes!
Write a program or function that takes two numbers - x>3 and n>0 - as input, and finds all possible bases b where the digit 3 appears at least n times in (x in base b).
Input and output may be through command line or function arguments, stdin/stdout, graphical input/output, error messages, function returns, etc.
The code must consist entirely of three-symbol "words", where each symbol is a letter or number (in printable ASCII) and the words are each separated by one non-alphanumeric printable ASCII character or newline (see example). Furthermore, adding a space into any of the words must ruin the program.
Shortest code wins.
Example
The following code meets the first part of the specs (but doesn't actually work):
abc 123 fwe[3gY]4fs-es3=13N
338 w3W|W2w

Test Cases
5 1 ->
8 1 -> 5
23 1 -> 4 5 6 7 10 20
15 2 -> 4
111 2 -> 4 6 9 36
819 3 -> 4 16
A test program written in Java 8 can be found at http://pastebin.com/E8GpHbfB.

Just to prove a solution exists... http://esolangs.org/wiki/Lenguage (didn't expect Pietu's creation to be relevant so soon)

I'm not a fan of the restriction. It seems gimmicky and eliminates some languages.

Should we consider adding a space in the middle only or at the edge too?

@proudhaskeller Only in the middle

This is impossible in J: I'd require a minimum of one =. to make it otherwise work under this restriction. Unrestricted, there is the 30 character  n((=s+/@(3=#.inv)"0])#s=.]2+i.)x.

This is impossible in GP: The parser ignores spaces outside strings, and so adding a space into a word won't alter its meaning.

BBC Basic, 207 bytes
BBC Basic allows you to abbreviate keywords by ending them with a period (e.g., PRINT ↠ PRI., REPEAT ↠ REP.). I should really be using a named procedure here instead of a function declaration, but abbreviating DEF PROC_whatever to DEF PRO. just isn't going to work.
The rules make it impossible to use an IF statement, so instead I'm calculating the target line of a GOTO statement based on the result of a comparison. (In BBC Basic, true has a value of –1, so 101-ZIP is equal to 102 if ZIP is true, and 101 otherwise.)
The last line (103=000) ends the function definition and returns a value of zero.
Tested on BeebEm3. Lines 10–60 are excluded from the byte count.
10 READ X,N : IF X=0 THEN END
20 PRINT "x=";X;", n=";N
30 A = FNX(X,N)
40 GOTO 10
50 DATA 5,1,8,1,23,1,15,2,111,2,819,3,0,0
60 REM -------------------
100 DEF FNX(FOO,BAR)BAZ=004:REP.BAT=000:QUX=FOO:REP.XXD=QUX MOD BAZ:ZAP=XXD=003:BAT=BAT-ZAP:QUX=QUX-XXD:QUX=QUX/BAZ:UNT.QUX=000:ZIP=BAT<BAR:ZIP=101-ZIP:GOT.ZIP
101 PRI.BAZ
102 BAZ=BAZ+001:UNT.BAZ=FOO
103=000

CJam, 108 bytes
097{sLo,Lso=rii*rii:MLo;Lso_Lso,002>Lso{001$Lso\Lob{003=Lso}Lso,Lso,MLo(Lso>Lso}Lso,Lso\Lso;LoS*Lso}000$001*

It will not stop people using CJam...

Haskell, 219
003&bbb=001
nnn&bbb|bbb>nnn=000|000<111=mod nnn bbb&bbb+div nnn bbb&bbb
nnn%xxx=ggo nnn 004 xxx
ggo nnn bbb xxx|bbb>nnn=get[nnn]nnn|nnn&bbb>xxx-001=bbb:ggo nnn(bbb+001)xxx|000<111=ggo nnn(bbb+001)xxx
get(xxx:sss)bbb=sss

call like 8 % 1.
I mostly just used three-letter / operator names, but it was tricky to get an empty list ([]).

C - 252 characters
Will admit C is not the best language for this, and had to cheat a little bit...
To compile, save as fit.c then gcc -D___=/**/ -o fit fit.c
The function fit can be all concatenated on one line, but I thought it looked nicer and fit in with the threeness of the challenge by formatting in lines of 9 (=3×3) token/punctuation pairs. The hardest part was figuring out a way to check for == 3 without using ==!
// The function I'm counting...

fit(int not,int fin,int*rot)___{int
nor,fir,nit,ton,tin,ion;for(nor=004;
nor<not;nor=nor+001)___{for(nit=not,
fir=000;nit>000;nit=nit/nor)tin=nit%
nor,ion=tin<003|tin>003,ion=ion?000:
001,fir=fir+ion;ton=fir<fin,ton=ton?
000:001;rot[nor]___=ton;___}___ ___}

// This is the code to call the function...

#include <stdio.h>

main()
{
    int a[999];
    int X[6] = {5, 8, 23, 15, 111, 819};
    int N[6] = {1, 1, 1, 2, 2, 3};

    int i, j;

    for (i = 0; i < 6; i++)
    {
        fit(X[i], N[i], a);

        printf("%d %d ->", X[i], N[i]);

        for (j = 4; j < X[i]; j++)
            if (a[j]) printf(" %d", j);

        printf("\n");
    }

    return 0;
}

Output is per specs:
5 1 ->
8 1 -> 5
23 1 -> 4 5 6 7 10 20
15 2 -> 4
111 2 -> 4 6 9 36
819 3 -> 4 16

Fixed it, with only one minor cheat...

seems like if you can make your code only one statement using , you could get rid of the brackets


text:
Forming Polyominoes with a Chain of Rods
Background
Consider a (closed) chain of rods, each of which has integer length. How many distinct hole-free polyominoes can you form with a given chain? Or in other words, how many different non-self-intersecting polygons with axis-aligned sides can you form with a given chain?
Let's look at an example. Consider a particular chain consisting of 8 rods of length 1 and 2, which we can represent as [1, 1, 2, 2, 1, 1, 2, 2]. Up to rotations and translations, there are only 8 possible polyominoes (we do count different reflections):

This first rod is dark blue, and then we traverse the polygon in a counter-clockwise sense.
The sense of rotation doesn't affect the result in the above example. But let's consider another chain, [3, 1, 1, 1, 2, 1, 1], which yields the following 3 polyominoes:

Notice that we do not include a reflection of the last polyomino, because it would require clockwise traversal.
If we had a more flexible chain of the same length, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], we would actually be able to form both reflections among some other polyoninoes, totalling 9:

The Challenge
Given a description of a chain, as an array or similar, determine the number of distinct polyominoes you can form (up to rotations and translations) by using the rods in order while going around the perimeter in a counter-clockwise sense.
Please write a full program and include commands to compile (if applicable) and run your code from the command line. Please also include a link to a free compiler/interpreter for your language.
Your program should read the input from STDIN. The first line will contain an integer M. The next M lines will be test cases, each of which will be a space-separated list of rod lengths. Your program should print M lines to STDOUT, each of which consists of a single integer - the number of distinct polyominoes that can be formed.
You must only use a single thread.
Your program must not use more than 1 GB of memory at any time. (This is not a completely strict limit, but I will monitor your executable's memory usage, and kill any process that consistently uses more than 1 GB, or spikes significantly above it.)
To prevent excessive amounts of pre-computation, your code must not be longer than 20,000 bytes, and you must not read any files.
You must also not optimise towards the specific test cases chosen (e.g. by hardcoding their results). If I suspect that you do, I reserve the right to generate new benchmark sets. The test sets are random, so your program's performance on those should be representative for its performance on arbitrary input. The only assumption you're allowed to make is that the sum of the rod lengths is even.
Scoring
I have provided benchmark sets for chains of N = 10, 11, ..., 20 rods. Each test set contains 50 random chains with lengths between 1 and 4 inclusive.
Your primary score is the largest N for which your program completes the entire test set within 5 minutes (on my machine, under Windows 8). The tie breaker will be the actual time taken by your program on that test set.
If anyone beats the largest test set, I will keep adding larger ones.
Test Cases
You can use the following test cases to check the correctness of your implementation.
Input                            Output

1 1                              0
1 1 1 1                          1
1 1 1 1 1 1                      1
1 1 1 1 1 1 1 1                  3
1 1 1 1 1 1 1 1 1 1              9
1 1 1 1 1 1 1 1 1 1 1 1          36
1 1 1 1 1 1 1 1 1 1 1 1 1 1      157
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  758
1 1 2 2 1 1 2 2                  8
1 1 2 2 1 1 2 2 1 1              23
1 1 2 2 1 1 2 2 1 1 2 2          69
1 2 1 2 1 2 1 2                  3
1 2 1 2 1 2 1 2 1 2 1 2          37
1 2 3 2 1 2 3 2                  5
1 2 3 2 1 2 3 2 1 2 3 2          23
3 1 1 1 2 1 1                    3
1 2 3 4 5 6 7                    1
1 2 3 4 5 6 7 8                  3
1 2 3 4 5 6 7 8 9 10 11          5
2 1 5 3 3 2 3 3                  4
4 1 6 5 6 3 1 4                  2
3 5 3 5 1 4 1 1 3                5
1 4 3 2 2 5 5 4 6                4
4 1 3 2 1 2 3 3 1 4              18
1 1 1 1 1 2 3 3 2 1              24
3 1 4 1 2 2 1 1 2 4 1 2          107
2 4 2 4 2 2 3 4 2 4 2 3          114

You find an input file with these over here.
Leaderboard
   User          Language       Max N      Time taken (MM:SS:mmm)

1. feersum       C++ 11         19         3:07:430

2. Sp3000        Python 3       18         2:30:181

"hole-free" seems superfluous. one contiguous chain can't produce hole'd polyominoes in the first place.

Is multi-threading allowed? And if the threads are in different processes, does each one get to use 1 GB? :P

@Sparr It can when the perimeter touches itself at a corner. For instance, see No. 81 here. That one shouldn't be counted.

@feersum For simplicity, I'm going to say no to multi-threading (and will edit the challenge).

@MartinBüttner ahh, I mistook touching-at-a-corner as self-intersecting.

@Sparr It's also self-intersecting, as far as the bounding polygon is concerned. The two definitions are supposed to be equivalent, and each was supposed to be valid on its own. I just wanted to provide two different viewpoints.

@PeterKagey Did you post this comment on the wrong challenge? Looks like it should have gone on this one.

C++11
Updates:
Added the first line of c which breaks out early if the distance is too far from the origin (which was the whole purpose of the variable rlen, but I forgot to write it in the first version). I changed it to use much less memory, but at the cost of time. It now solves N=20 in just under 5 minutes for me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <ctime>

#define M std::map
#define MS 999
#define l (xM*2+1)

#define KITTENS(A,B)A##B
#define CATS(A,B)KITTENS(A,B)
#define LBL CATS(LBL,__LINE__)
#define unt unsigned
#define SU sizeof(unt)
#define SUB (SU*8)
#define newa (nb^SZ||fail("blob"),nb+++blob)

#define D

struct vec {int x, y;};

unt s[MS*2];
int xM, sl[MS];
vec X[MS];

struct a;
struct a  { M<unt,unt>v;};

#define SZ ((1<<29)/sizeof(a))
a*blob;
unt nb;

int fail(const char*msg)
{
    printf("failed:%s", msg);
    exit(1);
    return 1;
}

struct
{
    unt*m;
    bool operator()(int x, int y) { return m[(x+l*y)/SUB] >> (x+l*y)%SUB & 1; }
    void one(int x, int y) { m[(x+l*y)/SUB] |= 1U << (x+l*y)%SUB; }
    void zero(int x, int y) { m[(x+l*y)/SUB] &= ~(1U << (x+l*y)%SUB); }
} g;

unt c(a*A, vec x, unt rlen, unt sn) {
    if((unt)x.y+abs(x.x) > rlen) return 0;
    if(!rlen) {
        vec *cl=X, *cr=X, *ct=X;
        for(unt i=1; i<sn; i++) {
            #define BLAH(Z,A,B,o,O) \
                if(X[i].A o Z->A || (X[i].A == Z->A && X[i].B O Z->B)) \
                   Z = X+i

            BLAH(cl,x,y,<,>);
            BLAH(cr,x,y,>,<);
            BLAH(ct,y,x,>,>);
        }
        unt syms = 1;
        #define BLA(H,Z) {bool sy=1;for(unt o=0; o<sn; o++) sy &= (int)(1|-(H))*sl[o] == sl[(Z-X+o)%sn]; syms += sy;}
        BLA(~o&1,cl)
        BLA(1,ct)
        BLA(o&1,cr)

        #ifdef D
            //printf("D");for(int i=0;i<sn;i++)printf(" %u",sl[i]);printf("\n");
            if(syms==3) fail("symm");
        #endif

        return syms;
    }
    if(!(x.x|x.y|!sn)) return 0;
    X[sn] = x;

    unt k = 0;
    for(auto it: A->v) {
        int len = it.first;
        bool ve = sn&1;
        int dx = ve?0:len, dy = ve?len:0;

        #define PPCG(O)(x.x O (ve?0:z), x.y O (ve?z:0))
        #define MACR(O) { \
            vec v2 = {x.x O dx, x.y O dy}; \
            if(v2.y<0||(!v2.y&&v2.x<0)||abs(v2.x)>xM||v2.y>xM) \
                goto LBL; \
            for(int z=1; z<=len; z++) \
                if(g PPCG(O)) \
                    goto LBL; \
            for(int z=1; z<=len; z++) \
                g.one PPCG(O); \
            sl[sn] = O len; \
            k += c(blob+it.second, v2, rlen - len, sn+1); \
            for(int z=1; z<=len; z++) \
                g.zero PPCG(O); \
            } LBL: \

    MACR(+);
    MACR(-);
    }

    return k;
}

void stuff(a *n, unt j, unt r, unt len1)
{
    unt t=0;
    for(unt i=j; i<j+r; i++) {
        t += s[i];
        if((int)t > xM || (len1 && t>len1)) break;
        if(len1 && t < len1) continue;
        int r2 = r-(i-j)-1;
        if(r2) {
            unt x;
            if(n->v.count(t))
                x = n->v[t];
            else
                n->v[t] = x = newa - blob;
            stuff(blob+x, i+1, r2, 0);
        } else n->v[t] = -1;
    }
}

int main()
{
    time_t tim = time(0);
    blob = new a[SZ];
    int n;
    scanf("%u",&n);
    while(n--) {
        nb = 0;
        unt ns=0, tl=0;
        while(scanf("%u",s+ns)) {
            tl += s[ns];
            if(++ns==MS) return 1;
            if(getchar() < 11) break;
        }
        xM = ~-tl/2;
        g.m = (unt*)calloc((xM+1)*l/SU + 1,4);

        memcpy(s+ns, s, ns*SU);

        unt ans = 0;
        for(unt len1 = 1; (int)len1 <= xM; len1++) {
            a* a0 = newa;
            for(unt i=0; i<ns; i++)
                stuff(a0, i, ns, len1);
            ans += c(a0, {}, tl, 0);
            for(unt i=0; i<nb; i++)
                blob[i].v.clear();
        }
        printf("%d\n", ans/4);
        free(g.m);
    }

    tim = time(0) - tim;
    printf("time:%d",(int)tim);
    return 0;
}

Compile with
g++ --std=c++11 -O3 feersum.cpp -o feersum.exe

doze #defines tho

In the absence of any other answers... here, have a bounty!

Python 3 (with PyPy) — N = 18
ANGLE_COMPLEMENTS = {"A": "C", "F": "F", "C": "A"}
MOVE_ENUMS = {"U": 0, "R": 1, "D": 2, "L": 3}
OPPOSITE_DIR = {"U": "D", "D": "U", "L": "R", "R": "L", "": ""}

def canonical(angle_str):
    return min(angle_str[i:] + angle_str[:i] for i in range(len(angle_str)))

def to_angles(moves):
    """
    Convert a string of UDLR to a string of angles where
      A -> anticlockwise turn
      C -> clockwise turn
      F -> forward
    """

    angles = []

    for i in range(1, len(moves)):
        if moves[i] == moves[i-1]:
            angles.append("F")
        elif (MOVE_ENUMS[moves[i]] - MOVE_ENUMS[moves[i-1]]) % 4 == 1:
            angles.append("C")
        else:
            angles.append("A")

    if moves[0] == moves[len(moves)-1]:
        angles.append("F")
    elif (MOVE_ENUMS[moves[0]] - MOVE_ENUMS[moves[len(moves)-1]]) % 4 == 1:
        angles.append("C")
    else:
        angles.append("A")

    return "".join(angles)

def solve(rods):
    FOUND_ANGLE_STRS = set()

    def _solve(rods, rod_sum, point=(0, 0), moves2=None, visited=None, last_dir=""):
        # Stop when point is too far from origin
        if abs(point[0]) + abs(point[1]) > rod_sum:
            return

        # No more rods, check if we have a valid solution
        if not rods:
            if point == (0, 0):
               angle_str = to_angles("".join(moves2))

               if angle_str.count("A") - angle_str.count("C") == 4:
                   FOUND_ANGLE_STRS.add(canonical(angle_str))

            return

        r = rods.pop(0)

        if not visited:
            visited = set()
            move_dirs = [((r, 0), "R")]
            moves2 = []

        else:
            move_dirs = [((r,0), "R"), ((0,r), "U"), ((-r,0), "L"), ((0,-r), "D")]

        opp_dir = OPPOSITE_DIR[last_dir]

        for move, direction in move_dirs:
            if direction == opp_dir: continue

            new_point = (move[0] + point[0], move[1] + point[1])
            added_visited = set()
            search = True

            for i in range(min(point[0],new_point[0]), max(point[0],new_point[0])+1):
                for j in range(min(point[1],new_point[1]), max(point[1],new_point[1])+1):
                    if (i, j) != point:
                        if (i, j) in visited:
                            search = False

                            for a in added_visited:
                                visited.remove(a)

                            added_visited = set()
                            break

                        else:
                            visited.add((i, j))
                            added_visited.add((i, j))

                if not search:
                    break

            if search:
                moves2.append(direction*r)
                _solve(rods, rod_sum-r, new_point, moves2, visited, direction)
                moves2.pop()

            for a in added_visited:
                visited.remove(a)

        rods.insert(0, r)
        return

    _solve(rods, sum(rods))
    return len(FOUND_ANGLE_STRS)

num_rods = int(input())

for i in range(num_rods):
    rods = [int(x) for x in input().split(" ")]
    print(solve(rods))

Run with ./pypy <filename>.

This is the reference implementation I wrote when discussing the question with Martin. It wasn't made with speed in mind and is quite hacky, but it should provide a good baseline to kick things off.
N = 18 takes about 2.5 minutes on my modest laptop.
Algorithm
Rotations are checked by converting each shape into a series of F for forward, A for anticlockwise turn and C for clockwise turn at each lattice point on the boundary of the shape — I call this an angle string. Two shapes are rotationally identical if their angle strings are cyclic permutations. Rather than always checking this by comparing two angle strings directly, when we find a new shape we convert to a canonical form before storing. When we have a new candidate, we convert to the canonical form and check if we already have this (thus exploiting hashing, rather than iterating through the whole set).
The angle string is also used to check that the shape is formed anticlockwise, by making sure that the number of As exceeds the number of Cs by 4.
Self-intersection is naïvely checked by storing every lattice point on the boundary of the shape, and seeing if a point is visited twice.
The core algorithm is simple, placing the first rod to the right, then trying all possibilities for the remaining rods. If the rods reach a point which is too far from the origin (i.e. sum of remaining rod lengths is less than the Manhattan distance of the point from the origin), then we prematurely stop searching that subtree.
Updates (latest first)

6/12: Introduced canonical form, added a few micro-optimisations
5/12: Fixed error in algorithm explanation. Made the quadratic cyclic-permutation-checking algorithm linear using the A,B cyclic permutations iff A substring of B+B method (I have no idea why I didn't do this earlier).

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

authors: Краси Николова

authors: Роман Кошурников


text:
Longest reverse palindromic DNA substring
As you may know, in DNA there are four bases — adenine (A), cytosine (C), guanine (G) and thymine (T). Typically A bonds with T and C bonds with G, forming the "rungs" of the DNA double helix structure.
We define the complement of a base to be the base it bonds to — i.e. the complement of A is T, the complement of T is A, the complement of C is G and the complement of G is C. We can also define the complement of a DNA string to be the string with each base complemented, e.g. the complement of GATATC is CTATAG.
Because of the double-stranded structure of DNA, the bases on one strand are complementary to the bases on the other strand. However DNA has a direction, and DNA transcription occurs in opposite directions on the two strands. Hence molecular biologists are often interested in the reverse complement of a DNA string — quite literally the reverse of the complement of the string.
To extend our previous example, the reverse complement of GATATC is CTATAG backwards, so GATATC. As you may have noticed, in this example the reverse complement is equal to the original string — we call such a string a reverse palindrome.*
Given a string of DNA, can you find the longest substring which is a reverse palindrome?
*I use the term "reverse palindrome", taken from Rosalind, to differentiate from the usual meaning of palindrome.

Input
Input will be a single string consisting of only the characters ACGT in upper case. You may write either a function or a full program for this challenge.
Output
You may choose to output via either printing or returning (the latter choice is only available in the case of a function).
Your program should output the longest reverse palindromic substring of the input string, if there is a unique solution. If multiple solutions exist, then you may either output any single one of them, or all of them (your choice). Duplicates are okay if you choose to output all of them.
The input is guaranteed to have a solution of at least length 2.
Worked example
ATGGATCCG -> GGATCC

The reverse complement of GGATCC is itself (GGATCC --complement--> CCTAGG --reverse--> GGATCC), so GGATCC is a reverse palindrome. GATC is also a reverse palindome, but it is not the longest one.
Test cases
AT -> AT
CGT -> CG
AGCA -> GC
GATTACA -> AT, TA
ATGGATCCG -> GGATCC
CCCCCGGGGG -> CCCCCGGGGG
ACATATATAGACT -> ATATAT, TATATA
ATTCGATCTATGTAAAGAGG -> TCGA, GATC
CGCACGTCTACGTACCTACGTAG -> CTACGTAG
TCAATGCATGCGGGTCTATATGCAT -> ATGCAT, GCATGC [, ATGCAT]
CGCTGAACTTTGCCCGTTGGTAGAACGGACTGATGTGAACGAGTGACCCG -> CG, GC, TA, AT [, GC, CG, CG, CG, CG]
CTCGCGTTTGCATAACCGTACGGGCGGAACAGTCGGCGGTGCCTCCCAGG -> CCGTACGG

Scoring
This is code golf, so the solution in the fewest bytes wins.

It would have been nicer if printing all of them had some sort of bonus.

@Optimizer isn't printing just the longest more difficult than printing all of them?

Or do you mean printing all of the longest ones?

@githubphagocyte yes, your second comment.

Pyth, 37 36 28 24 bytes
ef&}TzqmaCd6T_mx4aCk6Tyz

Combining the tips from FryAmTheEggman and the reverse palindrome check trick from Peter, this is a super short version.
However, this only works with Pyth 3.0.1 which you can download from this link and run like
python3 pyth.py -c "ef&}TzqmaCd6T_mx4aCk6Tyz" <<< "ATTCGATCTATGTAAAGAGG"

(linux bash only. On windows, press Enter instead of the <<< and then type the input)

This is my previous submission - 28 bytes solution
J"ACGT"ef&}TzqTjk_m@_JxJdTyz

Thanks to FryAmTheEggman for this version. This one creates all possible subsets of the input DNA string, filters the subsets on the condition that the subset is a substring of input and the reverse of transform is equal to the subset itself.
Due to all possible subset creation, this takes up even more memory than Peter's answer.

This is my first submission - 36 byte solution.
J"ACGT"eolNfqTjk_m@_JxJdTm:zhkek^Uz2

This is the exact translation of my CJam answer. I was hoping that this would be much smaller but turns out that lack of translation method made it almost similar size (still 2 bytes smaller though)
Try it online here

Uz is equivalent to Ulz.

J"ACGT"eolNf&}TzqTjk_m@_JxJdTyz Using y for subsets and then filtering out strings that aren't substrings of z is shorter :)

Oh, and if you do that, you don't need to sort because y is already sorted by length. You can just do ef...

GolfScript (35 34 bytes)
]{{..(;\);}%)}do{{6&}%.{4^}%-1%=}?

For testing purposes you may wish to use
]{{..(;\);}%.&)}do{{6&}%.{4^}%-1%=}?

which adds a .& to reduce the duplicated effort.
Dissection
]{         # Gather string into an array and do-while...
  {        #   Map over each string in the array
    ..     #     Make a couple of copies of the string
    (;     #     Remove the first character from one of them
    \);    #     Remove the last character from the other
  }%
  )        #   Extract the last string from the array
}do        # Loop until that last string is ''
           # Because of the duplication we now have an array containing every substring
           # of the original string, and if we filter to the first occurrence of each
           # string then they're in descending order of length
{          # Find the first element in the string satisfying the condition...
  {6&}%    #   Map each character in the string to its bitwise & with 6
  .{4^}%   #   Duplicate, and map each to its bitwise ^ with 4
           #   This serves to test for A <-> T, C <-> G
  -1%=     #   Reverse and test for equality
}?

q{]{__(;\);}%~}h]{:c:i6f&_4f^W%=}= in CJam. Same size. Do not try it in the online compiler for anything bigger than 7 length input

CJam, 39 38 bytes
I am sure this can be golfed further...
q:Q,,_m*{~Q<>}%{,~}${_"ACGT"_W%erW%=}=

Takes the DNA string from STDIN and outputs the longest reverse palindromic DNA to STDOUT
Try it online here
(Explanation soon)
(Saved 1 byte thanks to Peter)

Python 3, 125 chars
S=input()
l=[]
while S:
 s=_,*S=S
 while s:l+=[s]*all(x+y in"ATA CGC"for x,y in zip(s,s[::-1]));*s,_=s
print(*max(l,key=len))

Look ma, no indexing! (Well, except to reverse the string, that doesn't count.)
Iterating over the substrings is done by taking off chars from the front and end using starred assignment. The outer loop removes characters for the start of S, and for each such suffix, s loops over all prefixes of it, testing them one by one.
Testing for reverse palindrome is done by the code
all(x+y in"ATA CGC"for x,y in zip(s,s[::-1]))

which checks that each symbol and its reversed-string counterpart are one of "AT", "TA", "CG", and "GC". I also found a set-based solution to be one character shorter, but loses two chars on requiring outer parens when used.
set(zip(s,s[::-1]))<=set(zip("ACTG","TGAC"))

This still feels like it can be shortened.
Finally, the longest palindrome is printed.
print(*max(l,key=len))

I hope space-separated outputs are OK. If a list also fine, the the star could be removed. I had tried tracking the running max in the loop instead, as well as cramming the inner loops into a list comprehension so I could take the max directly without constructing l, and both turned out slightly longer. But, it was close enough that it's hard to tell which approach is actually best.

I wanted to be more flexible with this question so I didn't specify an exact output format for tied solutions. If it's clear what the solutions are then it's fine, so a list is okay.

Perl - 59 bytes
#!perl -p
$_=$_[~!map$_[length]=$_,/((.)(?R)?(??{'$Q5'^$+.-$+}))/gi]

Counting the shebang as one, input is taken from STDIN.
Sample usage:
$ echo CTCGCGTTTGCATAACCGTACGGGCGGAACAGTCGGCGGTGCCTCCCAGG | perl dna.pl
CCGTACGG

J (45)
{.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.)

This is a function that takes a string:
   {.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.) 'ATGGATCCG'
┌──────┐
│GGATCC│
└──────┘

Explanation:
{.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.)

              (                          \\.)  for each prefix of each suffix
               (                      #<)      include the argument if,
                        |.@]                      its reverse
                            -:                    is equal to
                'ACGT'&(      [{~3-i.)            the complement
            ,@                                 ravel
   (\:#&.>)@                                   sort by length of item
{.@                                            take the first one

Python 2 - 177 bytes
s=raw_input()
r,l,o=range,len(s),[]
for a in[s[i:j+1]for i in r(l)for j in r(i,l)]:q=['TC GA'.index(c)-2for c in a];o+=[a if[-n for n in q][::-1]==q else'']
print max(o,key=len)

Simple brute force. The actual "reverse palindromic" check is the only interesting part. Here it is written more readably:
check = ['TC GA'.index(c)-2 for c in substring]
if [-n for n in check][::-1] == check:
    # substring is reverse palindromic

I do that on every possible substring and put them in a list if it's true. If it's false, I put in an empty string instead. When all the checks are done I output the longest element of the list. I used an empty string because it saves bytes over putting nothing in, but it also means the program won't choke if there's no solution. It outputs an empty line and exits gracefully.

This seems to be shorter if you smoosh everything into a single list uncomprehension. I had to change the logic a bit, but I got 162 with s=raw_input();r,l,g=range,len(s),'TGCA';print max([a for a in[s[i:j+1]for i in r(l)for j in r(i,l)]if[g[n]for n in[~g.find(c)for c in a]]==list(a)[::-1]],key=len). Also, for strings, use find over index :)

authors: นส ภานุกา พินไชโย