text:
Self containing logs
The "problem"
Define a function log (or other 3 letter name) which when called will log/print/write (whatever is the default for the language in question) both the instruction (as source) and the first argument. In other words:
i=777
j=333
log(i) //outputs: "log(i) 777"
log(i+j+1) //outputs: "log(i+j+1) 1111"

For all practical purposes the output i: 777 would be enough, but in some languages there are very specific reflection libraries for that, and that would be no challenge, so the entire instruction should be outputted.
Inspiration
The inspiration for this was me and another programmer discussing how irritating it is that often (with bad debuggers), you write things like console.log("i:", i), next we made a (pretty crazy) javascript (node only) solution (it outputs i: 777 rather than the entire line of source) which was suprisingly long and reminded me of codegolfing and made me wonder how much better other (especially code golfing) languages would fare.
Bonuses
-10%: No file reading (beyond the compiler)
PS. This is my first 'question' here, so feel free to point out any mistakes I made.

Welcome to CodeGolf.SE! I personally think your question is pretty decent, but it's usually a better idea to run question ideas through the sandbox to resolve ambiguities etc before people start working on answers.

Thx and useful@sandbox, might be good to explain it's use on help/on-topic (it's mentioned, but I didn't consider it worth checking the way it was described there).

@WolleVanillebärLutz: Of course it's not, did you see anyone claim that to be true then?

The bounty is for TrungDQ (I think his solution is amazing just from a code perspective (better than our node only solution), regardless of length), have to wait 24 hours though before I can award it.

C (40 -10% = 36) (38 -10% = 34.2)
Note that, in C, a log function can only be defined for a specific type. Therefore, this log "function" takes only int arguments.
#define log(x)printf("log("#x") %d",x)

A more general solution specifies how to print the argument, in addition to the argument itself:
#define lg2(f,x)printf("lg2("#x") "f,x)

which would be used as e.g. lg2("%s", "I'm a string"); or lg2("%f", 3.1415).

I don't think the final brackets around x are necessary.

@ace: I thought they might be needed if the user puts in some odd characters in the argument, but upon reflection I think you're right. I'll remove them.

Python (65 -10% = 58.5)
This assumes your code is in a file (it produces odd output if invoked in the interactive interpreter):
import traceback as t
def log(x):print t.extract_stack()[-2][3],x

It has been tested on Python 2.7.6.
Example:
def foo():
    x = 1
    log(x)
    for i in xrange(10):
        log(x+i+1)
    return x

log(foo())

outputs
log(x) 1
log(x+i+1) 2
log(x+i+1) 3
log(x+i+1) 4
log(x+i+1) 5
log(x+i+1) 6
log(x+i+1) 7
log(x+i+1) 8
log(x+i+1) 9
log(x+i+1) 10
log(x+i+1) 11
log(foo()) 1

Nice! Got to say, this is the kind of crazy stuff that interests me as a programmer (negative index on a native function :O ) :P wonders off to find some docs

C++ 121 71 67 -10% = 60.3
#include<iostream>
#define log(x)std::cout<<"log("#x") "<<(x)<<"\n"

Used like this:
int main() {
    int i = 777;
    int j = 333;
    log(i);
    log(i+j+1);
}

Outputs:
log(i) 777
log(i+j+1) 1111

You can remove 30 char and make a one-liner if you write it in C instead of C++: #define log(x)printf("log(%s) %d\n",#x,x), but that will only work of integers.

@ace: then it only works for one type. (Also, this is the solution I proposed, see below)

@nneonneo I hate it when I forgot to refresh before posting a comment.

Rebol3 - 31.5 (35 - 10 %)
Here is a simple implementation shortened from @draegtun that works well for numbers:
log: func[p][print[{log[}p{]}do p]]

Running it outputs:
>> log: func[p][print[{log[}p{]}do p]]
>> i: 777
>> j: 333
>> log [i]
log[ 777 ] 777
>> log[i + j + 1]
log[ i + j + 1 ] 1111

It can be much more flexible (for displaying the form of non-number types) at 42.3 chars (47 - 10%)
log: func[p][print[{log}mold p mold/only do p]]

The output:
>> log: func[p] [print[{log}mold p mold/only do p]]
>> log [join "4" 4]
log [join "4" 4] "44"  ;; shows a string
>> log [1 + 2]
log [1 + 2] 3

Javascript (325)
I think this is the log function you are looking for:
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}

Usage
<script>
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}

function doSomething() {
  var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
var message = "...or just do it out here";
log(message + "!");
</script>

Output
log(a) = 123
log(b) = Hello, I am TrungDQ!
log(message + "!") = ...or just do it out here!

Long code
<script>
function log(msg) {
  // Get the line number and offset of the line where is function is called
  var lineInfo = (new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];
  var lineNum = lineInfo.split(':')[1];
  var charOffset = parseInt(lineInfo.split(':')[2]);

  // Get the file source
  request = new XMLHttpRequest();
  request.open('GET', window.location.href, true);

  request.onload = function() {
    // Get file source code
    var response = request.responseText;
    // Get the `log` line
    var line = response.split('\n')[lineNum - 1];
    // Get the `log` statement
    var logStatement = line.substr(charOffset - 1).split(';')[0];
    // Print it
    console.log(logStatement + ' = ' + msg);
  };
  request.send();
}

function doSomething() {
  var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
</script>

Only works when the script is put inside <script> tag which is put in .html document because it sends a request to location.href to get the source code. JSfiddle, F12 Dev Tool Console, embbed .js files won't work, I am trying to make it available everywhere...
Anyway, this question is interesting.

I'm little skeptical this is cross browsers.

Scala - (221 - 10%) = 198.9
Yay macros! This is actually exactly the type of stuff they're for.
import language.experimental.macros
def log(p:Any)=macro l
def l(c:reflect.macros.Context)(p:c.Expr[Any])={import c.universe._;reify{println("log("+(c.Expr[String](Literal(Constant(show(p.tree)))).splice)+") "+p.splice)}}

Readable version:
import language.experimental.macros
def log(p: Any) = macro l
def l(c: reflect.macros.Context)(p: c.Expr[Any]) = {
  import c.universe._
  val inputString = show(p.tree)
  val inputStringExpr = c.Expr[String](Literal(Constant(inputString)))
  reify {
    println("log(" + (inputStringExpr.splice) + ") " + p.splice)
  }
}

Example:
log(1)
val x = 3
log(x)
val y = 4
log(x+y)

Outputs:
log(1) 1
log(x) 3
log(x.+(y)) 7

Since addition is a method call in Scala, it adds that verbose syntax back in, but it's pretty close! It's also a bit more verbose in a couple of other cases.

Wow, that's quite interesting to see@the addition of the function. So much cool stuff to learn :D

bash (21 - 10% = 18.9)
This:
alias log=echo;set -v

Then use log like you would use echo:
log $((1+1))

or
A=2
B=3
log $((A+B))

This method will do all what is required; as a bonus, some extra information will also be printed, but no explicit rule forbid it.

BASH
Arguments are not passed using "(...)" in BASH, so I let the output of 'log()' fit that style:
$ log(){ echo "$FUNCNAME $@: $(($@))"; }
$ i=333
$ j=777
$ log i
log i: 333
$ log i+j+1
log i+j+1: 1111

$((...)) can be $[...] instead but I did not count the chars, so it doesn't matter up to now.

Tcl, 42.3 (47 - 10%)
proc log c {puts [dict g [info fr -1] cmd]\ $c}

Usage:
set i 777
set j 333
log $i  ;#outputs: "log $i 777"
log [expr {$i+$j+1}] ;#outputs: "log [expr {$i+$j+1}] 1111"

Edit: small improvement

Clojure
(defmacro log[x] `(let [x# ~x] (println "log("'~x")" x#)))

Homoiconicity has its benefits!
To use:
(def i 777)
(def j 333)
(log i) ;Prints log( i ) 777
(log (+ i j 1)) ;Prints log( (+ i j 1) ) 1111

Let's see what's happening with macroexpand:
(macroexpand '(log (+ i j 1)))
;; Prints the following:
(let* [x__1__auto__ (+ i j 1)] (clojure.core/println "log(" (quote (+ i j 1)) ")" x__1__auto__))

If you quote x, do you really need to use an intermediate gensym (ie. x#)? I think you will only evaluate the expression once (btw, I am no Clojure expert)

Julia, 51*0.9=45.9
julia> x=4
4
julia> macro log(x) println("log($x) $(log(eval(x)))") end
julia> @log(x)
log(x) 1.3862943611198906

Alternatively, but not meeting the rules
julia> @show log(x)
log(x) => 1.3862943611198906

Common Lisp - 119.7 (133 -10%)
(defmacro @(&whole f &rest r)(let((g(gensym)))`(let((,g(multiple-value-list,@r)))(progn(format t"~s~{ ~a~}
"',f,g)(values-list,g)))))

Named @ because log is the standard logarithm function and locked by default (at least on SBCL). Also, @ is only one character long.
Acts as a progn, taking a variable number of arguments, but prints to standard output. In real applications, I would probably signal a condition with  an S-expression instead of printing space-separated output.
Contrary to the existing Clojure solution, we ultimately returns the value of the logged expression, so that (@ x) can be used whenever x is used.
Printing uses prin1, which outputs a read-able string. This is useful when trying to reproduce logged expressions.
Handles all possible types (see C answer)
Takes into account mutliple values
Does not produce different outputs (see Scala answer)
Works from a file and from REPL (See Pyhton answer)
Does not require browser/interpreter trick (Python traceback, Javascript request)

Sample outputs:
CL-USER>(@ (+ 3 2))   ; user input
(@ (+ 3 2)) 5         ; printed output
5                     ; result of expression

CL-USER> (@ (values 3 4))  ; input
(@ (VALUES 3 4)) 3 4       ; logging
3                          ; first value
4                          ; second value

CL-USER>(@ (round 3.4))
(@ (ROUND 3.4)) 3 0.4000001
3                          ; rounded value
0.4000001                  ; delta

And finally, if I log the above defmacro, I have the ungolfed version:
CL-USER> (@ (defmacro @(&whole f &rest r)(let((g(gensym)))`(let((,g(multiple-value-list,@r)))(progn(format t"~s~{ ~a~}
"',f,g)(values-list,g))))))
STYLE-WARNING: redefining COMMON-LISP-USER::@ in DEFMACRO
(@
 (DEFMACRO @ (&WHOLE F &REST R)
   (LET ((G (GENSYM)))
     `(LET ((,G (MULTIPLE-VALUE-LIST ,@R)))
        (PROGN
         (FORMAT T ,"~s~{ ~a~}
"
                 ',F ,G)
         (VALUES-LIST ,G)))))) @
@ ; actual result

PHP 138
You can't redeclare log in PHP without using another module (APD) so I used logg instead, i can resubmit with log example if needed. That's minor, but more sinful i guess is that this assume the log function is on a line by itself. I can update my answer as dictated by comments.
<?php function logg($v){$b=debug_backtrace()[0];$h=fopen($b['file'],"r");for($i=0;$i<$b['line']&&$l=fgets($h);$i++);echo trim($l)." $v";}

example output:
for ($i=1; $i<10; $i++) {
  $j=$i+1;
  $k=$j+1;
  logg($i+$j+$k);
  echo "\n";
}
/*
logg($i+$j+$k); 6
logg($i+$j+$k); 9
logg($i+$j+$k); 12
logg($i+$j+$k); 15
logg($i+$j+$k); 18
logg($i+$j+$k); 21
logg($i+$j+$k); 24
logg($i+$j+$k); 27
logg($i+$j+$k); 30
*/

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


text:
Optimizing the telephone keypad
There seems to be this ongoing craze about people tediously learning new keyboard layouts like Dvorak or Neo because it supposedly makes them more productive. I argue that switching keyboard layouts is a bad idea, because it can take you months to get up to speed, and when you're finially 5% faster than the rest, you're screwed if you need to type on a computer that isn't your own.
Also, all these people forget where the real bottleneck in modern communication lies - the telephone keypad.
This is how your average telephone keypad looks like:

Letter 'r' is the third letter on button 7; so if you were to type the letter 'r' on a mobile phone, you would press button 7 three times, for 's' you'd press it 4 times, and for 'a' you'd press button 2 once.
Considering this, putting 'e' after 'd' was probably a bad decision - 'e' is the most commonly used letter in the english alphabet, so, if you were to label button 3 "EDF" instead of "DEF", you would save quite a lot of keystrokes.
Moreover, you've probably experienced yourselves that typing 2 letters that share the same button is a nuisance - if you want to write "TU", you can't just hit 8 three times, because that would result in 'V'. So usually you'd write 'T', then hit space, then hit backspace, and then write 'U', which equals 5 button presses instead of 3.

TL;DR
Given these two rules:

A letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label
Writing two letters that are typed using the same button requires an additional 2 button presses

What's the telephone keyboard layout that requires the least amount of button presses, given a specific text?
You should only use the buttons 2-9, 1 and 0 are reserved for special symbols.
Input
The text which you should find the optimal layout for is supplied via stdin. You don't need to handle anything other than the lowercase alphabet and can assume that the input consists of only that.
You can also assume that the input text is reasonably large and every letter is in there at least once, if that helps.
Output
I don't want to put too many constraints on the output, since that sometimes gives some languages advantages over others; so however your language shows arrays is fine, alternatively you can seperate each label with a newline.
There may be multiple possible optimal layouts, you can print any one of them.
Here's a simple example:
>> echo "jackdawslovemybigsphinxofquartz" | foo.sh
ojpt
avhz
cen
skm
dyf
wbq
ixu
lgr

Bonus Points
-35 if your algorithm is not brute-forcing all possible layouts (I'm looking at Haskell's `permutations' here)
-3 if your code fits inside a text message (140 chars) and you post a pic of you sending your code to a friend.
This is my first challenge on StackExchange. I'd be happy to hear whether you like it, or have any other feedback about it!

Welcome on CodeGolf.SE! I don't see any problem with your question, but it's generally a good idea to post your challenge in the sandbox first to get some feedback and remove ambiguities before posting on the main site.

Ah that's cool, I definitely will in the future.

My telephone can send a single 60-character SMS, but does not support brackets properly, am I out of the bonus?

@hexafraction Homing pigeons count aswell.

Nice question! I don't think anybody will be able to avoid the -35 bonus. Even if we restrict ourselves to layouts having 4 characters on two of the keys and 3 on all remaining 6, there are 26! / (2! * 6!) = 280,063,514,671,253,913,600,000 > 2^77 unique permutations, counting simple rearrangements of the keys only once.

I wonder why people got so different results

Also, I ask if you people could print the number of button-pressing of your solution. So we'll see who found the best one!

Perl, 333
$_=<>;$c{$&}++while/./g;@c=sort{$c{$b}<=>$c{$a}}keys%c;$d{$&.$1}++while/.(?=(.))/g;sub f{my$x=shift;if(my$c=pop@$x){for(grep!$_[$_],0..7){my@y = @_;$y[$_]=$c;f([@$x],@y)}}else{for(0..7){$z=$_[$_];$c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]}}$c<$m?($m=$c,@n=@_):1}}while(@c){$m= ~0;f[splice@c,0,8];push@{$a[$_]},$n[$_]for 0..7}print@$_,$/for@a

Here's an attempt to optimize for rule #2. After my comment, above, and in lieu of answers taking that rule into account (cf. high question rating), I thought that I owe some effort here...
Solutions that don't optimize for rule #2 can produce output very far from optimal. I checked long natural English text ("Alice in Wonderland", actually), pre-processed (lower case letters only), and e.g. Perl script from OJW's answer, result being
2: ermx
3: tdfz
4: alp
5: oub
6: ick
7: nwv
8: hgj
9: syq

er alone ruins it, plus some other pairs should never have ended on the same key...
Btw, zxqjvkbpfmygwculdrshnioate are letters sorted, frequency ascending, from that text.
If we try to solve it easy way (hoping for -35 bonus, maybe) and place letters one by one, choosing available key by minimal pair-wise count, we can end with e.g.:
slbx
hdmz
nrf
iuj
ogv
awk
tcp
eyq

I don't post code for this (wrong) solution here. E.g., note, c is more frequent than w and is placed first. tc (ct) pairs are obviously less frequent than ac (ca) - 43+235 against 202+355. But then w ends up with a -- 598+88. We end with pairs aw and tc (964 total), though it would be better ac and tw (635 total). Etc..
So, next algorithm tries to check each 8 remaining (or 2, if last) most frequent letters against letters already on the keypad, and to place them so that pair-wise count is minimal.
$_=<>;                          # Read STDIN.
$c{$&}++while/./g;              # Count letters (%c hash).
@c=sort{$c{$b}<=>$c{$a}}keys%c; # Sort them by frequency, ascending
$d{$&.$1}++while/.(?=(.))/g;    # (@c array), and count pairs (%d hash).

                                # Next is recursive sub that does the job.
                                # Some CPAN module for permutations
                                # would probably do better...
                                # Arguments are reference to array of what's
                                # left un-placed of current 8-pack of letters,
sub f{                          # and 8 element list of placed letters
    my$x=shift;                 # (or undefs).
    if(my$c=pop@$x){            # Pop a letter from 8-pack (if anything left),
        for(grep!$_[$_],0..7){  # try placing it on each available key, and
            my@y = @_;          # call sub again passing updated arguments.
            $y[$_]=$c;
            f([@$x],@y)
        }
    }else{                      # If, OTOH, 8-pack is exhausted, find sum of
        for(0..7){              # pairs count of current permutation (@_) and
            $z=$_[$_];          # letters placed in previous rounds (8-packs).
                                # @a is "array of arrays" - note, we didn't
                                # have to initialize it. First "8-pack" will
                                # be placed on empty keypad "automatically".
                                # We re-use undefined (i.e. 0) $c.

            $c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]}
        }
        $c<$m                   # Is sum for current placement minimal?
            ?($m=$c,@n=@_)      # Then remember this minimum and placement.
            :1
    }
}

while(@c){
    $m= ~0;                         # Initialize "minimum" with large enough
    f[splice@c,0,8];                # number, then call sub with each 8-pack
                                    # (and empty list of placed letters
                                    # from current round). On return,
                                    # @n will have optimal arrangement.
    push@{$a[$_]},$n[$_]for 0..7    # Then place it permanently on keypad.
}
print@$_,$/for@a                    # Show us what you've done.

Result is:
sdfz
hlmx
nrv
iyp
ogk
acq
twb
euj

I don't like the ac pair (The Cat being one of the characters, after all), but, still that's optimal letter placement for English, if my code is not wrong. Not exactly 'golfing' effort, just some working solution, ugly or not.

Python3, it's Montecarlo Time!
To solve this problem, I first count how many "clicks" you need with the default keyboard (intially: abc,def,ghi,jkl,mno,pqrs,tuv,wxyz). Then I modify this keyboard and see if it is cheaper (the text is written in less clicks). If this keyboard is cheaper, then it becames the default one. I iterate this process 1M times.
To change the keyboard I first decide how many changes to make (the maximum number of changes is the total number of letters n the keyboard). Then, for every switch, I choose two buttons and two positions and I transfer a character from the first position to the second one.
The maximum number of switches per time is the number of letters in the keyboard becouse it is the minimum number of changes you need to switch from two complete different keyboards. (I want that it is always possible to switch from one keyboard to any other one)
The output of  echo "jackdawslovemybigsphinxofquartz" | python .\myscript.py is:
61 ['anb', 'sef', 'hjc', 'iykl', 'odm', 'qgr', 'tuxv', 'wpz']

Where 61 is the number of button pressed to compose a given message.
Characters (no spaces and no comments): 577
I know its long but I'm really new to this stuff.
from random import *
S=['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
def P(L): # perform a switch of the keys of the keyboard:to switch from a given keyboard to another, the maximum number of exchanges is the number of the keys.
    R=randint
    N = len(''.join(L))
    W = randint(1,N)   # decide how many switches to perform
    EL = list(L)
    for i in range(0,W):
        B1=R(0,len(EL)-1)   # decide what buttons are considered in the switch
        B2=R(0,len(EL)-1)
        if len(EL[B1])==0: continue
        P1=R(0,len(EL[B1])-1)       # decide what letter to switch and where
        if len(EL[B2])==0: P2=0
        else:   P2=R(0,len(EL[B2])-1)
        C1 = EL[B1][P1]
        EL[B1]=EL[B1].replace(C1,'')
        EL[B2]=EL[B2][:P2]+C1+EL[B2][P2:]
    return EL
def U(L,X): # count how many clicks you need to compose the text X
    S=0
    Z=' '
    for A in X:
        for T in L:
            if A in T and Z not in T: S+=1+T.index(A)
            if A in T and Z in T: S+=3+T.index(A) # if the last character was in the same button..here the penality!
        Z=A
    return S
X=input()
n_iter=10**6
L = list(S)
cc=U(L,X)
print(cc,L)
for i in range(0,n_iter): #do some montecarlo stuff
    cc=U(L,X)
    pl=P(L)
    pc=U(pl,X)
    if(cc>pc):
        L=pl
        print(pc,L)

I found it so funny that I decided to try this algorithm with LO HOBBIT (I have an original copy at home too!). It has 383964 letters and these are the couple clicks vs keypad that I'm finding:
909007 ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
879344 ['abkc', 'def', 'gqhi', 'jl', 'mno', 'rs', 'tupv', 'wxyz']
861867 ['abg', 'def', 'qhyi', 'jcl', 'mno', 'r', 'tupxv', 'swkz']
851364 ['abg', 'e', 'qchi', 'jyl', 'mn', 'dr', 'tupxv', 'sowkfz']
829451 ['ag', 'ef', 'qchi', 'jyl', 'mn', 'dbr', 'tupxv', 'sowkz']
815213 ['amg', 'ef', 'qch', 'ojyl', 'i', 'dbnr', 'tupxv', 'swkz']
805521 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'dbnr', 'tupxv', 'swkz']
773046 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'bnr', 'tupxv', 'dswkz']
759208 ['amg', 'eqf', 'ch', 'ojyl', 'i', 'bnr', 'tupxv', 'dswkz']
746711 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tupxv', 'dwz']
743541 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tpxv', 'dwuz']
743389 ['ag', 'ekq', 'clh', 'sojy', 'i', 'nmfr', 'tpxbv', 'dwuz']
734431 ['ag', 'ekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dowumz']
705730 ['ag', 'oekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dwumz']
691669 ['ag', 'oekq', 'lh', 'nsjy', 'ic', 'rf', 'tpxbv', 'dwumz']
665866 ['ag', 'hokq', 'el', 'nsjy', 'ic', 'rbf', 'tpxv', 'dwumz']
661610 ['agm', 'hokq', 'e', 'nsj', 'ilc', 'rbf', 'tpyxv', 'dwuz']

So I claim this last one is one of the most practical keypad (in terms of clicks).

How do you know if it is optimal?

Montecarlo does not work in this way. It only put you nearer and nearer to the optimal solution. But let say, if in 1 million tries your solution does not change..then you're probably using the optimal one. (or you're not moving enough from this "local minimum")

So for challenges, we only need it to work most of the time then?

'Last one' requires 6 clicks to type 've' or 'ev'. But if you change these buttons to ev and tpyx, then typing 've' ('ev') will take only 5 clicks. Maybe 5 letter buttons should not be allowed at all. Maybe 1 million iterations should be tried after each success, not in total.

@PyRulez I realized that this would not be an easy problem to find an optimal solution for (except if you try all possible solutions, which I was hoping to prevent with that -35 bonus), so I actually really dig this approach.

Interesting method, but maybe this task is not exactly its domain. I checked, and, for 'Alice', default keyboard requires 291613 clicks. Optimized with my program - 195597. With 'Monte Carlo' approach I didn't get less than 207000 clicks in more than 5 million iterations. And, it's better to swap letters,  i.e. 2x4 + 6x3 layout remaining constant.

I love it! Counting spaces but with I can get to 573 characters with not too extreme golfing http://pastebin.com/9HEazR35

Well if you just want the most popular characters assigned to the bins 2-9, Perl can do that in 127 chars...
foreach(split /\s*/,<>){$x{$_}++}
foreach(sort{$x{$b}<=>$x{$a}}keys %x){$o{$n++%8}.=$_}
for(0..7){printf "%d: %s\n",$_+2,$o{$_}}

giving something like:
echo "jackdawslovemybigsphinxofquartz" | perl ./keypad.pl
2: ajeb
3: iynz
4: suv
5: ohm
6: wkl
7: rgp
8: xfc
9: dtq

Or print it all on one line, removing 12 characters:
foreach(split /\s*/,<>){$x{$_}++}
foreach(sort{$x{$b}<=>$x{$a}}keys %x){$o[$n++%8].=$_}
print join",",values@o,"\n";

you can easily trim this to 100 chars: $x{$_}++for split/\s*/,<>;map$o{$n++%8}.=$_,sort{$x{$b}<=>$x{$a}}keys%x;print map"$_:".$o{$_-2},2..9

JavaScript, 192 - 35 = 157
Just noticed the repeating characters rule; this doesn't take that into account. But as @mniip noted in his answer:

One might argue that this does not optimize for rule 2, but it does put most frequent letters on different keys.

o={}
a=[]
b=['','','','','','','','']
i=-1
s.split('').forEach(function(x){o[x]=o[x]?o[x]+1:1})
for(x in o)a.push([o[x],x])
a.sort().reverse().forEach(function(x){b[i=(i+1)%8]+=x[1]})
alert(b)

This would have probably been in Ruby, but I'm not at home and am being forced to use Internet Explorer (eww). But hey, it's sometimes fun using languages terrible at golfing to golf! ;)
Sample output (for your input):
avlc,sukb,otj,irh,zqg,ypf,xne,wmd

Since JS has no STDIN, the program assumes that input is stored in variable s.

Are you optimizing with this in mind as well: "Writing two letters that are typed using the same button requires an additional 2 button presses"

Re: last edit. I think the output for 'abcdefghia' is not exactly optimal.

@VadimR "You can also assume that the input text is reasonably large and every letter is in there at least once"

I know. 'azbcdefghizjklmnopqzrstuvwxyz'

You can optimise b=['','','','','','','',''] to b=[x='',x,x,x,x,x,x,x], s.split('') to s.split(x) and o[x]=o[x]?o[x]+1:1 to o[x]=-~o[x].

Also, you can optimise i=(i+1)%8 to (i+=1)%8.

Haskell, 160 - 35 = 125
import Data.List
import GHC.Exts
main=interact f where f s=show$transpose$map($sortWith(\x->length$filter(/=x)s)['a'..'z'])[t,t.d,t.d.d,d.d.d];t=take 8;d=drop 8

Example:
$ runhaskell % <<< "jackdaws loves my big sphinx of quartz"
["afpy","sgqz","ihr","ojt","bku","clv","dmw","enx"]
$ </usr/share/dict/propernames tr A-Z a-z | runhaskell %
["atjx","edgq","rhb","nmp","iyv","lcf","ouw","skz"]

One might argue that this does not optimize for rule 2, but it does put most frequent letters on different keys.

Python (119-35=84):
Assuming the string is a variable a, and only contains lowercase letters:
for h in range(8): print h+2,zip(*sorted([(__import__("collections").Counter(a)[d],d) for d in set(a)])[::-1])[1][h::8]

ungolfed:
import collections

#a="jackdawslovemybigsphinxofquartz"
a=__import__("string").lowercase

b=collections.Counter(a)

c=set(a)

d=[(b[d],d) for d in c]

e=sorted(d)

f=e[::-1]

g=zip(*f)[1]

for h in range(8): print h+2,g[h::8]

PYG (76-35=41):
Aaah, we can drop the enourmous import. Again, this assumes the stripped string is in a.
for h in R(8): print h+2,Z(*S([(CC(a)[d],d) for d in Se(a)])[::-1])[1][h::8]

source: Stack Exchange

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

authors: صالح عبدالله

sort: votes


text:
Books full of nonsense: Identify limericks
As we all know, limericks are  short, five-line, occasionally-lewd poems with an AABBA rhyming scheme and an anapestic meter (whatever that is):

Writing a Limerick's absurd
  Line one and line five rhyme in word
  And just as you've reckoned
  They rhyme with the second
  The fourth line must rhyme with the third

You are tasked to write the shortest program that, when fed an input text, prints whether it thinks that the input is a valid limerick. Input can either be on the command line or through standard input, at your option, and output could either be a simple "Y"/"N" or a confidence score, again at your option.
Here's another example of a correct limerick:

There was a Young Lady whose eyes
  Were unique as to colour and size
  When she opened them wide
  People all turned aside
  And started away in surprise

But the poem below is clearly not a limerick, since it doesn't rhyme:

There was an old man of St. Bees
  Who was stung in the arm by a wasp.
  When asked, "Does it hurt?"
  He replied, "No, it doesn't,
  I'm so glad that it wasn't a hornet."

Nor is this one, as the meter is all wrong:

I heard of a man from Berlin
  Who hated the room he was in
  When I asked as to why
  He would say with a sigh:
  "Well, you see, last night there were a couple of hoodlums around who were celebrating the Bears winning the darned World Cup, and they were really loud so I couldn't sleep because of the din."

Clues
Here are some of the clues you could use to decide whether or not your input is a limerick:

Limericks are always five lines long.
Lines 1, 2 and 5 should rhyme.
Lines 3 and 4 should rhyme.
Lines 1, 2 and 5 have around 3x3=9 syllables, while the third and fourth have 2x3=6 syllables

Note that none of these except the first are hard-and-fast: a 100% correctness rating is impossible.
Rules

Your entry should at the very least correctly categorize examples 1 through 3 in a deterministic fashion.
You are allowed to use any programming language you would like, except of course programming languages specifically designed for this contest (see here).
You are not allowed to use any library except your programming language's standard offerings.
You are allowed to assume that this file, the CMU Sphinx pronounciation dictionary, is in a file called 'c' in the current directory.
You are not allowed to hard-code for the test inputs: your program should be a general limerick categorizer.
You are allowed to assume that the input is ASCII, without any special formatting (like in the examples), but your program should not be confused by interpunction.

Bonuses
The following bonuses are available:

Your program outputs its result as a limerick? Subtract 150 characters length bonus!
Your program also correctly identifies sonnets? Subtract 150 characters extra length bonus!
Your program outputs its result as a sonnet when used on a sonnet? Subtract 100 characters additional extra length bonus!

Finally...
Remember to mention which bonuses you think you deserve, if any, and subtract the bonus from your number of characters to arrive at your score. This is a code golf contest: the shortest entry (i.e. the entry with the lowest score) wins.
If you need more (positive) test data, check out the OEDILF or the Book of Nonsense. Negative test data should be easy to construct.
Good luck!

This should be a code-challenge because of the bonuses. Please read the tag descriptions

@user80551 Consensus on meta appears to be otherwise.

I've clarified the nature of the bonuses, I hope that clears up the confusion.

Goooooooo Bears!

I don't understand the bonuses. How am I supposed to output "Y" in the form of a limerick?

@squeamishossifrage It doesn't have to be a literal "Y", just some way for us to tell what your program's decision was. As for the bonus: you get the bonus if the way you choose to display your program's decision is a valid limerick (in both the yes and no cases).

Well, this is boring. I'm starting a bounty.

Seems like your entry is hard to beat, Mathieu! I'll double the bounty.

Oops, looks like I can't do that. Sorry.

@WanderNauta: well there's always these Perl answers which are much shorter than any other one... so maybe there's something lying there

@MathieuRodic As I said in the Sandbox, I'm secretly hoping for someone who's insane enough to throw GolfScript against this question - but I guess Perl would work as well.

Python: 400 - 150 - 150 = 100
The shortest script I could come up with is that one...
import re,sys;f,e,c=re.findall,lambda l,w:f('^'+w.upper()+'  (.+)',l),lambda*v:all([a[i]==a[v[0]]for i in v]);a=[sum([[e(l,w)[0].split()for l in open('c')if e(l,w)][0]for w in f(r'\w+',v)],[])[-2:]for v in sys.stdin];n=len(a);print n==14and c(0,3,4,7)*c(1,2,5,6)*c(8,11)*c(9,12)*c(10,13)*"Sonnet"or"For a critic\nOf limerick\nWell-equipped\nIs this script.\n%s limerick!"%(n==5and c(0,1,4)and c(2,3))

...but don't even try it. It parses the provided dictionary for every word it meets, thus being very slow. Also, an error is generated whenever a word is not in the dictionary.
The code still meets the requirements though: recognizing whether the text passed via stdin is a limerick, a sonnet, or neither of those.
With only 20 more characters, here is the optimized version:
import re,sys;f,e,c=re.findall,lambda l:f(r'^(\w+)  (.+)',l),lambda*v:all([a[i]==a[v[0]]for i in v]);d={e(l)[0][0]:e(l)[0][1].split()for l in open('c')if e(l)};a=[sum([d.get(w.upper(),[])for w in f(r'\w+',v)],[])[-2:]for v in sys.stdin];n=len(a);print n==14and c(0,3,4,7)*c(1,2,5,6)*c(8,11)*c(9,12)*c(10,13)*"Sonnet"or"For a critic\nOf limerick\nWell-equipped\nIs this script.\n%s limerick!"%(n==5and c(0,1,4)and c(2,3))

Features

able to recognize sonnets (-150)
answers to limericks with a limerick (-150)
relatively fast: only one file parsing per execution

Usage
cat poem.txt | python poem-check.py

3 different outputs are possible:

a limmerick saying the input is one if it is the case
a limmerick saying the input is not one if it is the case
"Sonnet" if the input is recognized as such

Expanded code with explanations
import re, sys

# just a shortened version of the 're.findall' function...
f = re.findall
# function used to parse a line of the dictionary
e = lambda l:f(r'^(\w+)  (.+)', l)

# create a cache of the dictionary, where each word is associated with the list of phonemes it contains
d = {e(l)[0][0]:e(l)[0][1].split(' ') for l in open('c') if e(l)}

# for each verse (line) 'v' found in the input 'sys.stdin', create a list of the phoneme it contains;
# the result array 'a' contains a list, each item of it corresponding to the last two phonemes of a verse
a = [sum([d.get(w.upper(), []) for w in f(r'\w+',v)],[])[-2:] for v in sys.stdin]

# let's store the length of 'a' in 'n'; it is actually the number of verses in the input
n = len(a)
# function used to compare the rhymes of the lines which indexes are passed as arguments
c = lambda*v:all([a[i] == a[v[0]] for i in v])

# test if the input is a sonnet, aka: it has 14 verses, verses 0, 3, 4 and 7 rhyme together, verses 1, 2, 5 and 6 rhyme together, verses 8 and 11 rhyme together, verses 9 and 12 rhyme together, verses 10 and 13 rhyme together
if n==14 and c(0,3,4,7) and c(1,2,5,6) and c(8,11) and c(9,12) and c(10,13):
    print("Sonnet")
else:
    # test if the input is a limerick, aka: it has 5 verses, verses 0, 1 and 4 rhyme together, verses 2 and 3 rhyme together
    is_limerick = n==5 and c(0,1,4) and c(2,3)
    print("For critics\nOf limericks,\nWell-equipped\nIs this script.\n%s limerick!", is_limmerick)

Looks cool! I haven't tested it yet, but are you sure this takes input "either on the command line or through standard input" (see question)? If not, you should add that (probably a sys.stdin.read() or an open(sys.argv[1]).read() somewhere) and recount.

Okay! Corrected it :)

How does the algorithm check for rhymes?

With the help of the file provided by Wander Nauta in the question! It really helped.

@DavidCarraher: I added some explanation to the code, and made it a bit more readable...

Fine. Even better if you add examples of its output.

Clever! I'm not sure if I can award the output-is-a-limerick bonus though, as it only outputs a limerick if the input is a limerick and just plain False otherwise.

Well... I tried to write two limericks and one sonnet in less than 250 characters, but it seems a tidbit out of reach. Would a haiku do?

Nope, has to be limericks. Maybe you could use some kind of compression? Dictionary-based, perhaps?

Dictionary-based compression? Already considered, tried, and failed. The dictionary contains 115824 entries, so most indexes are as long as the original word. Neither will lz or bz2 give satisfying results...

Then I'm afraid you can't have the bonus - sorry...

I edited the post... it now displays the 'nay' as a limerick too.

Neat! A shame I can't upvote you twice.

ECMAScript 6 (138 points; try in Firefox):
288 - 150 points bonus for including limerick (pinched from @MathieuRodic).
a=i.split(d=/\r?\n/).map(x=>x.split(' '));b=/^\W?(\w+) .*? (\w+\d( [A-Z]+)*)$/;c.split('\r\n').map(x=>b.test(x)&&eval(x.replace(b,'d["$1"]="$2"')));e=f=>d[a[f][a[f].length-1]];alert('For critics\nOf limericks,\nWell-equipped\nIs this script.\n'+(a[4]&&e(0)==e(1)&e(0)==e(4))+' limerick!')

Notes:
Expects the variable c to contain the contents of the dictionary file, as you can't read files in plain ECMAScript.
ECMAScript doesn't have standard input, but prompt is generally considered "standard input"; however, as prompt converts line breaks to spaces in most (if not all) browsers, I'm accepting input from the variable i.
Ungolfed code:
// If you paste a string with multiple lines into a `prompt`, the browser replaces each line break with a space, for some reason.
//input = prompt();

// Split into lines, with each line split into words
lines = input.split('\n').map(x => x.split(' '));

dictionaryEntryRegEx = /^\W?(\w+) .*? (\w+\d( [A-Z]+)*)$/;
dictionary = {};
// Split it into
c.split(/\r?\n/).map(x => dictionaryEntryRegEx && eval(x.replace(dictionaryEntryRegEx, 'dictionary["$1"] = "$2"')));

// Get the last word in the line
getLastWordOfLine = (lineNumber) => dictionary[line[lineNumber][line[lineNumber].length - 1]]

alert('For critics\nOf limericks,\nWell-equipped\nIs this script.\n' + (lines[4] && getLastWordOfLine(0) === getLastWordOfLine(1) && getLastWordOfLine(0) === getLastWordOfLine(4)) + ' limerick!');

Neat! This doesn't take 'input on the command line or through standard input', though, which is required by the question. Maybe you could rewrite it to use Node.js or something.

@WanderNauta Thank you. Please see the latest edit, as I explain why I'm not using the standard input.


text:
Recognizing Repetition in strings
Create a program which gets an input from the user and tells the user what repetitions exist in the it. A few examples of inputs the user could give and outputs they should get:

Input: 112211221122
Output: 1122 * 3

Or:

Input: 123123
Output: 123 * 2

Or:

Input: 1234
Output: No repetitions found!

Tiebreaker: if your code can recognize more than one repetition:

Input: 123123456456
Output: 123 * 2, 456 * 2

Then you win if you are tied for 1st place with someone's code who doesn't recognize more than one repetition.
If your code requires a limit on the repetition length, it should be able to recognize repetitions at least 4 characters long. This is a code-golf question, so the shortest code wins (but please explain the code in your answer)

Ahem ... I see a clear pattern in your last example.

You are asking for repetition, not Patterns. Also, please clarify on inputs like 123123456456. Shuld the output be 123 * 2 456 * 2 or No repetitions found!?

@Quincunx You're absolutely right. I don't know why I was thinking patterns.

123123123123 -> 1234 or 1231232? Also, 1234 is 1234*1.

@Doorknob it should break it down into the smallest components (so 123*4). I know 1234 is itself times 1, but that isn't repetition.

What about nested repetition? aabbaabb. Is it a*2 b*2 a*2 b*2 or aabb * 2? Or a*2 b*2 *2?

@KnightOfNi please specify the extra points.

May the answer assume all characters in the strings are digits like in your own examples? I perfectly understand that your question is a string-question, but sometimes assuming such a thing can lead to interesting answers.

@MukulKumar If your code is tied or close to someone else's but you have the "extra points," the question goes to you.

@m.buettner The first and third of your examples are valid, but the second is not completely broken down.

Examples do not make a spec. Please write an actual spec and then move your examples to a section for test cases.

ass. i had an answer, and now i can't post it.

I'll post it anyways -> glot.io

@KnightOfNi so the extra points don't have any value? (like -30 bytes or -20%)

Possible duplicate: http://stackoverflow.com/questions/10055035/to-find-all-the-repeating-substring-in-a-given-string

The tie-break is silly. If code of equal length, then not including the code for the optional task will make it shorter, so no-one will include that code. 1234123412341234 is 12344 but 112211221122 is 11223 not 1*2 (smallest component). By duplicating characters without explaining how that works for the matching, you get contradictions in the examples.

Perl, 74 (73 + 1) bytes

Assumes -n flag (+1 byte).
say is a feature of version 5.10 and needs to be enabled.
This can be done by flag -M5.010 or easier with -E instead of -e.
Therefore I follow the other Perl answer in the calculation method of the costs.
It also reports repetitions as long as they do not overlap.

s/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"

Usage and tests
echo 112211221122 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
1122 * 3

echo 123123 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
123 * 2

echo 1234 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
No repetitions found!

echo 123123456456 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
123 * 2
456 * 2

Ungolfed with comments
s/
    (.+)              # catches the repeat unit
    (?{ $i=1 })       # initialize counter $1 with 1
    (
        \1            # next repetition
        (?{ $i++ })   # increase counter
    )+                # repeat unit must appear at least twice
/
    say "$1 * $i"     # print result as a side effect of the replacement;
                      # "say" adds a new line at the end
/gex                  # g: global, find all repetitions (without overlap)
                      # e: replacement text is executed as code
                      # x: only ungolfed: readability and comments
    ||                # s/// returns the number of replacements,
                      # this is zero, if no repetitions could be found
    say "No repetitions found!"

Perl (85 + 1 = 86 bytes)
Assumes -n flag (+1 byte) and -M5.010 (free).
length>4&&($i=say"$1 x ",length($&)/length$1)while/(.+)\1+/g}{$i||say"No repetitions found!"

Sample:
~ $ echo 123123456456 | perl -nE 'length>4&&($i=say"$1 x ",length($&)/length$1)while/(.+)\1+/g}{$i||say"No patterns found!"'
123 x 2
456 x 2
~ $ echo 112211221122 | perl -nE 'length>4&&($i=say"$1 x ",length($&)/length$1)while/(.+)\1+/g}{$i||say"No patterns found!"'
1122 x 3

Since the "No repetitions found!" has to be included in the count as well, you should probably use the extact string from the question; by changing one word, you easely spare 3 characters; while Doorknob's javascript answer uses the exact string from the question.

JavaScript, 81
Assumes input is stored in variable s. Run this in a console.
x=s.match(/^(.+?)\1+$/)
x?x[1]+" * "+s.length/x[1].length:"No repetitions found!"

Does not support multiple repetition, but that is portrayed as optional.
Explanation: regex /^(.+?)\1+$/ matches one or more characters and then those characters repeated one or more times. ? is used to make the + lazy, so it works for 123123123123.

APL 71 characters
(1+B<S)⌷(⊂'no repetitions found!'),⊂W[B],S÷B←1⍳⍨∧/¨V=¨S⍴¨W←V↑⍨¨⍳S←⍴⊃V←⊂

Example:
(1+B<S)⌷(⊂'no repetitions found!'),⊂W[B],S÷B←1⍳⍨∧/¨V=¨S⍴¨W←V↑⍨¨⍳S←⍴⊃V←⊂ '123123'

Try it with my online compiled to javascript version of GNU APL: here.


text:
What ROT is this? - decrypt ROT-n
Here are the letters of the English alphabet in order by frequency:
e t a o i n s h r d l c u m w f g y p b v k j x q z

That is, e is the most frequently used letter, and z is the least common. (Data from Wikipedia.)
Your challenge is to take some ROT-n'd text, such as:
ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz

This is the text "thisisaverysecretmessagethatisverysecureandsafe" that is "encrypted" through ROT-21 (half of 42). Your program, using the frequency table above, should be able to determine by how much each character was rotated and the original text.
(If you are not familiar with ROT-n, it is essentially shifting each character by n. For example, in ROT-2, a -> c, b -> d, ..., x -> z, y -> a, z -> b.)
How, you ask? The (very naive) algorithm you must use is:

for each n from 0 to 25 inclusive, apply ROT--n to the input string. (Negative n because we want to reverse the encryption. ROT--n is equivalent to ROT-26-n, if that's any easier.)
convert each input string to a number by adding up the relative frequencies of the characters. e is 0, t is 1, a is 2, etc. For example, the corresponding number for the string "hello" is 7 + 0 + 10 + 10 + 3 = 30.
find the string that has the lowest corresponding number.
output that string and its corresponding n.

Rules:

input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)
you may use a different algorithm, as long as it always produces identical results. For example, having z be 0 and e be 25 and choosing the highest number is also okay.
if two strings have identical scores, you can choose to output either one (or both) of them. This is an edge case and you do not have to account for it.
this is code-golf, so the shortest code in bytes will win!

Test cases:
Input: ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
Output: 21 thisisaverysecretmessagethatisverysecureandsafe
Input: pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom
Output: 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange
Input: ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq
Output: 12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe
Input: jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv
Output: 2 hereisthefinaltestcasethatyoumustdecrypt
In case you were wondering, here is a JSFiddle of the JavaScript test code I wrote, which successfully decrypted all the test cases I threw at it.

It might be useful to note the edge cases.  For example, wtaad should give 0 wtaad as the result, and vszzc should give 25 wtaad as the result.

You should give extra points for detecting implementation of TrippleROT-N.

@user19713 What is triplerot? I mean, what is the difference between ROT-6 and three times ROT-2?

@mrlister it's an old crypto joke that takes the piss out of TripleDES.

Can we output the n-root after the decrypted string?

@SpeedyNinja Yes, that's fine.

GolfScript - 87
The cheat here is to build every rotation simultaneously.  Since we need to loop over every ROT then every character, let's just loop over every character, slice the whole alphabet, then zip it up.  From there proceed as expected: count the score for each ROT and choose the minimum.
Extra golfed:
{97- 26,{97+}%.+''+>}/]{27<}%zip:d{{"etaoinshrdlcumwfgypbvkjxqz"?}%{+}*}%.$0=?.26\-\d=

Only a little golfed:
# the alphabet, and by frequency
26,{97+}%.+''+:a;
"etaoinshrdlcumwfgypbvkjxqz":f;

# build evey ROT decryption
{97-a>}/]{27<}%zip:d

# calculate likelihood
{{f?}%{+}*}%.

# find min
$0=

# output rotation factor and decryption
?.26\-\d=

Haskell - 192 175
f y=sum.map(\x->length.fst$break(==x)y)
main=interact(\s->snd$minimum$[(f"etaoinshrdlcumwfgypbvkjxqz"r,show(26-n)++" "++r)|n<-[0..25],let r=map(\x->([x..'z']++['a'..])!!n)s])

Running
% ./rot-n <<< "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom"
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange

Instead of summing lengths, you can form lists representing the numbers in unary, e.g. [1,1,1,1], and this will give the same ordering. Mapping and summing then becomes concatMap which can be written succinctly using a list comprehension. Combined with a few other tricks, I shortened it to 152 chars: main=interact(\s->snd$minimum[([1|x<-r,_<-fst$span(/=x)"etaoinshrdlcumwfgypbvkjxqz"],show(26-n)++' ':r)|n<-[0..25],r<-[[([x..'z']++['a'..])!!n|x<-s]]]).

GolfScript, 112 108 102 100 characters
{{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+

I'm not happy about the repetition with the re-decrypting at the end, but meh.
Ungolfed (if that makes any sense :P) and slightly older version:
# store input IDs (a = 0, b = 1, etc.) in s
[{}/]{97-}%:s;
# store frequency data IDs in f (blah, repetition)
"etaoinshrdlcumwfgypbvkjxqz"[{}/]{97-}%:f

# for each number from 0 to 26 (length of previous string left unpopped)...
,,{
  # the number is x
  :x;
  # return an array of...
  [
    # the score
    s{x 26\-+26%f?}%{+}*
    # and the n
    x
  ]
}%

# use $ort to find the n to output
$0=1=:x

# get the string that the n corresponded to (blah, more repetition)
s{x 26\-+26%97+}%''+

"input can be anywhere reasonable" does help GolfScript.  At first I couldn't figure out why both our scripts seemed to print an extra character at the end, until I realized echo puts a newline by default, which the interpreter picks up.

JavaScript (205)
f='zqxjkvbpygfwmucldrhsnioate';a='abcdefghijklmnopqrstuvwxyz';for(s=prompt(o=m=n=0)
,i=27;i--;w>m&&(m=w,n=i,o=u))for(u='',w=c=0;c<s.length;w+=f.indexOf(x))u+=x=(a+a)[a
.indexOf(s[c++])+i];alert((26-n)+' '+o)

I think it can still be golfed a bit more, so suggestions welcome!
Some notes to help understand the solution

m, n, and o track the highest score.
u and w track the character and value result, respectively for the current i
(a+a) helps prevent overflow when wrapping around past z, and is shorter than doing %26
I have the frequency in reverse order so I can search max instead of min.

Proof: http://jsfiddle.net/J9ZyV/5/

I count 209 chars. Anyway, I was able to get 2 characters off the length by putting indexOf in a variable.

C# + Linq - 273 264
As a function which takes the input string and returns the decoded string & offset (as per requirements):
static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);}

Ungolfed with comments:
static Tuple<string,int> d(string s)
{
    var r=Enumerable.Range(0,25)                                               // for every possible offset i
          .Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))) // calculate rot_i(input string)
          .OrderBy(                                                            // order these by their score
              x=>(
              from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)       // lookup frequency of each character
              ).Sum()                                                          // and sum each frequency to get the score
           ).First();                                                          // get the first one (lowest score)

    return Tuple.Create(r,(s[0]-r[0]+26)%26);                                  // compute offset and return results
}

Little test driver (remember to compile referencing System.Core for Linq):
using System;
using System.Linq;

namespace codegolf
{
    class Program
    {
        static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);}

        static void Main(string[] args)
        {
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null) break;
                var retval = d(input);
                Console.WriteLine(String.Format("{0} {1}", retval.Item2, retval.Item1));
            }
        }
    }
}

Giving:
$ mcs /reference:System.Core.dll main.cs && mono ./main.exe
ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
21 thisisaverysecretmessagethatisverysecureandsafe
pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange
ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq
12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe
jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv
2 hereisthefinaltestcasethatyoumustdecrypt
thisisaverysecretmessagethatisverysecureandsafe
0 thisisaverysecretmessagethatisverysecureandsafe

I think you miscounted - your current solution is actually 263 characters.  Also you can save one more char by removing the space between Tuple<string,int> d

Here's my version which is very close in implementation but a bit shorter: Tuple<int,string>f(string x){return Enumerable.Range(0,25).Select(n=>Tuple.Create(26-n,string.Concat(x.Select(c=>(char)((c-97+n)%26+97))))).OrderBy(t=>(t.Item2.Select(c=>"etaoinshrdlcumwfgypbvkjxqz".IndexOf(c))).Sum()).First();}

I think you should be using Range(0, 26), not 25.

dg - 137 130 129 128 bytes
f=t->min key:(t->sum$map 'etaoinshrdlcumwfgypbvkjxqz'.index$snd t)$map(n->n,''.join$map(c->chr$((ord c + 7-n)%26+ 97))t)(0..26)

Examples:
>>> f 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
(21, 'thisisaverysecretmessagethatisverysecureandsafe')
>>> f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
(8, 'hellopeopleofprogrammingpuzzlescodegolfstackexchange')
>>> f 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq'
(12, 'thiswasencryptedwithrottwelvesoitmustbeperfectlysafe')
>>> f 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv'
(2, 'hereisthefinaltestcasethatyoumustdecrypt')

Ungolfed code:
func = t ->
  #: Compute the score of the text `t` with respect to the frequency table.
  #: score :: (int, str) -> int
  score = t ->
    sum $ map 'etaoinshrdlcumwfgypbvkjxqz'.index $ snd t

  #: Compute rot-n of the string `t`. Return the offset and the shifted text.
  #: rot :: int -> (int, str)
  rot = n ->
    n, ''.join $ map (c->chr $ ((ord c + 7 - n) % 26 + 97)) t

  # return the minimum (computed by `score`) amongst all shifted messages
  min key: score $ map rot (0..26)

Can't you remove those spaces around c - 97 and (0..26)?

I can only remove the second one. Doing it now. I'll add some examples as well.

Never heard of dg before. Could you provide a link?

@TheDoctor: Sure! https://pyos.github.io/dg is the homepage and https://pyos.github.com/dg/tutorial the tutorial.

You can save one character by adding 7 instead of subtracting 97. Modulo 26 they are the same thing.

@hammar: Aww, maths... xD Thanks!

J - 92 char
A bit of an ugly duckling, but it works. Outputs the number and then the string, on two lines.
(26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:)

If you want them to be on the same line, space separated, this only goes up to 93 char, but takes an uglier route.
((":@],[:u:32,97+26|-)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])@(7+3&u:)

An explanation for (/:'ctljapqhewvknfdsyigbmuoxrz'): In this verb, we operate on the letter values as A=0, B=1, C=2, etc. To encode the letter values of the string etaoinshrdlcumwfgypbvkjxqz, the shortest way is actually to take the sort permutation for this weird string. This is because A is at index 4, B at index 19, C at 0, D at 14, and so on; hence the sort permutation is 4 19 0 14 8 13 ... when you grade (/:) it, and you get exactly the number values for etaoin....
Usage:
   (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:) 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
21
thisisaverysecretmessagethatisverysecureandsafe

   NB. naming for convenience
   f =: (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:)
   f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
8
hellopeopleofprogrammingpuzzlescodegolfstackexchange
   f 'wtaad'
0
wtaad

q, 97
{(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)}

.
q) tests:(
    "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvazocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz";
    "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom";
    "ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq";
    "jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv")

q) f:{(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)}

q) f each tests
21 "thisisaverysecretmessagethatisverysecureandsafethisisaverysecretmessagethatisverysecureandsafe"
8  "hellopeopleofprogrammingpuzzlescodegolfstackexchange"
12 "thiswasencryptedwithrottwelvesoitmustbeperfectlysafe"
2  "hereisthefinaltestcasethatyoumustdecrypt"

APL - 70 characters
F←{↑⍋+/'etaoinshrdlcumwfgypbvkjxqz'⍳⊃(⍳26){l[(⍺⌽l←⎕UCS 97+⍳26)⍳⍵]}¨⊂⍵}

Example:
      F 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
21
      F 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
8
      F 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq'
12
      F 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv'
2

I'm sure there are ways to compress this further, and I invite any other APL users to come up with solutions for that.

You have to output the decided string too...

Python 188
x="abcdefghijklmnopqrstuvwxyz"
y=input()
r=lambda n:"".join(x[x.find(i)-n]for i in y)
s={sum("etaoinshrdlcumwfgypbvkjxqz".find(b)for b in r(a)):(a,r(a))for a in range(26)}
print(s[min(s)])

Perl: 256 char (plus newlines for readability) including the frequency table:
@f=unpack("W*","etaoinshrdlcumwfgypbvkjxqz");
@c=unpack("W*",<>);$m=ord("a");$b=1E10;
for$n(0..25){$s=0;$t="";
for$x(0..scalar@c){$r=($c[$x]-$n-$m)%26+$m;$t.=chr($r);
for(0..scalar@f){if($r==$f[$_]){$s+=$_}}}
if($s<$b){$b=$s;$w=$t;$a=$n}}
printf"%d %s\n",$a,$w;

Text is provided like so:
echo "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz" | perl ./freq.pl
21 thisisaverysecretmessagethatisverysecureandsafewm

Take off 12 char if you want to bake-in the values of ord(a) and the length of @f

Elm - 465
Not going to win any golfing awards, but it makes a static webpage which displays a list of the form [(rotation number, rotated string)] as you type.
Note: not yet working here but you can copy-paste it into the official editor and run it.
import String as S
import Char (..)
import Graphics.Input (..)
import Graphics.Input.Field (..)
f="ETAOINSHRDLCUMWFGYPBVKJXQZ"
r s n=let t c=mod(toCode c-65+n)26+65 in map(fromCode . t)(S.toList s)
w s=case s of
 ""->0
 s->sum(S.indexes(S.left 1 s)f)+w(S.dropLeft 1 s)
b s=sort<|map(\x->((w . S.fromList . r s)x,(26-x,S.fromList<|r s x)))[0..25]
c=input noContent
main=above<~(field defaultStyle c.handle id""<~c.signal)~(asText . b . .string<~c.signal)

Python 2, 171
f,R,i='zqxjkvbpygfwmucldrhsnioate',{},raw_input();a=sorted(f)*2
for n in range(26):_=''.join(a[ord(x)-71-n]for x in i);R[sum(2**f.index(x)for x in _)]=n,_
print R[max(R)]

Ruby, 142 bytes
->s{(0..25).map{|i|[*s.map{["etaoinshrdlcumwfgypbvkjxqz".chars.index(c=((_1.ord-97-i)%26+97).chr),c]}.transpose.map{_1.reduce:+},i]}.min[1..]}

Attempt This Online!

Python + golfing-shortcuts, 165 161 bytes
A port of gcq's answer.
from s import*
def F(Y):R=lambda N:sj("",(Sl[Sl.find(I)-N]for I in Y));S={s("etaoinshrdlcumwfgypbvkjxqz".find(B)for B in R(A)):(A,R(A))for A in r(26)};p(S[q(S)])

R, 140 bytes
\(e,u=utf8ToInt,x=u(e)-97)c(n<-which.min(sapply(25:0,\(z)sum(match((x+z)%%26,u("etaoinshrdlcumwfgypbvkjxqz")-97)))),intToUtf8((x-n)%%26+97))

Attempt This Online!

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


text:
Make the most useful program within 100 characters
In this task, you are allowed make an useful program to do anything you can write within 100 characters. You are allowed to use less characters, but not more.
Rules, just to protect from standard loopholes that are no longer funny:

Your program cannot access the internet, unless it really has to. For example, the program which shows the most upvoted question on this website may use the Internet to check this question. However, it's not allowed to browse the Internet in order to find its real source and run it.
Your program cannot be an interpreter for the language it was written in. However, Brainfuck interpreter in non-Brainfuck language would be fine.
Your program cannot execute external programs that does exactly what your program does. For example, you cannot run vim, and claim that your program is vim implementation.
Your program cannot be dangerous for the computer it's being ran on and other computers. You aren't allowed to write program like rmdir / (the example here intentionally doesn't work, don't fix it), and claim it's an useful program to remove all files on the computer.
Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.
You aren't allowed to make language specifically for this task. However, you are allowed to make interpreter for your invented language in some other programming language.

Can I post more than one answer for this contest?

@TrungDQ: Sure.

This has got to be one of the best questions to date ;)

This is way too open-ended, even for a site like this one, even for a popularity contest. Literally any answer is valid, there's no frame of reference whatsoever for comparing them.

This question is cannibalizing code-golf. Interesting 100 character ideas should be able to be rephrased into great code-gold questions. I'd encourage the answerers to spend a few extra minutes to turn their answers into new questions.

C - 47 bytes
The following program outputs every document ever written in human history, along with every document that will ever be written and loads of interesting texts that no human will ever come up with (along with a "little bit" of garbage in between). Just give it some time. Moreover, every time you run it, it will output different texts first! If that's not useful! (And all of that within half the character limit!)
main(){srand(time(0));while(1)putchar(rand());}

If you don't care about it outputting something else each time, you only need 41 bytes!
main(){srand(0);while(1)putchar(rand());}

Not quite C99 conform, but it compiles smoothly with gcc.exe (GCC) 4.7.0 20111220.
The rules state

Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.

No problem.
Some things, this program will output:

a solution to every Millennium Problem
tomorrow's newspaper articles
the complete works of Shakespeare's (of course)
your darkest secret
all the other answers to this question

 Not really, because (as ace correctly mentioned in the comment), rand() is only a pseudo-random generator, that will wrap around at some point - probably way too early to produce a lot of meaningful texts. But I doubt that getting data from a true (hardware) random number generator is remotely possible within 100 characters. I'll leave this here for the fun of it, though.

As Dennis notes, the randomness of the the algorithm, could be somewhat improved (within the character limit), by using rand()^rand()>>16 instead of rand().

Not necessarily. rand() is only pseudorandom - it may not produce any useful text before it loops around.

@ace damn that's a good point. I doubt I can squeeze in code to talk to a true random number generator though :D

On Linux, getting true randomness is as easy as reading from the (pseudo-)file /dev/random.

@celtschk: No, it isn't. /dev/random should work well for all practical purposes, but it certainly won't meet the requirements of the Borel-Cantelli lemma. Of course, even with truly random output, you won't generate anything useful before we, the computer and the universe are all long gone...

@Dennis luckily that is still within the rules of this question! :)

@m.buettner: With GLIBC's rand(), there's a simple algebraic relation between bytes of your program's output: Viewing the output as an array x, you have x[i] == (x[i - 3] + x[i - 31] + c[i]) % 256, where c[i] is 0 with probability 0.75 and 1 with probability 0.25. This pretty much means that it can't generate any of the things you mentioned.

@Dennis yeah, but I doubt that any better PRNG would serve me well here, because it takes a LONG time to generate anything useful (especially a PRNG that fits within 100 characters). This was really just meant to be an entry for fun. Of course, if you have suggestions to improve the random number generator within 100 bytes, I'd be happy to see them! :)

THIS CODE IS DANGEROUS and erroneous ! I tried this code and it hung the process of output window after 15 seconds also This code needs two more header files stdlib.h and stdio.h so this makes 112 character long answer therefore this answer is illegal....Down-vote from me.

@MukulKumar it compiles just fine with gcc without those headers. And I can abort it with Ctrl+C. Also the second version is still well within 100 bytes, even with those includes.

@m.buettner I use Min GW GCC 4.7.2 compiler (I guess this is also gcc compiler) then why it is not fine when I compile this ?

@MukulKumar: What exactly did it hang? The compiler or the compiled program? And did adding the header really fix it? None of the headers should be necessary, not even time.h.

@Dennis: Would yoiu please care to explain why you think it won't meet those requirements? You are aware that /dev/random is not a PRNG, but actually collects entropy from the system?

@celtschk: The only source of truly random data are quantum effects, such as radioactive decay of atoms. For /dev/random, the kernel just collects some environmental noise, notably keyboard strokes and mouse movements.

@MukulKumar I was using gcc.exe (GCC) 4.7.0 20111220 and going by this

@Dennis thanks for the time.h hint. No clue, why I didn't try that.

@m.buettner: It won't make the PRNG much better, but you can remove the linearity using rand()^rand()>>16 instead of plain rand(). If you're looking for ways to save on bytes, remove int and %256.

@Dennis I was thinking about the %256 but I couldn't seem to find out what putchar does with ints greater than 256.

@m.buettner: The value is internally converted to an unsigned char when written.

@Dennis haha, I was actually looking at that page but somehow overlooked the sentence.

@Dennis the compiled program hanged after 10-15 seconds. Yes, adding header files really fixed the problem. Without headers, the code gave error saying that the srand() rand() and putchar() functions are undefined.

@MukulKumar do you get warning or actual errors if you simply run gcc -o monkey monkey.c? As for the hanging, I'm sorry but I really can't reproduce. What shell are you running it in?

@m.buettner no,... no warning and no errors. What is a shell ? BTW

BBC BASIC, 84 chars
MODE 6:INPUT T,A,B,A$,B$:FOR X=0 TO 1279:A=A+EVAL(A$):B=B+EVAL(B$):DRAW X,A+500:NEXT

Plots the solutions to first and second order differential equations.
Takes as user input:
Title (does nothing)
Start value for A (plotted value)
Start value for B (not plotted)
Expression for dA/dX
Expression for dB/dX

Inspired by a differential equation solving software called Polymath which I used when studying to be a chemical engineer. We would input different equations for reactants and products and see how the whole reaction system changed over time. A very simple software (not much more complex than this) but much more convenient for this purpose than Excel. Unfortunately I cannot do a complete clone of Polymath in 100 chars.

Mathematica 76
This program constructs an applet that displays information regarding various properties for any of 240 countries.  It opens with information about the adult population of Afghanistan.  The user may change the country and property settings through drop-down lists.
Mathematica interoperates smoothly with WolframAlpha.
For this reason I believe the submission meets requirement #1 of the challenge: "Your program cannot access the internet, unless it really has to".
This rather modest applet simply makes use of existing functionality in the Mathematica language.   A short video provides some additional information about the applet.
d = CountryData; Manipulate[WolframAlpha[p <> " " <> c], {p, d["Properties"]}, {c, d[]}]

Below is a list of the first 20  (of 223) properties related to countries.  With a additional programming one can obtain additional information regarding countries and analyze this information in Mathematica.
CountryData["Properties"][[;; 20]]

{"AdultPopulation", "AgriculturalProducts", "AgriculturalValueAdded",
"Airports", "AlternateNames", "AlternateStandardNames",
"AMRadioStations", "AnnualBirths", "AnnualDeaths",
"AnnualHIVAIDSDeaths", "ArableLandArea", "ArableLandFraction",
"Area", "BirthRateFraction", "BorderingCountries", "BordersLengths",
"BoundaryLength", "CallingCode", "CapitalCity", "CapitalLocation"}

I don't see how your program "has to" access the internet. The data you present doesn't change that frequently you would need to rely on an outside source.

Whether the source is inside or outside is open to debate. I was considering the request for information on WolframAlpha (which the code does make) to be a case of (necessary) "access to the internet", even though the code directly consults a Wolfram data server and does not require the use of a browser like FireFox. It does require that one have a network or WIFI connection

-1 if I could - this simply munges a data structure from a pre-existing service.

@l0b0 I suppose you could see it that way. Or you might say that it exploits the functionality of the language. After all, WolframAlpha was designed from the ground up to interoperate closely with Mathematica.

"The information in WolframAlpha is an integral part of Mathematica and the Wolfram Language" is a rather alarming state of affairs. That must make it the least stable programming language in existence.

@PeterTaylor.  Yes, that statement was silly. I replaced it.

@PeterTaylor not necessarily, I seem to get a Java update at least once a day ;-)

bash, 100 bytes
head -c${1--1} /dev/zero |
openssl enc -aes-128-ctr -pass file:/dev/random 2>/dev/null |
tail -c+17

This script prints a cryptographically secure stream of bytes. It takes an optional argument specifying the number of bytes it should print. By default, the output will be infinite.
Useful in cases where reading from /dev/urandom is just too darn slow.
Benchmark
$ time head -c 1G /dev/urandom > /dev/null
Real    59.75
User    0.03
Sys     59.68
$ time random 1G > /dev/null
Real    0.68
User    0.64
Sys     0.86

This script generates up to 1.5 GiB per second on my i7-3770.
In contrast, reading from /dev/urandom manages to generate barely 1 GiB per minute.
How it works

head -c${1--1} /dev/zero outputs the specified amount of zero bytes. If no amount is specified, ${1--1} equals -1 and head outputs an infinite amount.
openssl enc -aes-128-ctr -pass file:/dev/random uses AES-128 in counter mode to encrypt the zero bytes, reading the password from /dev/random.
tail -c+17 gets rid of the output's 16-byte header.

Note that this stream can be distinguished from a "real" random stream by looking at the first 2^68 output bytes (a real random stream should have duplicated blocks there, this one won't).

@PaŭloEbermann: You're obviously right. Then again, it would take over 6,000 years to generate that many bytes on my machine...

Javascript
Solve any equation (well, not all, but should work with common functions...)
r=s=>{for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x}

Without ES6 (105 chars):
function r(s){for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x}

Just give the left side of the equation assuming that the right side is zero.
Example :

r("x*x-9") returns 3
r("Math.sin(x)-1") returns 1.5707963394347828 (pi/2)
r("Math.pow(2,x)-512") returns 9

Warning : can diverge on some functions (or if there is no solution) and freeze your browser tab, or return NaN.

C - 99 characters
i;main(int c,char**a){for(a+=2;1+(c=getchar());)putchar(c+(**(a-1)-69?1:-1)**(*a+i++%strlen(*a)));}

This program allows encryption and decryption of any kind of data.
Usage
First... compile it!
gcc crypto.c crypto

If you want to encrypt the contents of mypreciousdata.txt with the key mysecretkey, and store the result in myprotecteddata.txt:
cat mypreciousdata.txt | ./crypto E mysecretkey > myprotecteddata.txt

Now, if you want to retrieve the decoded contents of myprotecteddata.txt:
cat myprotecteddata.txt | ./crypto D mysecretkey > mypreciousdata.txt

The longer the key, the safer!
Explanation
Please find the expanded and commented code below:
int main(int argc, char** argv)
{
    // retrieve the first argument passed to the program (action)
    char action = argv[1][0];

    // retrieve the second argument passed to the program (key)
    char* key = argv[2];

    // initialize character position in the key
    int i = 0;

    // initialize the current input character
    char c = 0;

    // loop until we reach the end of input
    while (c != -1){
        // get a character from stdin
        c = getchar();
        if (action == 'E'){
            // encode the current character
            putchar(c + key[i]);
        } else{
            // decode the current character
            putchar(c - key[i]);
        }
        // increment the position in the key, without overflow
        i = (i + 1) % strlen(key);
    }
}

This is a variant of the Vigenère cipher adapted for a alphabet of the size of your char type (usually 256).

GolfScript
I managed to squeeze this into exactly 100 characters!
{{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+

It takes input of ROT-n encrypted text and outputs the text decoded. (Taken from here.) For example, when given the input pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom, the output is 8hellopeopleofprogrammingpuzzlescodegolfstackexchange.

JavaScript

To generate a unique id in javascript

Math.random().toString(30).slice(2);

Produces something like : 'h9d2f4aniimma7h1d3pbffi0foi8d3mf'
strings of 30-32 alpha-numeric characters
Math.random().toString(36).slice(2)

Produces something like : 'uq2sze67hsacq5mi'
Strings of length 14-16 .

C++ 57
#include<iostream>
#include<conio.h>
int main(){std::cout<<getch();}

This program takes a character input and outputs its ASCII value.

The Brainfuck$ code is a lot shorter - ,:

@Timtech I don't know brainfuck$

http://esolangs.org/wiki/Brainfuck$

Fortran - 85 bytes
l=0;read(*,*)n;do while(n>0);i=mod(n,10);l=l+i;n=n/10;enddo;print*,"digit sum=",l;end

Reads in a number and prints out the sum of the digits. Useful for Project Euler problems.

How does this help for project Euler problems?

@PaŭloEbermann: Perhaps I should have added "some" before Project Euler. I know for sure Problems 16, 20 & 119 use digit sums, not sure about others, but many of their problems do not need this one.


text:
The Note of Destiny - place a note on a staff
The zombie apocalypse has come, and the world is coming to an end. Suddenly, someone discovers a formula that takes the current hour, minute, and day, and spits out the perfect note to play on a piano that instantly kills every zombie that hears it. Unfortunately, there is only one piano player left in the world, and he has forgotten how to read notes, but he still knows how to read sheet music. Of course, this is a very time-sensitive thing, so it seems natural to have a computer do it.1
Your challenge is to take a note, such as G, and output the note placed on a staff (in treble clef), like this:
-----

-----
   |
---|-
   |
--O--

-----

Specification:

You must output a staff of alternating lines of ----- (5 dashes) and a blank line. There will be 5 -----s total. The note must be superimposed on top of this staff.
The input will specify where the note is located. The input will be:

an optional H or L, specifying "high" or "low"
a letter from A to G, specifying the pitch
an optional # or b, specifying sharp or flat.

The "note" is defined as:

One O (capital O) aligned to the middle of the staff, which is in the place of the note. (The top line is HF (high F), and the bottom line is E (a normal E).)
Three |s (vertical bars), the stem, which will be:

one space to the left of the note and going downwards (starting one space below the note) if the note is on the middle line (B) or above, or
one space to the right of the note and going upwards (starting one space above the note) if the note is below the middle line.

A # or b one space directly to the left of the note if specified in the input.

Ledger lines must be added if the note is too high or low. These lines will be --- (only 3 dashes in width, as opposed to 5) and will only appear if the note is on or above/below (for top/bottom ledger lines respectively) the ledger lines.
Extraneous spaces may be placed anywhere you want; for example, you could make the blank lines have spaces or have a space after the ledger lines if it helps you save any characters.

Here is a visualization, to understand the specification more easily, with all the note names next to the lines:
      HB
 ---  HA
      HG
----- HF
      HE
----- HD
      HC
----- B
      A
----- G
      F
----- E
      D
 ---  C
      LB
 ---  LA
      LG
 ---  LF
... (bottom cut off for brevity, you get the idea anyway)

Here are some more examples that you can use to test your program:
Input: HG#
 #O
-|---
 |
-|---

-----

-----

-----

Input: LAb
-----

-----

-----

-----

-----
   |
 --|
   |
 bO-

Input: HB
  O
 |--
 |
-|---

-----

-----

-----

-----

Input: C
-----

-----

-----

-----
   |
---|-
   |
 -O-

This is code-golf, so the shortest code in bytes will win!
1: most realistic exposition evar! :-P

It looks very strange to have # or b at the right of the note rather than at the left; is it really what is required?

@ברוכאל No; that's just me not thinking properly ;-) edited

You have two HC's in your Visualization. I assume the top one should be deleted, as you make no mention of HHC (double high) in the rest of the specification.

@steve Oops; also a mistake. Edited

What about B# and the like?  1. plot as-is; 2. reject; 3. silently convert to C?

@DigitalTrauma Plot those too; I've played B#s and E#s in my experience with piano before. (I've even played double sharps, but that's outside the scope of the challenge. ;-))

It may be better to explicitly state that it should be in treble clef.

To clarify, by "on or above/below ... them" you mean the ledger lines, or alternately the pitches represented by the ledger lines.

@ace Of course; edited.

@couchand I thought that would be implied, but it's always good to be specific ;-) edited

How about your "blank line" requirement? Must it be be an absolutely empty line if there is no note or could it be four/five spaces?

@m.buettner Added an extra rule at the end of the specification to clarify.

Does it have to be text output? We should be able to render it as an image if we want.

Anyone up to attempting this in Fugue?

@AJM Yes, it has to be ASCII art.

Golfscript, 211 210 209 197 195 192 characters
Coming in for the (as of this post) win, a GolfScript version of my latest Python version:
"J"\+[0]+.1=71>>3<{}/@7*2/246-@3+7%-:z;:c;21,{..3z<3z
if<\11z>11z
if>|{;}{...2>\12<&\2%.{'-'' 'if}:Q~:9;&Q\.z={c!9{[c]''+}if}{..z>\4z+<&8z>&'|'9if}if\.z='o'9if\..z
4-\<\z<&7z<&'|'9if\;3$n}if}/

Test it out here (first 2 lines are user-input, normally it comes from stdin).
'Readable' version:
;"HCb"

"J"\+[0]+       #process input
.1=71>>3<       #first char is HJL, second is letter, third is #b or space
{}/             #spill chars onto stack, now we working with ints
@7*2/246-@3+7%- #convert HC/JD/LE etc to a number from 0 to 20
:z;:c;
21,{            #for r in range(21):
  ..3z<3z if<           #either out-of-bounds or process the line
  \11z>11z if>|
  {;}{
    ...2>\12<&\2%.{'-'' 'if}:Q~:9;&Q\        #1st char
    .z={c!9{[c]''+}if}                       #2nd char accidental
       {..z>\4z+<&8z>&'|'9if}if\            #2nd char stem or row
    .z='o'9if\                              #3rd char
    ..z 4-\<\z<&7z<&'|'9if\                 #4th char stem or row
    ;3$                                      #5th char=1st char
    n
  }if
}/

Aaaaaaand beaten by GolfScript again. :) ...

@m.buettner: Haha, it never ends.. surprisingly close though!

Better! Now I only need to find 6/9 bytes to catch up :D (although I don't see how I would do that)

@m.buettner: Got 2 more bytes down! Each one is so brutal though... I might have to stop for now. Good luck!

I got 4 because I had an unnecessary variable left from some previous version. But now it seems really hard to go any further without actually trying some completely different algorithm.

Oh bloody hell... just when I thought I had beaten your 209. I think I'm giving up. GolfScript prevails. ;)

@m.buettner: All hail the golfscript! I'm seriously impressed by your ruby effort though, usually it's nowhere close... I think this problem was just on the cusp of not being well-suited for golfscript (not all problems are). I have dreams of making Golfscript+, which also uses characters 128-255, to make one-byte functions of common operations (e.g. so if is one byte, a version of : which consumes the variable, etc...). I guess that would just be APL though..

Ruby – 271 267 252 249 234 229 220 214 characters
I literally just learned Ruby for this. So there is certainly room for improvement in golfing it down. Or doing anything really. But I needed a language with mutable strings. :)
def f(n)s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]end

Somewhat ungolfed:
def f(note)
  staff=[]
  0.step(20) {|i| staff[i] = " "*5}
  1.step(19,2) {|i| staff[i] = " ---"}
  3.step(11,2) {|i| staff[i] = "-"*5}
  level = 7
  if !(pos="HL".index note[i=0]).nil?
    level = 14*pos
    i += 1
  end
  level += (73-note[i].ord)%7
  staff[level][2] = "O"
  mark = note[-1]
  if !"#b".index(mark).nil?
    staff[level][1] = mark
  end
  offset = (level > 7) ? 3 : 1
  staff[level-2*offset+3,3].map {|line| line[offset] = "|"}
  first = [3,level].min
  last = [11,level].max
  puts s[first..last]
end

I can cut it by another 2 characters down to 212 characters if leading blank lines are allowed. This solution doesn't fill the lines that aren't printed anyway:
def f(n)s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s
end

Are lambda's fair game? Then I can get 210 characters with the first approach
f=->n{s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]}

Or 207 characters with additional blank lines:
f=->n{s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s}

Of course, now you'd need to do f.call("HGb").

Ha, +1 for learning an entirely new language! ;-) Here's a tip: !x.nil? is equivalent to !x. And for one line ifs, if x;y;end; is equivalent to y if x. Also you can use a literal newline in that string.

@Doorknob thanks, I'll try to work those in!

@Doorknob hm, I only got the if to work. If I use ?\n (if that's what you meant) I need to add a space, so I gain nothing. And removing the .nil?s didn't work at all (always evaluated to true).

I meant literally adding a newline between the two quotes. And I think you need extra parens when removing .nil?, but it's worth it in characters.

@Doorknob ah, no !x.nil? is !!x. :)

Whoops, that's right. I think !!!!!!!!x is the best way though. (Actually, 42 !s is.) :P

My comment was meant as a joke. !!x is the same as x. ;)

@Doorknob. oh, I somehow thought if needs a boolean. thinking about it, that doesn't make sense in a language that has a concept of truthy and falsy. I'll fix it tomorrow.

Python, 329 309 295 286 280 277 characters
Golfed a bit more now. Still can be improved, but not sure if I can beat out the ruby or golfscript solutions with this approach.
R=range
N='J'+raw_input()+' '
X=N[1]>'G'
a,b,c=N[X:3+X]
z=266-ord(a)/2*7+(ord(b)-4)%7
Z=[list((' '*5,(' ---','-'*5)[8<r<18])[r%2])for r in R(21)]
Z[z][2]='o'
if' '<c:Z[z][1]=c
Q=(z<13)*2
for i in(1,2,3):Z[z+i*Q-i][Q+1]='|'
for r in R(max(17,z),min(z-1,8),-1):print''.join(Z[r])

Initially I was printing out line-by-line, but it turned out to take too much, so I generate a string grid and then fill in what needs be filled in. Input is from command line, e.g.:
>echo HG# | python note2_golf.py
 #o
-|---
 |
-|---

-----

-----

-----

In line 5 you can remove the space before the second comma

@ace: Thanks, missed that one

GolfScript - 243 232 228 227 characters
I translated my CoffeeScript answer into GolfScript, which is much more suited to the string manipulations.
EDIT: Saved six characters by properly using the increment operator, three by making good use of the stack, six more by irresponsibly redefining operators I'm not using, and one more by not printing the trailing space after grace lines.
Entirely golfed:
..0="HL"?2+3%:o)2%.@="CDEFGAB"?7o*+:`2%45 32if:r;
).2$,<{=}{;;r}if:&;
[" "5*:|" ---":g]4*[|"-"5*]5*+[|g|]+.
[`<~]\[`>([0=:^&79r^]''+\~]
+17`<`)18if<9`>`9if:j>:t 13`>.2*):x;
4,1>{`j-\2${+}{-}if}%\;
{.@<\t>(:v[x<'|'+x)v>+]\++:t}
/-1%n*

With comments:
# extract octave
..0="HL"?2+3%:o

# extract note
2%1\-.@="CDEFGAB"?7o*+:k

# line spacer
2%45 32if:r;

# extract accidental
1+.2$,<{=}{;;r}if:a;

# staff
[" "5*:|" --- ":g]4*[|"-"5*]5*+[|g|]+.

# lines below
[k<~]\

# note line and above
[k>([0=:w a 79r w]''+\~]+

# cut off just what we need
17k<1k+18if<
9k>k 9if:j>:t;

# and the note stem
13k>.2*1+:x;4,1>{k j-\2${+}{-}if}%\;

{
  .t<\
  t>(:v[x<'|'+1x+v>+]\++:t;
}/

# now output the note
t-1%n*

I would have been astonished if I could beat a GolfScript solution in a language that I have no experience in ;)

I'm no GolfScript expert but I think I've eked out just about all the characters I'm going to get out of this, so if you can find another two, you're golden!

Try to type Go in it. it will output oo||| :)

Java - 921 907 863 characters
I build up each string seperately, storing each string in an array.
Then loop through the array and print out each line.
public class D{public static void main(String[]a){char[]z=a[0].toCharArray();char[]y=new char[3];y[0]=('H'==z[0]||'L'==z[0])?z[0]:'N';int o=(y[0]=='N')?0:1;y[1]=z[o++];y[2]=z.length>o?z[o]:'!';int n=y[1]<'C'?((int)(y[1]-'A'))+6:((int)(y[1]-'C'))+1;n=(y[0]=='N')?n+7:(y[0]=='H'?n+14:n);String s="     ";String b=" --- ";String[]u=new String[22];for(int i=1;i<=21;i+=2){u[i]=s;}for(int i=10;i<=18;i+=2){u[i]="-----";}u[20]=n>19?b:s;u[2]=n<3?b:s;u[4]=n<5?b:s;u[6]=n<7?b:s;u[8]=n<9?b:s;char c=u[n].charAt(0);char e=u[n].charAt(1);char[]h=new char[]{c,y[2]=='!'?e:y[2],'O',e,c};u[n]=new String(h);for(int i=0;i<22;i++){if(n<14&&i-n<4&&i>n)u[i]=u[i]!=null?u[i].substring(0,3)+"|"+u[i].charAt(4):s;else if(n>13&&n-i<4&&n>i)u[i]=u[i]!=null?u[i].substring(0,3)+"|"+u[i].charAt(4):s;}for(int i=21;i>=0;i--)if(!(i>n&&i>18||i<n&&i<10))System.u.println((u[i]==null)?s:u[i]);}}

Oh please don't hate me, it's my first time. I coulnd't find any faq/introduction so I hope my posting format is ok.
 Not sure how serious people got about character counts....
normal version of the code - extra is linebreak/spaces (1313 characters):
public class DisplayNote
{
  public static void main(String[] args)
  {
    char[] z=args[0].toCharArray();
    char[] y=new char[3];
    y[0]=('H'==z[0]||'L'==z[0])?z[0]:'N';
    int o=(y[0]=='N')?0:1;
    y[1]=z[o++];
    y[2]=z.length>o?z[o]:'!';

    int noteValue=y[1]<'C'?((int) (y[1] - 'A')) + 6:((int) (y[1] - 'C')) + 1;
    noteValue=(y[0]=='N')?noteValue+7:(y[0]=='H'?noteValue+14:noteValue);
    String s="     ";
    String b=" --- ";
    String[] out=new String[22];
    for (int i=1;i<=21;i+=2){out[i]=s;}
    for (int i=10;i<=18;i+=2){out[i]="-----";}
    out[20]=noteValue>19?b:s;
    out[2]=noteValue<3?b:s;
    out[4]=noteValue<5?b:s;
    out[6]=noteValue<7?b:s;
    out[8]=noteValue<9?b:s;

    char c=out[noteValue].charAt(0);
    char e=out[noteValue].charAt(1);
    char[] h=new char[]{c,y[2]=='!'?e:y[2],'O',e,c};
    out[noteValue]=new String(h);
    for (int i=0;i<22;i++)
    {
      if (noteValue<14&&i-noteValue<4&&i>noteValue)
        out[i]=out[i]!=null?out[i].substring(0,3)+"|"+out[i].charAt(4):s;
      else if (noteValue>13&&noteValue-i<4&&noteValue>i)
        out[i]=out[i]!=null?out[i].substring(0,3)+"|"+out[i].charAt(4):s;
    }

    for (int i=21;i>=0;i--)
      if (!(i>noteValue&&i>18||i<noteValue&&i<10))
        System.out.println((out[i]==null)?s:out[i]);
  }
}

I see tons of unnecessary whitespace (especially after semicolons and around operators and brackets and parens) and long variable names (like args).

In the character counting submission: 921 characters, all whitespace is gone :P

The second submission with whitespace everywhere is to let people read the code, as I said it's my first time so not sure if we're meant to leave 1 submission and 1 where you try to reduce the character limit... or what?

No; I see an enormous amount of useless whitespace in that version. For example, spaces after semicolons, spaces around operators, spaces after [], spaces around parentheses, etc.

Removed them all now (I think) Thanks :)

If you rename out to o you can save another 2n characters (with n a reasonably sized integer).

Python, 250 245 242 235 characters
A very different approach which ended up beating out my other one! Input processing code is similar but that's about it.
M=' -'
N=raw_input()+M
a,b,c=('J'+N)[N>'G':][:3]
z=ord(a)*7/2-246-(ord(b)+3)%7
for r in range(21):
 L=M[r%2];F=M[2<r<12and r%2]
 if min(3,z)<=r<=max(11,z):print F+((L,'|')[8>z<r<z+4],(L,c)[M<c])[r==z]+(L,'o')[r==z]+(L,'|')[z-4<r<z>7]+F

I mapped out each character's value based on the row and column and then golfed the printing:
#given row r, with note on row n, how to print each char?
#rows are:
#       HB : 0
#  ---  HA : 1
#       HG : 2
# ----- HF : 3
#       HE : 4
# ----- HD : 5
#       HC : 6
# ----- B  : 7
#       A  : 8
# ----- G  : 9
#       F  : 10
# ----- E  : 11
#       D  : 12
#  ---  C  : 13
#       LB : 14
#  ---  LA : 15
#       LG : 16
#  ---  LF : 17
#       LE : 18
#  ---  LD : 19
#       LC : 20
#chars are:
# 0 | 1 | 2 | 3 | 4
#
# 0,4:
#    if r%2:
#      if 2<r<12: '-'
#      else ' '
#    else: ' '
# 1: ' -b#|'
#    if r==n:
#      if A: c
#      else: ' -'[r%2]
#    elif n<8 and n<r<n+4: '|'
#    else: ' -'[r%2]
# 2: ' -o'
#    if r==n: 'o'
#    else: ' -'[r%2]
# 3: ' -|'
#    if n>7 and n-4<r<n: '|'
#    else: ' -'[r%2]

+1, Last line seems more Perl's black magic than Pythonic stuff

Haskell 377C
import Data.Char
(<.)=elem
n(c:r)|elem c"HL"=let(s,a)=n r in(s+case c of 'H'->7;_-> -7,a)|1<2=(mod(ord c-67)7-2,case r of[]->' ';[x]->x)
r(s,a)y x=c where d|s>4= -1|1<2=1;c|x<.[0,4]&&(y<0||y>8)=' '|x==2&&y==s='o'|y==s&&x==1&&' '/=a=a|x==2+d&&y<.[s+k*d|k<-[1..3]]='|'|1<2="- "!!mod y 2
g p@(s,a)=unlines$[map(r p y)[0..4]|y<-reverse[min 0 s..max 8 s]]
main=getLine>>=putStr.g.n

Ungolfed version:
import Data.Char

fromName ('H':s) = let (step, alter) = fromName s in ((step + 7), alter)
fromName ('L':s) = let (step, alter) = fromName s in ((step - 7), alter)
fromName (x:s) = (mod (ord x - 67) 7 - 2, if null s then ' ' else head s)

renderChar :: (Int, Char) -> Int -> Int -> Char
renderChar (step, alter) y x = let
    dir = if step >  4 then -1 else 1
    normal = "- "!!mod y 2
    stemYs = [step + k * dir | k <- [1..3]]
    c | elem x [0,4] && not(elem y [0,2,4,6,8]) = ' '
      | x == 2 && y == step = 'o'
      | y == step && x == 1 && alter /= ' ' = alter
      | elem y stemYs && x == 2 + dir = '|'
      | otherwise = normal
  in c

render :: (Int, Char)-> String
render (step, alter) = unlines [map (renderChar (step, alter) y) [0..4] | y <- ys]
  where
    ys = reverse [min 0 step .. max 8 step]

main = getLine >>= (putStr.render.fromName)

Literate CoffeeScript - 497 527 characters
I'm sure there's a better way to build the grid but I can't figure it out.
One golf helper.
_=(q)->->q.split ""

A C major scale and staff.
s=_("CDEFGAB")()
l=_ "-----"
e=_ "     "
g=_ " --- "
t=->
  o=[e(),l(),e(),l(),e(),l(),e(),l(),e(),l(),e(),g(),e()]
  o.unshift e(),g() for [0..3]
  o

Our notation function will take the string representation of a note.
f=(i)->
  o=1
  m=t()

First we'll determine the octave.
  if /L|H/.test i[0]
    if i[0]=="L" then o=0 else o=2
    i=i[1..]

Then the note and accidental.  Gotta love deconstructing assignment.
  [n,a]=i

Let's convert the note and octave to an index and plot the note.
  x=7*o+s.indexOf n

  m[x][1]=a if a
  m[x][2]='O'

Now we'll cut out only as much staff as we need.
  j=9
  k=17
  if x>17
    k=x
  else if x<9
    j=x
  u=x-j
  m=m[j..k]

And the note stem.
  if x<13
    m[x][3]='|' for x in [u+3...u]
  else
    m[x][1]='|' for x in [u-3...u]

Now let's output the results.
  m.map((p)->p.join '').reverse().join '\n'

Finally, we'll export the function for console testing.  These
characters don't count towards the total.
module.exports = f

Looking closer it seems like I screwed up when refactoring the note stem, so it produces illegal output at the moment.

I fixed it, but it added 30 characters :-/

C, 325 304
Now 21 bytes shorter thanks to @ace!
i;j;c;n;main(t){char
x[133];for(i;i<132;i++){x[i]="-----\n     \n"[i%12];if((i<18||i>77)&&!((i%12)&11))x[i]=32;}for(;!n;){c=getchar();if(c>71)t=c^72?2:0;else
n=7*t+7-(c-4)%7;}x[i=n*6+2]=79;if((c=getchar())>32)x[i-1]=c;for(t=0,j=n<9?i+5:i-17;t<3;t++,j+=6)x[j]='|';x[n<13?77:n*6+5]=0;puts(x+(n>4?24:n*6));}

Output:
./a.out
HBb
 bO
 |--
 |
-|---

-----

-----

-----

-----

./a.out
LG#
-----

-----

-----

-----

-----

 --|
   |
 --|
 #O

Global variable are initialised to zero by default, so you don't need to initialise n and you can remove the i=0 in the first for loop.

Also, in the first if statement, ((i%12)&11)==0 can be replaced with !((i%12)&11).

Finally, ?: has a very lower precedence than ^ and <, so you can remove the brackets of the conditions before the ?. And you can replace printf("%s", with puts(.

JavaScript 390 388
A bit of a challenge, I'll have to admit... I'm sure there's ways of reducing this further... I'm open to suggestions...
First Iteration
C=(a,x,o,c)=>{a[x]=a[x].substr(0,o)+c+a[x].substr(o+1)};l=7;s=[];for(i=21;i--;)s[i]="    ";for(j=1;19>j;j+=2)s[j]=" ---";for(k=3;12>k;k+=2)s[k]="-----";~(p="HL".indexOf((n=prompt())[i=0]))&&(l=14*p,i++);l+=(73-n.charCodeAt(i))%7;C(s,l,2,"O");m=n[n.length-1];"#"!=m&   "b"!=m||C(s,l,1,m);o=7<l?3:1;for(z=0;3>z;C(s,t=l-2*o+3+z++,o,"|"));S=s.splice(3<=l?3:l,11>=l?11:l);console.log(S.join("\n"))

Second Iteration (using n.slice(-1) instead of n[n.length-1]), shaves 2 bytes
C=(a,x,o,c)=>{a[x]=a[x].substr(0,o)+c+a[x].substr(o+1)};l=7;s=[];for(i=21;i--;)s[i]="    ";for(j=1;19>j;j+=2)s[j]=" ---";for(k=3;12>k;k+=2)s[k]="-----";~(p="HL".indexOf((n=prompt())[i=0]))&&(l=14*p,i++);l+=(73-n.charCodeAt(i))%7;C(s,l,2,"O");m=n.slice(-1);"#"!=m& "b"!=m||C(s,l,1,m);o=7<l?3:1;for(z=0;3>z;C(s,t=l-2*o+3+z++,o,"|"));S=s.splice(3<=l?3:l,11>=l?11:l);console.log(S.join("\n"))

Ungolfed version:
function C(a,x,o,c){
    a[x]=a[x].substr(0,o)+c+a[x].substr(o+1);
}
l=7;s=[];
for(i=21;i--;){
    s[i]="    ";
}
for(j=1;19>j;j+=2){
    s[j]=" ---";
}
for(k=3;12>k;k+=2){
    s[k]="-----";
}
i=0;n=prompt();
p="HL".indexOf(n[i]);
if(p>=0){
    l=14*p;i++;
}
l+=(73-n.charCodeAt(i))%7;
C(s,l,2,"O");
m=n.slice(-1);
if((m=="#")||m=="b"){
    C(s,l,1,m);
}
o=7<l?3:1;
for(z=0;3>z;z++){
    C(s,t=l-2*o+3+z,o,"|");
}
F=Math.min(3,l);
L=Math.max(11,l);
S=s.splice(F,L);
console.log(S.join("\n"));

Could you add an ungolfed (readable) version, please?

@m.buettner Done... I hope it helps give you a better understanding of what I've done :)