text:
Find the absolute value of a number without built-in functions
The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge.
As per Quincunx's suggestion, I am limiting input to anywhere between -9E99 and 9E99.
Also, the only functions/operators you can use are input, output, return, +, -, *, /, %, ^ +=, -=, *=, /=, >, <, ==, >=, <=, !=, square, and square root or their equivalents

Is the program allowed to loop forever and continue receiving input, finding the absolute value, and outputting it?

take any real number as input. I believe that no program can do this. Most solutions here won't work for -10^-googol for instance. Maybe you should restrict it to double values or something similar. But the what about -π? Programs that only allow doubles wouldn't work. Also, what about something like π-4?

My answers can handle all these values @Quincunx

And yes, it is allowed to loop if you want.

Umm, with those limited input values, only arbitrary precision/length integers work. Any regular floating point, etc won't work (can't store values that high). And are you talking about the infinitely many reals between those two? Also, your answer can really handle -10^-googol (ie -10^(-10^1000), something like -0.(1000 zeros)1). If it can, can it handle -10^(-googol^(googol^(googol^googol)))? That is a real number too. And -π is not exactly representable by decimal numbers (irrational), so almost every solution here fails.

@Quincunx As I said, all answers have a limit of -9E99 and 9E99. Also, pi is a real number so it must be handled.

let us continue this discussion in chat

@Quincunx Fine with me

@Timtech: Can you clarify "You may not use any built-in functions"? For example, does the GolfScript answer violate this rule when it uses the built-in split functions? Or did you just mean built-in functions that are specifically designed to calculate the absolute value?

@musefan You may not use any built in functions (math operators are not included, they are not functions). The GolfScript answer did violate the rule; that's why it's not accepted.

@tim Why don't operators count as functions? In C and friends you can override operators and use them just like normal functions. This seems to be a very vague rule

@Doorknob I don't use that many C-related languages.

Well, irrelevant - operators in those languages are functions too. (Same in many many other langs.) So why don't those count?

@Doorknob If math operators aren't allowed either, how would you even write valid code to do this?

-1. Question is vague and the definition of "built-in function" has only appeared in the comments 3 days after the question was posed. It seems like you're just looking for the shortest way to say printf(x*(x<0?-1:1)) in a number of languages.

You say single character math operations are allowed. This means that something like python's ** should be allowed because it is exactly equivalent to ^ (raise to the power). Either this or other answers with powers should be disqualified.

What if absolute is a single-characters math operator in my language?

Sorry @NBZ but it's not one of the acceptable functions/operators in the last lines.

Apart from the fact that the question as currently written seems to permit a whitelist of operators but only if they're not built in to the language, this is a classic example of why trying to whitelist permitted operations is a disaster. Consider >: in some languages it returns 0 or 1; in other languages it returns true or false and Booleans can't be cast to integers. Should languages in the second category be permitted to use ?: in contexts which could be algebraically rewritten in terms of the condition as 0 or 1 under the "or their equivalents" grant? It's extremely fuzzy

Does putting the value on the stack count as returning it?

J, 2 bytes
**

Usage:
   f =: **
   f 9.3
9.3
   f -9.3
9.3

Explanation:
This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).

If you write it as (%*) you also get complex magnitude for no extra characters.

Wouldn't this be considered a built-in sgn function?

GolfScript, 4 characters
I believe I win. ;)
Works with integer or decimal numbers of any length.
'-'/

Try it online
These programs do the same and are of equal length:
'-'-

'-'%

GolfScript (old version), 16 13
My first GS program! (that actually does something)
Doesn't work with decimal numbers because GolfScript doesn't have floating point.
~:$0<{0$-}$if

Try writing a version that does support floating point (like my Befunge version now does)

@Quincunx Challenge accepted ;) after I get back to a computer; commenting from a phone right now

@Quincunx Done, 4 characters :)

It looks like you just remove all instances of the minus sign (what I would do if I knew a fast way of doing so). What does / do?

I don't know any GolfScript, but it looks like / is the "remove" character.

@Quincunx, it splits the string, so if the input is '-3' it will create an array ['' '3']. The remove character, which would be a more sensible way to do this, is -. But this is in any case arguably cheating.

@peter Why is this cheating? Also, if you use % instead of / the empty string will be removed, but it doesn't matter since the output is the same

I said arguably cheating: the spec is vague on whether inputting and outputting a string is acceptable.

@PeterTaylor Nevertheless, that's the way GolfScript takes input, and the output is the same so that doesn't matter at all.

Doesn't this break the rule of "You may not use any built-in functions"? (as defined here as built-in)

@musefan Well, by that logic, the C answer breaks the rules because it uses operator< and operator-, the J answer breaks the rules because it uses *, the Perl answer uses s, the Mathematica uses Sqrt and ², etc.

@Doorknob: yeah, but I can't be bothered to comment on all the answers. Yours has the most votes so I choose this one

@musefan Well, still, using your logic, all of these answers are completely disqualified. Maybe the OP needs to make the question more clear...

@Doorknob: Actually, I don't see the problem with the C one. I think operators are fine. I think it means built-in functions that perform more process intensive action, such as splitting an array... of course, that just my understanding. Like you say, the OP should be more specific

@Doorknob: See recent comments on the question. They explain that your answer violates the rule and is why it has not been accepted. This could also be true for the other answers

@musefan Shall we start discussing that / is not a function but an operator???

@Howard: No thanks, you call it what you want. I am not making the rules on whats accepted so it doesn't matter what I think

I'm late to the party, but the question specifies a clear and restrictive list of the operators that are allowed. In the list is the math operator /. The string operator /, no so much...

Perl: 5 characters
s/-//

The example:
perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'

This is a good sed answer, too.

J - 7 3
Max of number and inverse (3)
>.-

When assigned to a function: take the maximum between the negative and the number, using a hook so: (f g) y = y f g y
f=:>.-
f _4 5 _1 0
   4 5 1 0

root of the square (5 or 4)
]&.*: _4 5 _1 0
    4 5 1 0
NB. or if an expression is good enough:
%:*: _4 5 _1 0
    4 5 1 0

Negate if number smaller than its negative (7)
-^:(<-)

Takes the inverse (the inverse is bigger than the number itself) times.
Would loosely translate to:
if -num > num then
    num= -num
end

C - 21
#define x(a) a<0?-a:a

This is a preprocessor macro, but does the same thing as Quincunx's Java solution when a real number is used as input.

It needs parentheses around the -a, otherwise it expands to --a.

Mathematica 10 8
Method 1 (8 chars)
Take the square root of a number squared.
Sqrt@#²&
Examples
Sqrt@#²&[-.0176987]
Sqrt@#²&[.0176987]

.0176987
.0176987

Method 2 (8 chars)
Sign returns  -1 if negative, 0 if zero, 1 if positive.
# Sign@#&

Examples
# Sign@#&[-4.3]
# Sign@#&[4.3]

4.3
4.3

4 chars?
As the following picture shows, it is possible to legitimately reduce the function, but I haven't been able to replicate the input on SO.

5 chars: √#^2&

I was trying that but I couldn't get a rendering of the square root symbol as it would actually be used in Mathematica (it would actually contain the #^2.) #^2 should be possible to show with two symbols, but I couldn't find a way to show that either.

What about #²?

Thanks! That works. How did you manage to generate it? (I copied and pasted your example.) Btw, I've tried pasting Latex and MathML code for the square root, with no success.

Dead caret followed by 2 yields ² for me (on Linux using xkb and a keyboard layout that happens to use dead-key variants for ^ ~ ¨ etc). Same goes for other digits and ⁻ ⁺ ⁽ ⁾ ⁼.

@FireFly Sqrt@#² yields a real number; Sqrt@#^2 yields a complex number.

Brainfuck, 40 chars
+++++[>+++++++++<-],[->->+<<]>[>.>],[.,]

Or 35 chars if wrapping is allowed.
-[+>+[+<]>+],+[->->+<<]>[>-.>],[.,]

Python CLI, 20
lambda x:[x,-x][x<0]

"output or return the absolute value". Doesn't that imply that this needs to be in a method? Otherwise, some of my code can be vastly shortened.

Yes, this doesn't count. It has to take input and return or output.

@Quincunx fixed

Needs minor adjustment. (lambda x:[x,-x][x>0])(42) returns -42.

must by lambda x:[x,-x][x<0]

This isn't reusable though, should you include something like g= before it? Or is this really ok?

@Quincunx No.  At the commandline, you can call _(x) immediately after executing the above to compute the absolute value of x.  Or if you want to use the function more than once, you can say g=_.

APL, 5
×∘×⍨⎕

A function would be 4 chars
×∘×⍨

Explanation
×, when used with one argument, is the signum function; when used with two arguments, is multiplication.
∘ is the compose(combination) of two functions.
×∘× is a function that takes two arguments and return the left argument times the signum of the right arugment.
⍨ means "use right argument as both left and right argument".
⎕ takes input from screen.

×× should be enough, as per this J answer.

C: 13 characters
I would assume using overloaded operators are not permitted? Just because something is abstracted and doesn't follow the standard formatting of a function call doesn't mean it isn't a function.
For example:
(**)n <==> abs(n) <==> '-'/
Anyways, here is my code:
With explanation:
n+: ==>  +(true - false) ==> +(1-0) ==> +1
n-: ==>  -(false - true) ==> -(0-1) ==> -(-1) ==> +1
a=n*(n>0 - (n<0))

Yes, abs is not permitted

I understand that. That is why I don't believe the people posting overloaded operands should be permitted either. Since those are functions, just without the typical wrapping.

It's just that so many people are... but have an upvote :)

How is '-'/ an overloaded operand? It just takes a String, splits it on the - character (removing such characters from the output), then prints it. This is definitely not equivalent to abs(n) (as your <==> (iff) suggests.

@Quincunx Splitting a string is a function

Haskell, 14 characters
sqrt.flip(^)2$

J, 13
Without using build-in functions (like signum and the like):
f =: -`]@.(0&<)

f -1.253
1.253
f 0.91235
0.91235

Python 2.7 (16 charcters)
This one is the shortest here in python.
(input()**2)**.5

Let n = input(), then

+1, definitely a great answer. Wouldn't **.5 work though?

@Timtech Yes, I didn't think of that. Thanks. BTW This is my first answer here.

EXCEL, 10:
=SQRT(n^2)

-- n is a defined cell name with the input value.

Is using SQRT() really ok with the rules?

@yeti - it's listed in the question...

Ok... maybe I just was too tired to get my eyes open wide enough... :-\

VBA version of this, 12 bytes ?([A1]^2)^.5

TI-Basic, 3 bytes
Outputs square root of input squared.
√(Ans²

Alternates
√(AnsAns          3 bytes
Ans²^.5           5 bytes
max(Ans,-Ans      5 bytes
Anscos(angle(Ans  5 bytes
-min(Ans,-Ans     6 bytes
If Ans<0:-Ans     7 bytes
Ans-2Ans(Ans<0    8 bytes
Ans(2(Ans>0)-1    10 bytes
Ans(-1+2(Ans>0    10 bytes

Maybe edit this into your other answer instead? (I'll undownvote it if you do)

@ThomasKwa Didn't notice that other answer (that was a while ago), thanks for the notice, I'll delete it and add a better version as an alternate here.

There's also Anscos(angle(Ans at 5 bytes, which is interesting.

Thanks for that suggestion - it's smart since cos(x) = cos(-x)

That's not how Anscos(angle(Ans works. angle( returns pi for negative numbers and 0 for nonnegative numbers. cos( returns -1 for pi and 1 for 0. Therefore, you're multiplying the number by its sign function, except for 0 which doesn't matter.

Interesting, nice alternative :)

Python - 31 28 26 24 23 18
Uses boothby's idea of a lambda function, saving 5 characters (or 3 if I need to assign it to a variable):
lambda x:(x*x)**.5

Old Methods
Uses a generator function to save 1 char, so it is necessary to print the value with some function that uses a generator/iterator, like for i in a(b):print(i)
def a(b):yield(b*b)**.5

Saved 2 3 characters by squaring and unsquaring.

def a(b):yield(b<0)*-2*b+b

Old one:
def a(b):yield b if b>0 else-b

Edit: saved two characters by factoring b in.

JavaScript 26 13
alert((b=prompt())<0?-b:b)
Reducing it further with fat arrow functions...
a=b=>b<0?-b:b
Et voila! Reduction by 50%! Only issue is that this now only works for Firefox 22 and above with thanks to the fat arrows...

You don't need a=.

C, 19
Slightly more than some other C answers, but guaranteed branch-less. the f variable is a float. I hope the bitwise operator & is allowed.
*(int*)&f&=INT_MAX;

Inspired from http://devmaster.net/posts/9998/the-ultimate-fast-absolute-value

Nice one - clears the sign bit. But the question requires numbers between -9E99 and 9E99 - you need double.

@urogen — unverified: *(long*)&f&=LONG_MAX; where f is a double.

Seriously, 8 7 4 3 bytes
Thanks @quintopia
My first Seriously answer, to a 2 yr old question!
Note the challenge is older than the language
,ª√

Seriously is a stack based language. What this does is it pushes the input on the stack, then multiplies if with itself. Then it takes the square root of the result. It is based on the fact that sqrt(x^2)=|x|.

1½ is shorter than 21/.

Also try it online.

Put the 1/2 at the beginning of the program and you can avoid stack rotation. Also, since the question says square and square root are allowed, you can do this in 3 bytes by using those two commands.

Java - 36
This is the obvious solution.
double a(double b){return b<0?-b:b;}

Is the semicolon required? I do more JavaScript than Java.

@Timtech Yes. Every Java statement, apart from code blocks, needs a semicolon

Ruby, 15 characters
a=->b{b>0?b:-b}

Ruby, 22 chars (with I/O)
p (a=gets.to_f)>0?a:-a

Accepts input on stdin, outputs on stdout

Befunge 98 - 11 7 8
~:'-`!j,

Explained:
~  read character input
:  duplicate
'- fetch - and push it
`  compare duplicated value with it, 1 if first is greater, otherwise 0
!  if the number on the stack is 0, set it to 1, otherwise 0
j  jump the number of characters on the top of the stack, which is 1 if the input character is -
,  print the character on top of the stack

If I understand this correctly, then this works for any input, but only if constant looping is allowed. It simply prints everything but the minus sign. If infinite looping is not allowed, then this should work (13 10 chars (Thanks FireFly)):
~:'-`!j,#@

Old version (Befunge 93) - 11
&:0`2*1-*.@

It works like this:
& push input
: push a duplicate
0 push a zero
` pop duplicate and 0, if duplicate greater than 0, push 1 else 0
2 push a two
* pop the 1 or 0 and 2 , multiply the 1 or 0 by the 2
1 push a one
- pop last two values and subtract the second value on the stack by the first (ie a-1)
* pop last two values and multiply last two values on stack (ie + or - 1 * input)
. print
@ end program

Note: Only integers are valid numbers in Befunge.

If I need to support floating point input, then it is 18 chars:
&&\:0`2*1-*.".",.@

It is 17 chars in Befunge 98:
&&\:0`2*1-*.'.,.@

Note: these print a space before the decimal point

I'm sorry, but the program has to be able to accept any real number as input.

@Timtech Well, if the programming language is not capable of that, then...

@Doorknob It happens. Learning multiple programming languages may be the way to go.

@Timtech notice that I have three answers in different languages...

I know, I was talking to Doorknob.

@Timtech I have answers in 2 PLs as well :P

@Doorknob I see. I will add some more :)

:O I had no clue ' fetch character existed. Oh, and you need ot negate the greater-than I believe. Also, for the non-infinite-looping version, ~.'-backtick!j,#@ works (~ acts as a reflector on EOF in B98).

@FireFly Is the . after the ~ supposed to be a :? It appears to work correctly when it is. Also, I think I need a ! in the infinite looping version (see edit)

Oh, yeah, you're completely right about :.  Yup, looks good now.

Clojure 13 18 chars
#(max %(- %))

i am not sure if max is allowed, but i have seen others use it so here it goes :)
after the debate in the comments below, it was decided that max is indeed allowed!
use it like that:
(#(max %(- %)) -2) ; returns 2

edit - it seems max isnt allowed, so lets resort to the trivial solution
a trivial solution:
#(if(< % 0)(- %)%)

or
#((if(< % 0)- +)%)

I'm sorry, max is not allowed. No hard feelings, I am not supportive of all the answers that break the rules.

@Timtech max can easily be defined mathematically: max(x,y) = if x < y then y, otherwise if x not < y then x (or in a set: {((x,y),z)|if x > y, z = x or if x not > y, z = y}). This is a function from reals to the reals. As such, I would say that max is allowed, for the same reason that sqrt is.

@Timtech Here is another definition: http://www.physicsforums.com/showthread.php?t=337952

@Quincunx I understand that it can be defined mathematically, and I am fine with that.

C# 6.0, 29 bytes
double m(double n)=>n<0?-n:n;

Note that this uses a feature of C# 6 (designed some time after the challenge was posted).

@VisualMelon Included C# 6.0 note there.

MATLAB, 10 bytes
@(a)a^2^.5

Pretty straight forward. We are allowed sqauare and square root, so the absolute value of a number (assuming it is not complex!) is simply square it then square root it.

Burlesque, 4 bytes
XXim

XX returns the digits of an integer and im converts the digits back to an integer. XX removes the sign.
You might also go with Jsn?* depending on the exact types.

If the integer given does not contain any duplicate digits then you can use NB. See, that's what makes golfing fun. Exploiting every trick to pass testcases :).

Swift, 35 bytes (Not Competitive)
This is just for fun, and because Swift was developed after this question was posted, is not a competitive answer.
func a(v:Int)->Int{return v<0?-v:v}

un-golfed version
func absolute(value: Int) -> Int{
   return value < 0 ? -value : value
}

It is important to note that the language was invented after the challenge and therefore it technically is not a competitive answer.

Prolog, 22 bytes
Saves 7 bytes over printing as we were allowed to return the absolute value.
Code:
p(X,Y):-Y is(X^2)^0.5.

Explanation:
Input X is squared, taken the root of and returned as Y.
Example:
p(-9.0e99,X).
X = 9.0e+99

Milky Way 1.1.5, 13 bytes
':0e?{_^_;-}!

Explanation
'              # read input from the command line
 :             # push a duplicate of the TOS to the stack
  0            # push 0 to the stack
   e           # push the truth value of A > B where A and B are the top two stack elements
    ?{_ _  }   # if-else statement
       ^       # pop the TOS without outputting
         ;     # swap the top two stack elements
          -    # push the value of A - B where A and B are the top two stack elements
            !  # output the TOS

Usage
./mw <path-to-code> -i <input-integer>

PHP, 30
<?=($n=$argv[1])*(1-($n<0)*2);

Gema, 2 characters
Same as edem's
Perl answer.
-=

Sample run:
bash-4.3$ gema -p '-=' <<< '-82.923'
82.923

Python - 27 chars
>>> f=lambda x:-x if x<0 else x
>>> f(-19.768)
19.768

-1. This does not comply with the specs. It does not return the absolute value, it simply negates the input (try f(300)). Fix it and I'll revert the vote.

oh duhh... fixed it

PowerShell: 38
Lazy if/else. Maybe I'll find a shorter way later.
if(($x=+(read-host))-lt0){-$x}else{$x}

R 17 characters
max(n<-scan(),-n)

Or 13 characters by adapting David Carraher Mathematica answer:
sqrt(scan()^2)

Max isn't allowed; I'd recommend switching to your 13 character solution.

Ti-84 Table, 12 5 characters
The text in brackets are the square root character and the squared character, respectively.
Y=[square root]X[^2]

The old code:
Y=X(2(X>0)-1

Both of these handle rational and irrational numbers. Any real number is valid, with limits of -9.99999999*10^99 and 9.99999999*10^99 for the second one and sqrt(-9.99999999*10^99) and sqrt(9.99999999*10^99) for the first one.
Gets input on X and shows equivalent absolute number as Y.

Square root is a function.

@Gareth It's dealing with mathematics.

PowerShell, 22
(read-host)-replace'-'

Or, if the returned value has to typed as numeric, 23:
+(read-host)-replace'-'

F#, 30
let a x=if x<0. then -x else x

Python (20)
lambda x:x*2*(x>0)-x

AWK, 15
1,$0*=$1<0?-1:1

Note that, the following code can handle all values except 0
AWK, 13
 $0*=$1<0?-1:1

No one use sed? similar as perl
s/-//

Duplicate of http://codegolf.stackexchange.com/questions/15668/find-the-absolute-value-of-a-number-without-built-in-functions/15693#15693

PHP, 40
<? $n=$argv[1];if($n<0) $n*=-1;echo $n;

SQL - 43 chars
SELECT CASE WHEN @n<0 THEN -@n ELSE @n END;

Which SQL dialect? MSSQL lets you skip some spaces and the semicolon (40 chars): select case when @n<0then-@n else @n end, MySQL handles boolean (22 chars): select((@n>0)*2-1)*@n;.

@manatwork, I was aiming for a DBMS agnostic answer. In MySQL, this would save 1 more char: SELECT(@n>0)*2*@n-@n; And the semicolon is not strictly needed in any dialect.

Arcyóu, 16 bytes
(F(x)(^(^ x 2).5

This is an anonymous function taking one numeric type. It returns a floating point number equal to the number's absolute value. This is just nested exponentiation.

FP15 (7)
(*)sqrt

The (*) function squares a number. How does it work? In Haskell, (2*) means \x -> 2 * x and (*2) is \x -> x * 2, but (*) isn't \x -> x * x. In FP15, you can do (*) and even things like (*2+1) and (^2 - 5*sqrt). Also, in FP15, function composition is left-to-right.
Examples (~ is negation):
$ ./fp15-repl.py
> 12(*)sqrt
12.0
> 0(*)sqrt
0.0
> ~12(*)sqrt
12.0

If the signum function is allowed:
(*sgn)

If conditionals are allowed:
{(<0):~|_}

If max is allowed:
(~.max)
[,~]max

I created this language and it's still work in progress (no IO functions for now), but the last time I worked on it was early October.

Go, 62 bytes
Pretty straightforward, I should think. Submitting a noncompilable standalone function feels so... wrong.
func a(){a:=""
Scanln(&a)
b,_:=Atoi(a)
if b<0{b=0-b}
Print(b)}

Rotor, 2 bytes
sS

Challenge predates this language by two years, so this isn't competitive.
Squares input and then square roots it. Nothing special.

Note: this answer was written before the rule change mess, and was valid at time of posting.

Mouse-2002, 11 bytes
The DUP word is two bytes too long, and it requires a space after it. :(
However, it still costs less than a var. (2 bytes per use)
?&DUP 0<[_]

Expanded:
?      ~ input
&DUP   ~ dup
0 <    ~ cmp
[      ~ if
  _    ~ signflip
]      ~ fi

Or, if leaving the value on the stack is not sufficient, then 12 bytes:
 ?&DUP 0<[_]!

This language needs implicit printing if nothing was.

$ mouse abs.mou
-100e99
100e99
$ mouse abs.mou
-INF
INF
$

Do I get a bonus if my program can compute every real number?

LISP, 38
(define (abs x)
 (cond ((< x 0) (- x))
        (else x)
        ))

Please add also the character count.

Ti-Basic 84, 10 bytes
Ans(2(Ans>0)-1

Do you not need to close the outer parenthesis?

@PeterTaylor No, it is not required.

This doesn't work.

Fixed! Input & output on Ans which is the standard

I won't remove my downvote, because this is essentially your third redundant TI-BASIC answer.

Dude do you stalk my answers or something?

authors: набиячлэвэлиь


text:
The Most Useless Program EVER!
Inspired by The Most Useless Machine Ever.
Write the shortest program that does the following:

create a graphical window, then immediately close the window and exit the program.
do this in some visually apparent manner. Like the "arm" that pushes the switch in the machine, the program must use some visual method in the GUI to close itself.
this visual method must be what causes the program to close; you cannot just show it as something on the side (though there may be other things off to the side)

Note:

The program does not have to be visible long enough for the visible activity to be seen by a human as long as the activity is the cause of the closing.
The window must be a GUI (must display a graphical window that contains the visible exit method).
The visual method needs to be something the user could do if it wasn't done automatically. Explain what needs to be changed in the code for the user to be able to do this (Thanks to Iszi).
The program must close if there is no interference from the user, but if the user interferes, then it does not need to close automatically.
Please include an explanation of what it is that causes the program to close.

Example: a window containing a button which is programmatically clicked, running a short snippet of code that closes the program.

I'd suggest that, for programs not visible enough to be seen by a human, answers should include mention of what should be changed in the code (adding/increasing timer values, etc. - but not fundamentally changing its functionality) in order to demonstrate to a human that it actually does something visual.

Should this be code golf or a popularity contest?

I've changed my TI-BASIC answer to a compiled version that is shorter than my other answer (which is currently accepted). I'd appreciate it if you could change that :)

I'm curious why this question is being DVd and VTCd. For one, this has an objective winning criterion; it's a [code-golf]. I can understand that this isn't the best question, but why is it being VTCd?

TI-Basic, 3 bytes
DispGraph:1

hex: 31 3E DF

Explanation
DispGraph Displays the graph (a graphical window)
:1 Simulates a press of 1 (by storing 1 to Ans at the last step of a program), which takes the calculator back to the home screen. A user could do the same thing.

GTB is kind of stupid considering that the symbols for each command are stored a 2-byte values.

Concurred, I (from inspection using CalcSys) would count as 6(perhaps 4, not sure if all OSs use single-byte tokens for : and 1). Filesystem overhead and tables are obviously not included in the count.

What do you mean by compiled? TI-BASIC is interpreted.

@Jakob Back then I was more confused about how TI-Basic worked. What I should have said is the source is 3 1-byte tokens. Let me fix this answer

@Jakob There we go. I think back then we were scoring TI-Basic programs by ascii byte count rather than tokens

Oh yeah, I wondered if the age of the answer had something to do with it. Thanks!

Ruby with Shoes, 110
Shoes.app{button('Close'){exit}
p=para
t=Time.now
animate{u=(t-Time.now).to_i+10
exit if u<0
p.text=' '*u+?<}}

Makes a little arrow that pushes a "Close" button. (Pushing the close button manually also closes the window.)

Windows Batch, 4 bytes
Save the following program to a .bat file in your user folder (C:\Users\username):
Exit

When executed from the Start, Run prompt, a new window opens, types the command Exit and executes it.

"The window must be a GUI (must display a graphical window that contains the visible exit method)." - it's arguable if your window contains the visible exit method, I'd say it doesn't.

@gronostaj It has an X in the top-right corner.

Ah, I see - you're exploiting the rules. There is a visible method to exit and user can do the same thing program does, but those are two different methods to terminate it. That's clever, +1.

Creating a .bat with only a space character: 1 byte?

@SEarle1986, the space character wouldn't cause the program to exit.  It would exit because it reached the end of the batch file.  Exit will cause the window to close before the batch file completes.

JavaScript: 133 117
(You need to allow popups in your web browser for this to work)
Code-golfed:
(function(){w=window.open(),d=999,i=setInterval(function(){w.resizeTo(d-=9,d),d<0&&(clearInterval(i),w.close())})})()

Source:
http://jsfiddle.net/gt2t8/2/

Why does it resize?

@Quincunx do this in some visually apparent manner. Like the "arm" that pushes the switch in the machine, the program must use some visual method in the GUI to close itself.

reduced to 117 chars: (function(){w=window.open(),d=999,i=setInterval(function(){w.resizeTo(d-=9,d);if(d<0)clearInterval(i),w.close()})})()

@Griffin thanks! Updated with your suggestions

One that I can run without leaving the page. Awesome.

Always think JS answers should get -75, so I don't have to leave... and then +50 for having to disable popups

Golf-Basic 84, 5 4
g`:1

Display the graph, simluate a press of 1, closing the graph and returning home.

Does this do the same as your other answer?

@Quincunx Yes, it does.

x86 / Win32 assembly (337 310 271 bytes)
.586
.model flat
option casemap:none
include kernel32.inc
include windows.inc
include user32.inc
i textequ <invoke>
.code
s:i CreateThread,0,0,$+46,0,0,0
i MessageBox,0,$,$,0
i ExitProcess,0
i Sleep,999
i FindWindow,0,$
i PostMessage,eax,256,13,0
ret
END s

Assembles with MASM32 (ml /c /coff /Gz /I<include path> test.asm / link /SUBSYSTEM:WINDOWS /LIBPATH:<library path> test.obj kernel32.lib user32.lib).
It creates a MessageBox with an "OK" button, and a thread that simulates a carriage return press from the user after 999 ms.
The $ is substituted with the address of the beginning of the code section by the assembler/linker. The first instruction is a push byte 0 (implicitly, since it's generated by the invoke), which is encoded as 6A 00, which equals the null-terminated string "j". I take advantage of this when calling MessageBox and FindWindow.

Is the assembly 271 bytes, or is that the size of the machine code?

Bash with X Window System, 10 chars
xterm -e :

Open an xterm window, run the bash no-op :, after which the xterm window closes.
If you want to see the useless window for a second, you can change the : to sleep 1:
xterm -e sleep 1

Tcl/Tk, 131
grid [button .b -command exit]
event generate .b <Button-1> -warp 1 -x 5 -y 5
event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5

Tcl/Tk, 136
grid [button .b -command exit]
event generate .b <ButtonPress-1> -warp 1 -x 5 -y 5
event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5

It needs to be ran on an interactive shell, line by line and user can not move the mouse between.

Application starts

Button whose behaviour is to close the app is added to the app window

Generate an event that presses down the mouse on the button — Altough the cursor is not visible in the screenshot it is over the button; it is visible the buttonhas been pressed because it now sunken in, and before it was embossed out.

Finally generate an event that releases the mouse button up.
a. Image before really sending it (before pressing Enter)

b. After Enter the interactive shell and the app windows just disappeared.

Note to tcl'ers:
Tried to do the same directly on the window's X Close button using:
event generate . <ButtonPress-1> -warp 1 -x 175 -y -10
event generate . <ButtonRelease-1> -warp 1 -x 175 -y -10

but I was not successful.

Bash - echo  (50 bytes)
Not golfed, 54 bytes:
s=sleep;echo -n \>\\;$s 1;echo -ne "\b\b >/";$s 1;echo

Golfed, 50 bytes
I can't exactly display the golf version here because the backspace characters actually backspace.  For the golf version, change both of the "^H" to single backspace (^H) characters:
s=sleep;echo -n \>\\;$s 1;echo -n ^H^H \>/;$s 1;echo

Notes:

The activity is visible for 2 seconds.
It doesn't use a window manager or anything of that sort, but I count the ASCII art as a "gui".  If you are running the command in a terminal window, which is now the usual case, the activity is displayed in that window.  It does not open up a new window.
The user can close the program sooner than the automatic close by hitting "CTRL-C" within 2 seconds of starting the program.  Users who are more comfortable using their GUI can put their cursor on the little "X" in the corner of the terminal window, quickly, and "click" it.
The program closes after 2 seconds if there is no interference from the user.  The user can only cause it to close sooner.
What causes the program to close is the completion of the final "echo".

source: Stack Exchange

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

sort: votes


text:
Check if the 15 puzzle is solvable
The fifteen puzzle is peculiar in that only half the possible states of arrangement are solvable. If you flip the 14 and 15 tiles, there is no way you can slide the blocks so that they are flipped back.
Your task is to build a program that accepts a list of integers in the format of your choice (containing exactly one instance of each of the numbers from 0 to 15, with 0 being the blank space) representing the state of an arrangement of tiles in a 4x4 grid, and outputs a single boolean value determining whether the grid is solvable or not.
The shortest code to do this in any language wins.

Good question :)

I was going to ask this question, but with an arbitrary side-length; but that adds very little to the challenge.

Jelly, 9 bytes
Œc>/€;TSḂ

A monadic Link accepting a list of the integers reading in row-major order alternating between left-right and right-left which yields 0 if solvable and 1 if not (to invert this add ¬ to the right of the code).
Try it online! (this example is a board where 12 just needs to slide into place)
How?
Similar to John Dvorak's answer we calculate parities and utilise a snake-like input order to simplify checker-board parity, although instead of checking equality of parity we sum the out-of-order count with the non-zero indices and test whether that is odd:
Œc>/€;TSḂ - Link: list of integers
Œc        - unordered pairs
    €     - for each:
   /      -   reduce with:
  >       -     greater than?
      T   - truthy indices (i.e. [1..16] without 1-indexed index of 0)
     ;    - concatenate
       S  - sum
        Ḃ - is odd?

J, 28 characters
((C.!.2=_1^i.&0)&.".&.stdin''

The input order is row-major with rows read alternatingly left to right and right to left in a single path across the table. Assumes the zero belongs to the top left corner.
Usage on Windows:
<nul set /p="0 1 2 3 7 6 5 4 8 9 10 11 15 14 13 12" | jconsole c:\...\15.jhs

Explanation:

<nul set /p= is used to prevent a newline in the input, that echo produces that ". doesn't like. Of course, Unix supports echo /n.
v&.".&.stdin'' reads "v under parse under stdin" meaning "input, then parse the input, then do v, then undo parse (= format), then undo input (=output)". 1!:1]3 is one character shorter, but it does not have a defined inverse.
C.!.2 means "permutation parity". It returns either 1 (even parity) or _1 (odd parity). That is, _1^inversions
_1^i.&0 means "-1 to the power of index of 0".
thus, C.!.2=_1^i.&0 means "does the permutation parity equal the hole position parity?"

This works for a 4x4 board, but if the desired end position is row-major left-to-right, then the permutation for the solved position has an odd number of inversions, and thus odd parity. Also, the parity is reversed (for any input order) when the desired hole position moves from upper left to bottom right. In both cases, the fix is one character: add - after = to reverse the expected parity.
Proof of correctness:
After each move, the zero exchanges a position with some number, flipping the permutation parity. The zero also alternates between white and black checkerboard positions, indicated by odd and even positions in the input ordering. Thus, this condition is neccessary. It is also sufficient by the counting argument: it is common knowledge that exactly half of the positions is solvable. This condition filters out exactly half of the possible positions.

When you say "the zero also alternates between odd an even positions": doesn't it change by +1, -1, +4, or -4? I think that a checked pattern gives the colouring you need, but it could be described more accurately.

@PeterTaylor you are right; sorry. Does my edit count as a valid fix?

I think your edit addresses a completely separate issue. The bit I quoted is in the last paragraph.

"Between odd and even positions" is more like "between black and white squares on a chessboard".

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

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


text:
Relative dates in words
Given a specific date, have the code output a relative reference:

If the date entered is ahead of the current date, express as "x days from now" or "x weeks, y days from now", or "x years, y weeks, z days from now". Zero units need not be mentioned.
If the date is the current simply have it output "Today"
If the date entered is earlier than the current date, express as "x days ago" or "x weeks, y days ago", or "x years, y weeks, z days ago". Zero units need not be mentioned.

Smallest solutions are the winners here...
Good luck!

JavaScript, 146
Input is a timestamp as number of milliseconds from 1970-01-01 (Unix timestamp × 1000), since this makes things more conventient for me (and no input format was specified).
D=new Date-prompt()
d=Math.abs(D/864e5)
e=d%365%7|0
alert(e?[d/365|0,"years,",d%365/7|0,"weeks,",e,"days",D>0?"ago":"from now"].join(" "):"Today")

R, 102, 98
(kinda cheating: literal interpretation of the question)
cat(if(x<-as.Date(readline())-Sys.Date())c(abs(x),"days",c("from now","ago")[(x<0)+1])else"today")

Examples:
2013-12-08
today

2010-01-13
1425 days ago

2015-12-2
724 days from now

+1 for using "days only" interpretation

can squeeze a few: cat(if(x<-as.Date(readline())-Sys.Date())c(abs(x),"days",c("from now","ago")[(x<0)+1])else"today")

@flodel Thanks for the tip! Great idea to assign the value inside if.

Abuse is within the rules of code golf.

Hey, I was the first to use the literal interpretation and I was shorter :P

Ruby, kinda cheating - 89, less cheaty - 140
Kinda cheating, 89
f=->d{i=((d-Time.now)/86400).ceil;["Today","#{-i} days ago","#{i} days from now"][0<=>i]}

It's a function that takes the date as an argument and returns the string.
Examples:
irb(main):036:0> f[Time.new(2013, 12, 1)]
=> "7 days ago"
irb(main):037:0> f[Time.new(2013, 12, 10)]
=> "2 days from now"
irb(main):038:0> f[Time.new(2013, 12, 8)]
=> "Today"
irb(main):039:0> f[Time.new(2011, 10, 8)]
=> "792 days ago"

Hey, you never said we couldn't use only days!

express as "x days from now" or "x weeks, y days from now", or "x years, y weeks, z days from now". [emphasis mine]

Well, I choose the first one :P Abusing the rules is so fun!
Less cheaty, 140
f=->d{t=Time.new
a=((d-t)/86400).ceil
g='from now'
a,g=-a,'ago'if a<0
a==0?'Today':"#{a/365} years, #{a%365/7} weeks, #{a%365%7} days #{g}"}

Examples:
irb(main):111:0> f[Time.new 2013, 12, 10]
=> "0 years, 0 weeks, 2 days from now"
irb(main):112:0> f[Time.new 2013, 12, 17]
=> "0 years, 1 weeks, 2 days from now"
irb(main):113:0> f[Time.new 2014, 12, 17]
=> "1 years, 1 weeks, 2 days from now"
irb(main):114:0> f[Time.new 2012, 12, 17]
=> "0 years, 50 weeks, 6 days ago"
irb(main):115:0> f[Time.new 2012, 1, 1]
=> "1 years, 48 weeks, 6 days ago"
irb(main):116:0> f[Time.new 2013, 12, 8]
=> "Today"

It said

Zero units need not be mentioned.

But you never said they cannot be mentioned.

C - 348
First CodeGolf post, so I figured that I would have fun with it.
#include<time.h>main(int a,char *v[]){a--;struct tm t={0};char* n=strtok(v[1],"/");while(n!=0){switch(a++){case 1:t.tm_mon=atoi(n)-1;case 2:t.tm_mday=atoi(n);case 3:t.tm_year=atoi(n)-1900;}n=strtok(0,"/");}a=(int)difftime(time(0),mktime(&t))/86400;printf("%s\n",a=0?"today":(a>0?strcat(itoa(a)," days ago"):strcat(itoa(abs(a))," days from now")));}

Ungolfed:
#include <time.h>
main (int a,char *v[])
{
  a--;
  struct tm t={0};
  char* n=strtok(v[1],"/");
  while(n!=0)
  {
    switch(a++)
    {
                case 1:t.tm_mon=atoi(n)-1;
                case 2:t.tm_mday=atoi(n);
                case 3:t.tm_year=atoi(n)-1900;
    }
    n=strtok(0,"/");
  }
  a=(int)difftime(time(0),mktime(&t))/86400;
  printf("%s\n",a=0?"today":(a>0?strcat(itoa(a)," days ago"):strcat(itoa(abs(a))," days from now")));
}

Test runs:
$ ./date 12/8/2013
1 days ago
$ ./date 12/10/2013
1 days from now
$ ./date 12/9/2013
today

Nice work, now the next thing you need to do is compress that sucker as much as you can to reduce your characters, which in turn improves your score... :)

Please remove the unnesscary whitespace - you can post an ungolfed version too. If you post both, I'll upvote it.

@JohannesKuhn Done. That reduced the character count by a ton, thanks!

Python 2 - 134
This is a bit abusive as this assumes the objects given is a datetime.date() object. But you did say it would be given as a date, so...
from datetime import*
D=input()
t=datetime.now().date()
w=str(D-t).split(',')[0]
print[w[1:]+" ago","today",w+" from now"][cmp(D,t)+1]


text:
Enumerate an undecidable set
An undecidable set is a set for which determining whether an object is an element of the set is an undecidable problem
Write a program which runs forever, printing the elements of any undecidable set, each element appearing on its own line.  For any element in the set, there must be a finite amount of time after which your program will print that element.  Each element should only be printed once.
Since you have to enumerate the elements, the set you choose will be RE.
Some examples of undecidable sets which are RE:

Programs of any Turing-complete language which halt.
Post correspondence problem instances with solutions.
Sets of Wang tiles which can't tile the plane.

What is an example of an undecidable set?

Added some examples.

"Programs of any Turing-complete language which halt." So that means we can output print(1+1), print(2+2), print(3+3), etc.?

@Doorknob can you print every valid Python program that halts?

@JanDvorak Wait, so the set has to be finite, but it has to be impossible to test whether an element is in the set, but that's contradictory... set.indexOf(element) > -1

The set will be infinite.

@cardboard_box So I can do the print(1), print(2), etc. thing?

@Doorknob No. The set of valid print-number statements is decidable.

@JanDvorak No, because the set of all positive integers is infinite, right?

@Doorknob No.  You'd have to print all python programs which halt.  Determining whether or not a python program is in the set described is trivially decidable.

@cardboard_box but you can't print all python programs that halt, because just like you said, the set is inifinite

@Doorknob you can, eventually

@JanDvorak No, because if you could, then you could decide whether a program is in that set eventually, so you have solved the Halting Problem

@Doorknob enumerate all: for each python program that halts, there needs to exist a moment in the execution of your script such that that program is printed.

I changed the wording. Hopefully it's clearer now.

ah, thanks @Jan, I think I get it now

@Doorknob you can't solve the halting problem this way. To prove some program never stops, you'd have to watch your generator for infinite time.

Does the domain of truth of an unproven conjencture count as undecidable, or we need something that is proven undecidable?

@JanDvorak it must be proven undecidable.

so, preferably one of these?

@Jan Yes, but some of those aren't enumerable.

One more question: does our generator have to be single-threaded and deterministic? Or at least use a bounded number of threads?

"Each element should only be printed once" - how strict should we be about this? Do we need to filter out two sets of Wang tiles if they only differ in tile definition order? I suppose so. It also makes sense to count rotations and reflections as equal - but this is harder (and expensive) to check. But what about sets of tiles which are only equivalent after recoloring (and 2D rotation and reordering)? Do we need to count [["1212"]] and [["2121"]] as distinct? Checking for coloring/reordering isomorphism is equivalent to the graph isomorphism problem (very expensive).

You can count those as distinct or not.  The set of ordered, rotated sequences of Wang tiles which can't tile the plane is still an undecidable set.

Is the set of Wang tiles that tile the plane periodically undecidable?

Haskell, 404 characters
This Haskell program prints all FRACTRAN programs which halt when given the input 2. (The syntax of a FRACTRAN program is a list of positive rational numbers.)
import Data.Ratio
import Data.List
import Data.Either
r=do
 z<-[1..]
 let r=repeat z
 (p,q)<-zip r[1..z]++zip[1..z]r
 if gcd p q==1 then[p%q]else[]
o l=d[map(:xs)r|xs<-l]
e p n=n:maybe[](e p)(find((==1).denominator)$map(*n)p)
h p=map Left(e p 2)++[Right p]
main=mapM print$rights$d$map h$d$iterate o[[]]
d=concat.s
s[]=[]
s([]:b)=s b
s((x:a):b)=[x]:z a(s b)
z[]b=b
z a[]=map(:[])a
z(x:a)(y:b)=(x:y):z a b

I have made no great effort to compress this program. Furthermore, the GCD test in the definition of r is purely an optimization (it avoids duplicates).
(Also, If you are interested in running it, be sure to compile it, perhaps with optimization; I found that running it in ghci quickly consumed gigabytes of memory.)
It operates by successively constructing infinite lists of infinite lists and then flattening them in a diagonal order: the list of all positive rational numbers, the list of all lists of positive rational numbers (all programs), and the list of all evaluation states (including “halted”) of all programs. We then print only the halted states (which are annotated with the program which halted).
Here is the uncompressed and commented version:
import Data.Ratio
import Data.List
import Data.Either

-- List of all positive rational numbers
rationals = do
  limit <- [1..]
  let r = repeat limit
  (p,q) <- zip r [1..limit] ++ zip [1..limit] r
  if gcd p q == 1 then [p%q] else []
-- List of all lists of positive rational numbers (all FRACTRAN programs)
programs = diagonal $ iterate oneMore [[]]
oneMore l = diagonal [map (:xs) rationals | xs <- l]

-- FRACTRAN evaluator
evalStep p n = find ((== 1) . denominator) $ map (* n) p
evaluation p n = n : maybe [] (evaluation p) (evalStep p n)
evaluationWithHaltMarker p = map Left (evaluation p 2) ++ [Right p]

-- All evaluation states of all programs
evaluations = diagonal $ map evaluationWithHaltMarker programs

-- All halting programs
haltingPrograms = rights evaluations

main = mapM_ print haltingPrograms

-- from http://stackoverflow.com/questions/7141287/haskell-cartesian-product-of-infinite-lists
diagonal :: [[a]] -> [a]
diagonal = concat . stripe
    where
    stripe [] = []
    stripe ([]:xss) = stripe xss
    stripe ((x:xs):xss) = [x] : zipCons xs (stripe xss)

    zipCons [] ys = ys
    zipCons xs [] = map (:[]) xs
    zipCons (x:xs) (y:ys) = (x:y) : zipCons xs ys

The Left values are never actually looked at since we don't care about non-halting states; it's just the shortest way I saw to carry through the incremental evaluation.
Some “future work” if one were trying to write a practical implementation to generate interesting programs, rather than golfing, would be to reduce the needed work by restricting the set of programs under consideration to those which:

do not have a statically obvious loop (e.g. an integer).
are unique under “register renaming”; e.g. [3/2, 5/3] is the same as [7/2, 5/7].
have no dead code under the assumption that the input is 2; e.g. in [5/3, 7/2], 5/3 is dead code because no 3s are in numerators.
have no dead code due to preceding code; e.g. in [3/2, 5/2], 3/2 will always take precedence over 5/2.

I mention these cases in particular because (other than the looping one) they form the majority of the output. As far as I've run it, it has not produced any output program of length greater than 2.

Haskell, 232 characters (with line breaks removed)
This Haskell program prints all solvable Post correspondence problems over the alphabet {A, B}. (Actually, it prints only the ones that actually use every tile at least once. But this shouldn't affect the undecidability of the set.) Each set of tiles is sorted (using Haskell's sort function; I don't know how that works on lists of tuples of strings, but it does) and de-duplicated (using nub), and the entire list of solutions is de-duplicated as well.
It works by generating all strings, and then, for each string and for each number n up to twice the length of the string plus one, generating all pairs of ways to break the string into n pieces. The d function generates all ways to break a string s into a number n of pieces. The program takes advantage of the fact that in Haskell, do notation on lists simulates non-deterministic choice.
(If I'm not mistaken, "twice the length of the string plus one" is the greatest number of distinct tiles a string can serve as a solution string for. For example, "AB" is a solution string for ("","A"), ("","B"), ("A",""), ("B",""), ("","").)
The sequence command, as used right after s <- (but not as used right after main =), returns all ways of selecting one element from each of a list of lists; for example, sequence ["abc", "123"] is ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"].
import Data.List;
main=sequence.map print.nub$do{
n<-[1..];
s<-sequence$replicate n"AB";
p<-[1..n];
u<-d p (s*2+1);
v<-d p (s*2+1);
return.nub.sort$zip u v
};
d 0""=[[]];
d 0_=[];
d n s=do
f<-[0..length s];
c<-d(n-1)(drop f s);
return(take f s:c)

With the line breaks, this is 246 characters, but all of the line breaks can be removed.


text:
Type out Green Eggs and Ham in vim
The book Green Eggs and Ham by Dr. Seuss is famous for only having 50 different words in the entire story of the book.
Your task is to create a sequence of keystrokes that will result in the entire text of Green Eggs and Ham when applied to an empty file in the vim text editor, starting in normal mode with all default settings. Your keystrokes must not load any other files as part of their operation - all text must be generated within the editor itself.
Your final buffer must look exactly like this file, although it can remain in whichever mode it ends up being in (you don't have to have a final <Esc> to return it to normal mode).
Chorded keystrokes like <C-o> or using Shift to type a capital letter count as a single keystroke.
The sequence of the fewest keystrokes to achieve this goal wins.

If somebody wants to create the Emacs equivalent of this question, they can. I'm not familiar enough with Emacs to know if it would make for an interesting question at all.

Also, "with all default settings" means that you aren't allowed to load settings from a .vimrc file.

Based on your "canonical" insert-entire-file answer, I take it the mode you leave the editor in after the insertion doesn't matter. Maybe this should be explicitly specified to clarify (i.e. you don't have to  out from insert-mode).

Yeah, you don't have to <Esc> out from insert mode, but you do have to start in normal.

As I see it, this question is on the edge of being off-topic. It's not a codegolf, it's a vimgolf (there is a page for that, a good one. Anyone interested should take a look). I also find the text to be too long, making it very time consuming to golf.

You lied: it is 51 words. Now I have to start over. (kidding)

It's more than 51 if you count capitalizations as different words.

Also, there is a small typo in there. I'm not sure if its meant as a test to see who used your reference text or not, so I won't point it out.

fixing the typo brings the unique word count to 50

I didn't even notice the typo myself. Thanks for pointing it out, though - I found it and fixed it.

Is invoking external commands using Vim keystrokes allowed, if the "Your keystrokes must not load any other files" rule is still followed?

If those external commands are not available on a default Vim installation, then yes, it would violate the "loading any other files" rule.

1864 keystrokes
Somebody could probably write some code that produces a more optimal solution, but this beats the reference case for now. This is a damn mess, and I am ashamed I did it by hand.
First, we enter insert mode.
i

Then all this
That ]! That ]!
IDNlike that ]!

Do Y like$?

|;].
IDNlike$.

WPY LTB or tB?

IZ LTB or tB.
IZ LTanywB.
IDNlike$.
|;].

WPY LTin a h@?
WPY LT=a m@?

|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

WPY ETin a box?
WPY ET=a fox?

Not_a box. Not =a fox.
Not_a h@. Not =a m@.
IZ ETB or tB.
IZ ETanywB.
IZ eat$.
|;].

WPY? CPY? In a car?
Eat them! Eat them! B they are.

IZ,X,_a car.

You may LT. You will see.
You may LTin a tree!

IZ,X_a tree.
Not_a car! You let me be.

|in a box.
|=a fox.
|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

AQ! AQ! AQ! AQ!
CPY;wPY;on aQ?

Not_aQ! Not_a tree!
Not_a car! Sam! Let me be!

IZ,X,_a box.
IX,Z;=a fox.
:=a m@.
:in a h@.
:B or tB.
:anywB.
IDNlike$.
|;].

Say! In +? B_+!
WPY;cPY,_+?

IZ,X,_+.

WPY;cPY,_the rain?

IZ,X,_the rain.
Not_+. Not on aQ.
Not_a car. Not_a tree.
|;Sam;Y see.
Not_a h@. Not_a box.
Not =a m@. Not =a fox.
:B or tB.
|!

You do not like$?
|;].

CPY;wPY;=a g^?

IZ,X;=a g^!

WPY;cPY;on a b^?

IX,Z;on a b^.
IWN,WN;=a g^.

:in the rain.
:on aQ.
Not_+! Not_a tree!
Not_a car! You let me be!
|in a box.
|=a fox.
:in a h@.
|=a m@.
|B or tB.
|!

IDNlike$!
|;].

You do not LT. So Y say.
Try them! Try them! & Y may.
Try them and Y may;I say.

Sam! If Y will let me be,
I will try them. You will see.

Say! I like$!
I do! I LT;]!
& I wPETin a b^.
& I wPET=a g^.

!ETin the rain.
&_+. & on aQ.
&_a car. &_a tree.
They are so good;so good;Y see!

So I will ETin a box.
!ET=a fox.
!ETin a h@.
!ET=a m@.
!ETB and tB.
Say! I will ETanywB!

I do so like$!

Thank Y! Thank Y;]!

Hit escape to enter command mode. And unravel the compressed stuff. Order matters, as I've compressed some compressed text.
<Esc>
%s/|/|anywB/g
%s/:/IWNET/g
%s/|/IDNLT/g
%s/Z/ wPnot/g
%s/X/ cPnot/g
%s/&/And/g
%s/+/the dark/g
%s/@/ouse/g
%s/^/oat/g
%s/Y/you/g
%s/IDN/I do not /g
%s/LT/like them /g
%s/]/Sam-I-am/g
%s/ET/eat them /g
%s/WN/ will not/g
%s/$/ green eggs and ham/g
%s/P/ould /g
%s/!/And I will /g
%s/Q/ train/g
%s/B/here/g
%s/_/ in /g
%s/=/with /g
%s/;/, /g

you got the wrong substitution for eat them, it's backwards. and you can cut the leading colons by using ed mode which stays in command mode after commands.

@hildred I actually started with the full text, did a global replace and added the full text to compressed text to another file. Must have forgotten to reverse that one :(

If you replace so good;so good; with <Esc>2aso good;<Esc>a, you can save three keystrokes. Also, replace iThat ]! That]!<Enter> at the beginning with 2iThat ]! <Esc>xo for another three.

Also, since DN doesn't appear elsewhere, you can remove the I from IDN and I do not  in the replace statement with those two expressions in it.

And, replace all instances of IDNlike$!<Enter>|;]. with 1 and input %s/1/IDNlike$!\n|;]./g to save about 20 keystrokes or so.

3,470 keystrokes
i<entire text of file>

The text file is 3,469 characters long, so typing "i" to put it in insert mode and typing out each character individually will take 3,470 keystrokes.

Lol @ pure brute force

This is intended mostly as a last-place reference solution more than anything.

yet it's currently the best contestant as well :-) (no, I'm not going to participate; sorry)

You more of an Emacs person? :-)


text:
Output: Calendar Month (without native calendar generating functions)
Upon receiving month and year in YYYYMM format, generate output of the corresponding calendar month for that year.
For example the input 201312 should generate the following output:
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Only trick is, NO native calendar generating functions... so Linux clones, no "cal" function... Muahahahahah!
PS: The calendar must start out with Monday as the left-most day, this is to ensure that the output is like the "cal" function, but does not output like "cal", which has Sunday as its left-most day...
Smallest code size wins.

You want it to look like a calendar, might want to change your text to say that more clearly. Also, what are the winning conditions?

@Quincunx, you're like my conscience, only digital...

Except I'm not digital...

Close enough, buddy... You're just pixels on a screen here ;)

So... Winning conditions?

"Smallest size wins." size of what? If it is code size, then please change the tag to code-golf

I presume you want the Gregorian calendar, but for what range of years?

Python 2.7 - 152
Unfortunately it fails for September 1752. Granted, it imports all of the calender functions, but only uses 1, and that just returns the start day of the week and the number of days.
from calendar import*
w,l=monthrange(*divmod(input(),100))
print" Mo Tu We Th Fr Sa Su\n"+"   "*w+''.join(["%3d"%s+"\n"*((s+w)%7<1)for s in range(1,l+1)])

Relatively standard code, but this is my favourite bit:
"\n"*((s+w)%7<1)

It prints the new line using string multiplication, if the number of the current day and start day of the week is Sunday (e.g. 7) as the boolean is cast to an integer.
This saves a character on the more intuitive x%7==0 by using x%7<1 instead.
Test output:
> 198210
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

let me guess: you have just translated my approach to another language and it came up shorter. I'm okay with that, but disclosure would be nice.

@JanDvorak Oh no. Not at all. I couldn't even understand yours. To be honest, given the verbose imports I needed, I was shocked it was going to come close to beating yours. Just out of curiousity what is 52.times doing? Its not multiplication?

It's a looping construct. n.times{...} is identical to (0...n).each{...} or 0.upto(n-1){...}. Multiplication would be 52 * ...

@JanDvorak
I played with Python a few years ago in a job I was working in... I found the indent syntax a little bit of a pain... So used to curly brackets I guess...
LOVE the "\n"*((s+w)%7<1) trick... I've never checked to see if this would work in JavaScript... ;)

The Wiki reference you mentioned was interesting... "It reformed the calendar of England and British Dominions so that a new year began on 1 January rather than 25 March (Lady Day) and would run according to the Gregorian calendar, as used in most of western Europe."
I'm surprised the English were a little behind then...?

But the output is wrong? October 1982 still had 31 days.

@user113215 Good catch, that was output from an earlier version that wasn't working. The code in the answer does give the correct calendar (except for September 1752).

Ruby, 170 168 characters
g=gets.to_i
require'date'
d=Date.new g/100,g%100
puts'Mo Tu We Th Fr Sa Su'
l=['']*(d.jd%7)+[*1..(d>>1).jd-d.jd]
56.times{|i|$><<"#{l[i].to_s.rjust 2} #{?\n if i%7>5}"}

Bugfix: didn't require the neccessary library (+16)
used julian date modulo 7 instead of current week day directly (-3)
used /100 and %100 to parse date instead of regex (-13). Taken from LegoStormtroopr's answer.
removed the parentheses around the argument to rjust and Date.new(-2)

Cool. Not tested exhaustively, but seems that you can change "#{l[i].to_s.rjust 2} #{?\n if i%7>5}" with "%2s %s"%[l[i],i%7>5?$/:""].

Mathematica 203
g@d_:=Module[{w={"Mo","Tu","We","Th","Fr","Sa","Su"},c},
c@n_:=" "~ Table ~{n};
Grid@Partition[Join[w,c[Position[w,StringTake[ToString@DayName@d,2]][[1,1]]-1],
Range@DayCount[d,d~DatePlus~{1,"Month"}],c@6],7]]

Testing
g[{2013, 12}]
g[{2014, 1}]
g[{2014, 2}]

Great use of Mathematica!

Vyxal, 87 bytes
k§2vẎṄ,4ȯI:£3<?4ẎIεD4/⌊‟₁/⌊N‟:400/⌊»∧+ż↵`»8τv‹¥Ẏt2Ṡ7%7ε¤w$ẋf»∇ė{»4τ¥Ẏt28+ɾJ7ẇƛƛS2↳;Ṅ;⁋,

Try it Online!
-7 thanks to lyxal.
=== Part 1: Header ===
k§      # Monday to Sunday
  2vẎ   # Get first two letters of each
     Ṅ, # Join by spaces
=== Part 2: What day does it start? ===
4ȯI                                          # Last two (month) as integer
   :£                                        # Store a copy to register
     3<?4ẎIε                                 # Decrement the year if the month is Jan or Feb
            D                                # Calculate:
             4/⌊‟                            # floor(y/4)
                 ₁/⌊N‟                       # -floor(y/100)
                      :                      # y
                       400/⌊                 # And floor(y/400)
                            »...»8τv‹        # Compressed list of the days (mod 7) at the start of each month
                                     ¥Ẏt     # Get the correct item
                                        2    # Add 2 (1 because first day of month, 1 because it ends on Sunday)
                                         Ṡ7% # Take the sum of the whole thing, mod 7.
=== Part 3: Get the whole month ===
7ε                     # Difference from 7
  ¤w$ẋf                # Copies of the empty string
       »...»4τ         # Compressed list of days in each month, -28
              ¥Ẏt      # Get the correct item
                 28+   # Add 28
                    ɾ  # Make a range out of that
                     J # Add on the empty strings
=== Part 4: Format nicely ===
7ẇ           # Divide into chunks of 7
  ƛ      ;   # Foreach...
   ƛ   ;     # For each item...
    S        # Stringify
     2↳      # Align
        Ṅ    # Join by spaces
          ⁋, # Output joined by newlines

Try it Online! for 88 bytes

SmileBASIC, 204 bytes
INPUT Y$Y$[3]=Y$[3]+"/
DTREAD Y$+"/01"OUT Y,M,,W
W=W-1+!W*7?"Mo Tu We Th Fr Sa Su
FOR I=1TO 30+(1AND M-(M>7))-(M==2)*2+(Y MOD 4<1&&(Y MOD 100||Y MOD 400<1))LOCATE W*3,?STR$(I,2);
W=W+1
IF W>6 THEN W=0?
NEXT

Wow, that leap year detector is VERY long...

PHP, 153 147 bytes
Mo Di We Th Fr Sa Su
<?=str_pad("",3*$w=date(w,$t=strtotime(chunk_split($argv[1],4,"-")."7")));while($d++<date(t,$t))printf("%2d "."
"[++$w%7],$d);

breakdown
echo"Mo Di We Th Fr Sa Su\n";   // header
echo str_pad("",3*                      // 4. print leading spaces
    $w=date(w,                          // 3. get weekday
    $t=strtotime(                       // 2. convert to unix timestamp
        chunk_split($argv[1],4,"-")."7" // 1. import, split to year-month-, append day 7
)));
while($d++<date(t,$t))                  // 5. loop $d through days of month:
    printf("%2d "."\n"[++$w%7],$d);         // print date, plus a linebreak for sundays

JavaScript (239)
h=prompt();y=h.slice(i=0,4);m=h[4]+h[5]-1;d=new Date(y,m);a='MoTuWeThFrSaSu'.match(/../g);for(p=0;p<(d.getDay()||7)-1;p++)a.push('  ');while(d.setDate(++i)&&d.getMonth()==m)a.push(9<i?i:' '+i);while(c=a.splice(0,7).join(' '))console.log(c)

Output:
(for 198210)                (for 201312)

Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
             1  2  3                           1
 4  5  6  7  8  9 10         2  3  4  5  6  7  8
11 12 13 14 15 16 17         9 10 11 12 13 14 15
18 19 20 21 22 23 24        16 17 18 19 20 21 22
25 26 27 28 29 30 31        23 24 25 26 27 28 29
                            30 31

C (gcc), 242 bytes
Not the most elegant solution, I suspect.
Input in the form of an integer with the four high digits forming the year, and the low two digits the month.
X=100,W;f(d){int m=d%X,y=d/X,i=0,M=" >8><><>><><>"[m]/2+(m==2&(!(y%4)&&(y%X|!(y%400))));for(m+=m<3?y--,10:-2,W=(((1+(26*m-2)/10-2*y/X+5*(y%X)/4+y/X/4)%7)+6)%7,printf("Mo Tu We Th Fr Sa Su\n%*s",3*W,"");i<M;)printf("%2d%c",++i,W++%7^6?32:10);}

Try it online!

Suggest (13*m+4)/5+y%X*5/4-7*y/X/4 instead of 1+(26*m-2)/10-2*y/X+5*(y%X)/4+y/X/4

APL(NARS), 183 chars
L←{(0=400∣⍵)∨(0≠25∣⍵)∧0=4∣⍵}⋄C←{Y←(30+2741⊤⍨12/2)+(¯2+L⍵[2])×2=⍳12⋄d←7∣+/Y[⍳⍵[1]-1],{1+L⍵}1900..⍵[2]-1⋄7 7⍴(,/7 2⍴'MoTuWeThFrSaSu'),(d⍴⊂''),{2 0⍕⍵}¨(⍳Y[⍵[1]]),12⍴⊂''}∘{(100∣⍵),⌊⍵÷100}

Input ok only from 1900. Test & how to use it:
    C 201312
 Mo Tu We Th Fr Sa Su
                    1
  2  3  4  5  6  7  8
  9 10 11 12 13 14 15
 16 17 18 19 20 21 22
 23 24 25 26 27 28 29
 30 31
    C 202312
 Mo Tu We Th Fr Sa Su
              1  2  3
  4  5  6  7  8  9 10
 11 12 13 14 15 16 17
 18 19 20 21 22 23 24
 25 26 27 28 29 30 31


text:
Code Golf - Word Clock
Write a program which takes the current time of the system clock, rounds to the nearest minute (you may choose how to round halves) and displays it formatted as the following:
A quarter past one in the morning.
A quarter to two in the afternoon.
Two o'clock in the afternoon.
Twenty-five minutes to three in the morning.
Twenty-seven minutes to seven in the evening.
One minute past twelve in the afternoon.
Twelve o'clock noon.
Twelve o'clock midnight.

Rules:

12:01am to 11:59am is deemed as morning.
12:01pm to 5:59pm is deemed as afternoon.
6:00pm to 11:59pm is deemed as evening.
15 minutes past the hour must be expressed as A quarter past the hour
30 minutes past the hour must be expressed as Half past the hour
45 minutes past the hour must be expressed as A quarter to the upcoming hour
On-the-hour times must be expressed as the hour o'clock, with the addition of noon and midnight being expressed with the addition of noon or midnight respectively.
Other times in hh:01 to hh:29 must be expressed as (number of minutes) past the hour.
Other times in hh:31 to hh:59 must be expressed as (number of minutes) to the upcoming hour.
Twenty-one to twenty-nine must be hyphenated.
The first letter of the output must be capitalised. The other letters must be lower-case.

It would be useful to provide a testing version of your code so that it can be tested without manipulating the system clock.

Let's see what you got... - The specification is still a bit vague. E.g. what about Fifteen minutes past one or Fourty-five minutes past one for the first two examples?

I agree with Howard: there's a lot of dialectal variation here. To ensure that the contest is about golfing you need a complete spec. You also need to address rounding because the time is rarely an integer number of minutes past midnight.

What?  Noon is noon, and midnight is midnight.  I suggest those times read "Twelve o'clock noon" and "Twelve o'clock midnight".  Noon is not afternoon, or 0=1.

Okay, so what do I print at 3:30 PM? Do I have to say "half past three in the afternoon"?

I'm voting to close until the spec is clarified to avoid more people posting solutions which might have to be withdrawn for not meeting the clarified spec.

I join @PeterTaylor, and suggest passing it through the sandbox

@boothby As soon as a clock hits 12:00 noon, it registers as a PM time, as does a clock hitting 12:00 midnight registers as an AM time...

Any clock that exhibits that behavior sucks.  In my humble opinion or something.

so, "thirty minutes past twelve in the morning" is a valid output?

I thought I had put the 15,30,45 minute rules in...? They must have not saved...
Updated...

Python 2.7, 159 162 156 161
from datetime import*
n=datetime.now()
if n.hour()<12:
 t="morning"
elif n.hour()<18:
 t="afternoon"
else:
 t="evening"
print"%i in the %s."%(n.hour(),t)

Edit #1 - Added a period at the end of the output.
Edit #2 - Shortened the imports, lengthened code to correct syntax.

Why the verbosity in the print statement? You're calling str on... a string... anyway, much shorter: print"%i in the %s."%(n.hour,t) (and then you can remove the period from the other strings, saving even more chars

Attempting to test on ideone gives syntax error. (I was attempted to test because on inspection this doesn't seem to meet the spec, regardless of how the current ambiguities are resolved).

Would be helpful to show an example with input and output.  Looks to me like numbers are rendered as digits rather than letter strings.

@DavidCarraher They are

@Tim, Did you read the spec? It needs to output the time in a written format as I mentioned above...

@Eliseod'Annunzio Okay, I'll work on it

Mathematica 450
Date[] calls for the current date and time. [[{4,5}]] returns the hour and minutes
f[]:=f[Date[][[{4,5}]]];
f[{h_,m_}]:=Module[{p,w,s},
p@h1_:=Which[0<h<12," in the morning.",12<h<18," in the afternoon.",18<h<24, " in the evening."];
s[t_]:=WolframAlpha["spell "<>ToString@t,{{"Result",1},"Plaintext"}];
w=s[h~Mod~12]<>p@h;
Which[
m==0, Switch[h,12, "noon", 0|24,"midnight",_,s[h~Mod~12]<>p@h],
m==15,"a quarter past "<>w,
m==30,"half past "<>w,
m==45,"a quarter to "<>s[h~Mod~12+1]<>p@h,
m<30,s@m<>" minutes after "<>w,
m>29,s[60-m]<>" minutes before "<>s[h~Mod~12+1]<>p@h]]

Current Time
f[]

"ten minutes past three in the afternoon."

Specific times
f[{4, 45}]
f[{10, 30}]
f[{11, 0}]
f[{12, 0}]
f[{13, 15}]
f[{15, 0}]
f[{22, 17}]
f[{24, 0}]

"a quarter to five in the morning."
"half past ten in the morning."
"eleven in the morning."
"noon"
"a quarter past one in the afternoon."
"three in the afternoon."
"seventeen minutes past ten in the evening."
"midnight"

I noticed I still need to implement "minutes before midnight/noon" and "n minutes after midnight/noon". Will get to that later.

You can save a few characters and get in spec by using "to" rather than "before" and "past" rather than "after".


text:
Write a function that results the sum of two integers using bitwise operations, w\o conditional operation

You cannot use if,while,for, ?:, ||, && etc., or recursion!
Assume it is Int.32
Shortest answer wins

They use control flow with the ?: operators.

(i) ?: is not "control flow", it's just an operator and it may well be branchless; (ii) if you don't want to allow the ternary conditional operator then you should state this in the question.

@PaulR - Unless I am misunderstanding, ?: equates to an if-then statement. If it is not considered a part of control-flow, then what is it considered? I was going based off of this Control flow wikipedia entry.

No - it doesn't equate to if-else (in C and related languages at least) - it's just an operator, which in some limited cases you can use to replace if-else, but it's still just an operator nonetheless, and its use does not necessarily imply branching. Anyway, I see you've changed the rules now to exclude ?: so I guess that makes its use moot.

@PaulR hmm yes, it does imply branching. Code inside the ?: operator is not executed unless the condition is met. And that is what a branching is.

@Dokkat: if you look at the code generated by any reasonably modern compiler you will see that in many simple cases that branchless instruction sequences are generated, so no, ?: does not necessarily imply branching. Try it with e.g. y = a > b ? a : b;.

@PaulR if that is the point, so does if-then-else. Try int x; if (a>b) x=a; else x=b;.

The subtle difference though is that ?: is an operator, which evaluates either of two expressions. OTOH if/else is a control flow construct. Anyway, the argument is now moot, as the rules have been changed.

Yea but I just want to make it clear for the reader that it is more of a definitions difference than an actual difference. The only actual difference between those, in general, is that you can fit the ?: operator where C expects expressions, and you can have statements inside the if-then-else. The separation between statements and expressions itself is an error and can be considered historical baggage.

C - 91
Based on Kogge-Stone, there is probably ways to cut parts of this off, but it seems good enough to start the race.
g,p;t(h){g|=p&g<<h;p&=p<<h;}d(a,b){g=a&b,p=a^b;t(1);t(2);t(4);t(8);t(16);return a^b^g<<1;}

An ungolfed version and possibly some explanation can be found from http://chessprogramming.wikispaces.com/Parallel+Prefix+Algorithms

Python 3 (66 chars)
def a(i,j):v=locals();exec("i,j=i^j,(i&j)<<1;"*32,v);return v['i']

Nice workaround for the loop limitation. I wonder if I could do something similar with macros.

J - 814
A better version
+&.(1&(32 b.))

Which does: sum under rotate bits which means (for people who don't speak J):
do rotate on both arguments, sum them, inverse the rotation.
This way the bit operation is really used in the result.

First of all: I have no idea what your code does. My comment is written as if you just summed two numbers in a completely normal manner.    I think "write -- sum -- using bitwise operations" does include both of the requirements. Usually I like cheaters in code-golf, but if we continue on this path the questions will have to be written in formal mathematical definitions. I don't want to go there.

@shiona to be fair, the title is not really a requirement. The OP should have put more in the body of the question.

you are right, the result of the bitop is not really used . Here's a better one...

Golfscript, 3 (or 7, if it needs to be assigned to a function)
Since you never said + was forbidden
0|+

0| basically does nothing (if the top of the stack is a number), because n [bitwise or] 0 is n.
+ adds them.
If it needs to be a function:
{0|+}:s

Assigned to function s.