text:
Smallest Lua table copy
So I really like to mess with tables and shallow and deep copies and I can do it in 239 chars! I wonder if there's a shorter way to do it...
Rules:

It must be done in less than 239 chars.
You must set table.copy.shallow and table.copy.deep.
A deep copy must maintain recursion. (so if I had tx.t == tx, a deep copy must have ty.t == ty (where ty is a deep copy of tx))
You must make a local copy of every function you use. (for speed)
You must be able to pass in a custom recursion table with a metatable to override default copy behavior. (at least on the deep copy function, see examples here)
If needed, use metatables. If possible, abuse them.
It must work in Lua 5.1 and 5.2.
You may use load/loadstring.
You may use the C API.
Some input/output examples (actually unit test): https://gist.github.com/SoniEx2/7942bdd0658b719ab275

This looks like a rare example of a good language-specific challenge to me, but especially with Lua I'm afraid your audience on here may be very small, so don't be disappointed if you get very few answers and some downvotes by people who don't like language-specific challenges (which are generally discouraged around here).

I wonder if I should allow C...

I'm now allowing the use of the C API because that may make it a bit more possible...

While I'm not against specific language challenges, and thought of having a go at this, the "I can do it in X chars, see if you can beat me" part is a bit discouraging, as I have no reason to assume your solution isn't already the best one.

@Tal Yep, but I kinda want it smaller...

@SoniEx2 so you're disqualifying all answers that don't help you specifically? That's not what this site is for.

@m.buettner I'm not disqualifying all answers that don't help me, just the ones which aren't smaller than my code... (even if that means I'm asking for something impossible)

@SoniEx2 I don't see the difference. The limit seems arbitrary and spoils the fun for your participants. If you leave it out you're less likely to put people off, which could give you more submissions - which will try to beat each other, and are more likely than not beat your target line anyway. Especially if you tell him how short you got it without requiring them to best your score. Because someone might have an answer with 250 characters, but wouldn't post it, because it's disqualified anyway. But if he posted it, he might revisit it later, discover a new trick, and save 20 characters.

So now that an answer has been accepted can we see the 239 char version?

@JerryJeremiah Click the link that says "I can do it in 239 chars!"

235
Substantially based on the guts of SoniEx2's 239 answer.
local o,k,F=type,next,{}for n=0,2 do
F[n]=function(a,r,t,G)if n<1 or o{}~=o(a)then return a end
t={}r=r or{}r[a]=n<2 and t G=F[n%2]for x,y in k,a do
t[r[x]or G(x,r)]=r[y]or G(y,r)end
return t end end
table.copy={shallow=F[2],deep=F[1]}

The advantage comes from using the same function prototype for both functions. Instantiating the same function prototype with different upvalues allows it to fill both roles.
Ungolfed:
-- ungolfed
-- note that type and next must have local copies to meet the spec
local o, k, F = type, next, {}
for n = 0, 2 do
  -- F[0] will be the identity function
  -- F[1] will be table.copy.deep
  -- F[2] will be table.copy.shallow
  F[n] = function(a, r, t, G)
    -- a is the table input
    -- r is the optional "custom recursion table" that is required
    -- t and G are just locals
    -- the spec implies (but does not state) that the global environment shouldn't be polluted
    -- r will only be used by recursive calls

    -- if n < 1, this is F[0], so act is the identity
    -- o is type, o{} is "table"
    -- if a is not a table, just return it
    if n < 1 or o{} ~= o(a) then
      return a
    end

    -- t will be the copy
    t = {}

    -- r will be the map that remembers which tables in the original map to which tables in the copy
    -- or, if it is passed in, it is a table that controls the behavior of the copy
    r = r or {}

    -- F[0] doesn't each here
    -- F[1] must add t to the map
    -- F[2] must not add t to the map
    -- (adding false will not hurt F[2] -- only true values will be picked up below)
    -- (behavior may not be exactly as desired for shallow copy, but spec doesn't require this feature)
    r[a] = n < 2 and t

    -- this is the function we will call to copy members
    -- for F[1] table.copy.deep, this is F[1] itself
    -- for F[2] table.copy.shallow, this is F[0] the identity
    -- (for F[0], we never get this far)
    -- the byte count seems equivalent making this a local vs putting it
    -- in both places it is used, but this is probably more efficient
    G=F[n%2]

    -- loop over and copy members
    -- first try r (which will only have non-1 entries for tables in F[1])
    -- then try G
    -- note that instead of calling "pairs" as usual, we can observe that pairs(a)
    -- is defined to return next, a, nil -- we use these (with implicit nil) directly
    for x, y in k, a do
      t[r[x] or G(x,r)] = r[y] or G(y,r)
    end

    return t
  end
end

-- export the functions as required
table.copy = {
  shallow = F[2],
  deep = F[1]
}

Hopefully I understood the spec correctly. This passes the provided test cases and there is enough similarity in the construction that I'm reasonably sure it does the same thing.
Note -- Initially I didn't understand the part about the "custom recursion table", but I have edited my answer to support it.
Note 2 -- Improved answer. I've also decided that the provided reference solution in 239 bytes does not exactly match my understanding of how the custom recursion table ought to work, since it cannot be used to add false into the copy. However, I believe my solution works as well as the provided one.

This is amazing! Hmm I wonder what happens if you shallow copy _G...

So I added a _G testcase. See if you can get that to work.

The reason your test case fails (for me) is that you're defining a global "G" after doing the copy, so the tables don't match anymore. It will pass if you declare "G" as a local.

You can golf a few bytes out, Any number followed by a letter where the letter doesn't match [a-eA-ExX] does not need whitespace. So n<1 or can become n<1or

@ATaco: Thanks for pointing that out. I remember reading about this on lua-l. Unfortunately, I don't think it's appropriate for this answer because it doesn't work in PUC-Rio Lua 5.1.

238 chars!
Turns out, it wasn't impossible!
loadstring(("local k,o,d=next,type dDif o{}~=o(a)thenBaAt={}r=r or{}r[a]=tCt[r[x]or d(x,r)]=r[y]or d(y,r)ABtAtable.copy={shallowDt={}Ct[x]=yABtA,deep=d}"):gsub("%u",{A=" end ",B=" return ",C=" for x,y in k,a do ",D="=function(a,r,t)"}))()


text:
Saying a number in the shortest way
A string of digits (positive integer) can be converted to plain English in various ways. For instance, 115 can be read as "hundredfifteen", "oneonefive", "elevenfive", "twoonesfive". So question's challenge is to output the shortest string representation for a given digits string.
Rules:

The input string can start with a zero and the output should account for that.
Maximum length of input is 18. So you deal with numbers less than a Quintillion.
You should use only the following mathematical words for numbers in your output: zero, one, ..., nine, ten, eleven, ..., twenty, ..., ninety, hundred, million, billion, trillion. You can use their plural forms for sequences (i.e. "fivetens" for 1010101010). No synonyms (i.e. "oh" for 0) or slang (i.e. legs for 11) are allowed. You don't need to include a "one" prefix for cases like 100, just "hundred" is fine.
You don't need to put spaces between different words in your output.
The output shouldn't be ambigous. This means, from the output string one should be able to determine the input unambigously. So for 705 you can't output "seventyfive" since it may be the output of 75 also. You may use "and" if that'll remove ambiguity, otherwise you don't need to include "and" in your output.
Winner is the entry that will have the shortest code length excluding import statements and if not some user finds out a deficit in the code (i.e. a shorter representation than the program spits out for a particular input ).
Please post your output for the following test cases to make evaluation easier: 1234, 00505, 122333, 565577555555666888, 1000010, 10001000, 10101010.
No reading from an input file, so usage of a dictionary or hash map should count towards your code length.

edit1: Changed the competition type to code-golf per comments and added test cases.
edit2: Restricted the words that can be used in the output. Thanks to @PeterTaylor for the examples.

Could you put a hard limit on the input numbers? Or do I have to support "Septendecillion"? Furthermore, I think with a slightly more rigid spec this would be a great code-golf question. I don't really see why it has to popularity-contest. The current spec is already too tight to leave a lot of room for the kind of creativity that is rewarded by popularity contests.

@m.buettner, do you think changing the criteria to "output longest string" will enable more creativity and make it more suitable to popularity-contest? Secondly, can you elaborate on how we can make the spec more rigid to make it a good code-golf question? Having a limit makes sense for inputs like 1000000 so I'll add it. Thanks for pointing.

I agree with @m.buettner; this would be a better code-golf question.

I think this would work best as a code challenge. You have a secret list of 5000 numbers, after a week you reveal the numbers and whichever program represents them with the least total characters wins.

@Hovercouch: only if finding the shortest solution for each number is very hard to do optimally, and I'm not convinced that's the case, because the amount of possible strings per number seems rather limited.

Why isn't "18403" the shortest way to say the number 18403?

The spec is too imprecise as it stands, so it just sets up lots of arguments as to whether a string represents the given number or not.

Let's say that you need to communicate a number in a phone conversation. You will say some words and the other party will be able to write the number down in an unambiguous way. Additionally, you want to use the least amount of letters when you "say" this number. That's the specs of this question. @PeterTaylor, is it more clear now? Shall I add this to the question?

No, that doesn't make it any more clear. Some phrases are unarguably correct: e.g. for 00 it is definitely ok to say zero zero. But some people might say oh oh - or should that be written o o? And for 11, English bingo players might say legs, which is probably unbeatable but certainly controversial. In order to avoid clashes over acceptability, I think you need to give an exhaustive list of permissible words.

@PeterTaylor, I see what you meant more clearly now. I listed the permissible words in the rules.

4
This is cheeky and a cheat. I wrote this script about a year ago based off of this comic (tad of profanity).
The idea goes like this. Given any number as a string, adding the number of characters will eventually condense to 4. Four itself is 4 letters long and thus the end of the line.
For example:

10 -> 'ten'
'ten' -> 3 (letters long)
3 -> 'three'
'three' -> 5 (letters long)
5 -> 'five'
'five' -> 4 (letters long)

I verified up to 100,000. Very hacky but got the job done:
to20 = [
        'zero'
        ,'one'
        ,'two'
        ,'three'
        ,'four'
        ,'five'
        ,'six'
        ,'seven'
        ,'eight'
        ,'nine'
        ,'ten'
        ,'eleven'
        ,'twelve'
        ,'thirteen'
        ,'fourteen'
        ,'fifteen'
        ,'sixteen'
        ,'seventeen'
        ,'eighteen'
        ,'nineteen'
        ]

by10s = ['twenty'
         ,'thirty'
         ,'forty'
         ,'fifty'
         ,'sixty'
         ,'seventy'
         ,'eighty'
         ,'ninety'
         ]

by10powers = [
             'hundred'
             ,'thousand'
             ]

def cosmetize(number):

    # the number is too damn high!
    if number >= 100000:
        return "Too high"

    numstr = str(number)

    # Do ones
    if number < 10:
        return to20[number]

    # Pshh.. who needs zero anymore?
    to20[0] = ''

    # Do tens
    numstr10 = numstr[-2:]
    if int(numstr10) < 20:
        numstr10 = to20[int(numstr10)]
    else:
        numstr10 = by10s[int(numstr10[0])-2] + to20[int(numstr10[1])]
    if number < 100:
        return numstr10

    # Do hundreds
    numstr100 = numstr[-3]
    if numstr10 == '':
        numstr10 = ""
        numstr100 = to20[int(numstr100)] + by10powers[0]
    elif int(numstr[-2:]) > 19:
        numstr100 = to20[int(numstr100)] + by10powers[0]
        numstr100 += 'and'
    else:
        numstr100 = 'and'
    if number < 1000:
        return numstr100 + numstr10

    # Do thousands
    numstr1000 = numstr[:-3]
    if numstr100 == 'hundred':
        numstr100 = ""
    if int(numstr1000) < 20:
        numstr1000 = to20[int(numstr1000)] + by10powers[1]
    else:
        numstr1000 = by10s[int(numstr1000[0])-2] + by10powers[1]

    return numstr1000 + numstr100 + numstr10

i = 0
mx = []
z = 0
while i < 100000:
    length = cosmetize(i)
    x = [length]
    while not len(length) == 4:
        length = cosmetize(len(length))
    i += 1

# No inifinite loop? what magic is this?
print "OMG"

Python - (191 - 38) = 153 bytes
This code has the worst case length of 18 for input of 000000000000000000. I'm not sure if this is system dependant. If it's not, I could remove a couple characters.
from string import*
from math import*
s=digits+lowercase+uppercase
c=raw_input()
b=len(s)
a=int(c)
print'-'*(len(c)-len(c.lstrip('0')))+''.join(s[a/b**i%b]for i in range(int(log(a,b)),-1,-1))

For the last line I have to give credit to this fellow. Example outputs:
> 1234
9j
> 00505
--3Z
> 122333
6Vn
> 565577555555666888
5haShÄøŠé
> 1000010
êÌõ
> 10001000
48Šõ
> 10101010
4ewª

Disclaimer: This answer is not a serious answer and it's not trying to compete. This is taking advantage of ambiguity of the rules.

Clever one but "êÌõ" is not plain English as mentioned in the first sentence. I thought it was clear from the examples but it seems like I need to state this explicitly.

@pembeci As I said, the point of this was to show how ambiguous the rules are.

source: Stack Exchange

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

sort: votes


text:
Produce an unexpected word
The goal is to write program that will produce a word unexpectedly (program doesn't look like it is going to produce a word).
Example (JavaScript):
alert(([0][1]+"").slice(4,8))

alerts "fine" - jsfiddle.

Explanations:

 1. [0][1] returns undefined, because there only one element in array [0]
 2.  Adding empty string converts undefined to string "undefined"
 3. slice(4,8) outputs fifth to eight characters of undefined

This is underhanded popularity contest.

I don't think this challenge is objectively measurable. How "unexpected" is "unexpected enough"?

I think this is more or less a dupe of the "Print an unexpected obscenity" question which has now been deleted so I can't find the link. That one was also an [tag:underhanded] about unexpectedly printing a word, with the constraint that it had to be an insult

I'm closing this question because, by community consensus, underhanded challenges are no longer welcome on the site.

Python2.x
import re
try: re.compile("[")
except re.error, e: print e.message.split()[0]

try it

That was certainly unexpected.

CJam
"":iXf&YbBB*b:c

Prints Pneumonoultramicroscopicsilicovolcanoconiosis.
Try it online. (Permalink works in Chrome. You have to copy and paste the code in some browsers.)
To understand how it works, click here to run this:
"":i5f%5b5I*b' f+~

I still don't get it!

 The first code block is actually 970 bytes long, since there are 318 zero-width characters (U+200B and 0+200C) between the two double quotes. Even with a monospaced font, these characters are completely invisible.

 X, Y and B are variables initialized to 1, 2 and 11.

 :iXf& casts each character to an integer (8203 or 8204) and computes the parity. This way, U+200B becomes 1 and U+200C becomes 0.

 Yb converts the array of integers from above to an integer by considering it a base 2  number.

 BB*b converts that integer into an array of its digits as a base 121 number.

 The sad smiley :c casts each digit to its corresponding ASCII character.

 The second code block is actually 6543 bytes long. It follows the same idea, but it uses the characters U+200B to U+200F, base 5 numbers and string evaluation.

Oh, you sneaky rascal :)

Very very tricky. +1

Python
I don't expect any upvote (but pwease don't downvote this either - unless the net votes are above 0!), because of course I claim NO MERIT WHATSOEVER on this answer, but in my opinion, the award would go hands down to Tim Peters for this Python code...
import this

(If you've never heard about it, try it here :) )

Em... Explain, please. ))

@nicael this is "The Zen of Python", or PEP20 - it's a series of affirmations about how Python scripts should be implemented, and it has been hard-coded into Python as module this... as an easter egg, if you wish :)

Ok - here'we go:
Javascript:
new Function("".split("").map(function(v){return String.fromCharCode(v.length)}).join(''))();

Evaluate it in your console...

 It can't be that easy. Try to find it yourself.

Certainly +1. Explain please! ))

I found it! https://whiskers75.co.uk/assets/OHMYGODWHATTHE.png

+1 For those wondering how this works, paste the code into this tool: http://mothereff.in/js-escapes

You can shorten this by replacing new Function(...)(); with eval(...);

Yes, but this is not a code golf and I think new Function(...)(); looks way more confusing as it is hiding the eval :)

This kills my shell. http://i.imgur.com/i7ElDry.png

C - ioccc feeling
#define\
    __(a,b) b##a
    __(in(O){,ma)
    __(at*f=&O;,flo)
    #define\
    _ __(ntf("%f",*f);,pri)
    __(ng,lo)__(ng $;O=, lo)
        __(NE__;$=,__LI)
        O*4*2699*14449
        *__(1ll,1765069);O=~--O;_-_-
        _-_-_-_-_-_-__(ts(&$);},pu)

output (using gcc 4.7.2):

 -nan-nan-nan-nan-nan-nan-nan-nan BATMAN

C - WinApi
leave it to the professionals
#include <Windows.h>

CONST CCHAR *ParseStringOutputHandler(HANDLE hOut)
{
    /*
    * Prototype for SEH support function.
    */
    CONSOLE_SCREEN_BUFFER_INFO SBInfo;
    COORD crdSBInfoCoord;
    COORD crdMaxWinSize;
    COORD crdSize;
    WORD wMagicNum = 0x40;
    WORD wAttr = 0x14;
    INT8 i;
    static CCHAR szParseArray[9];
    /*
    *       This file contains the definitions and prototypes for the compiler-
    *       dependent intrinsics, support functions and keywords which implement
    *       the structured exception handling extensions.
    */
    crdSBInfoCoord.X = _WIN32_WINNT_NT4 >> 8;
    crdSBInfoCoord.Y = SUBVERSION_MASK / 28;
    crdMaxWinSize.X = EXCEPTION_EXECUTE_HANDLER | 0x2;
    crdMaxWinSize.Y = (_WIN32_IE>>010) + 3;
    crdSize.X = _WIN32_IE_IE20 >> 0x8;
    crdSize.Y = 0x15;
    SBInfo.dwCursorPosition = crdSBInfoCoord;
    SBInfo.dwMaximumWindowSize = crdMaxWinSize;
    SBInfo.dwSize = crdSize;
    SBInfo.wAttributes = wAttr;
    /*
    * Currently, all MS C compilers for Win32 platforms default to 8 byte
    * alignment.
    */
    for (i = 1; i <= 8; ++i){
        switch (i){
        case STRICT:         szParseArray[i-1] = SBInfo.dwCursorPosition.X;     break;
        case DM_COPY:        szParseArray[i-1] = SBInfo.dwCursorPosition.Y;     break;
        case DC_PAPERSIZE:   szParseArray[i-1] = SBInfo.dwMaximumWindowSize.X;  break;
        case _CRT_PACKING/2: szParseArray[i-1] = SBInfo.dwMaximumWindowSize.Y;  break;
        case 0x5:            szParseArray[i-1] = SBInfo.dwSize.X;               break;
        case DC_BINS:        szParseArray[i-1] = SBInfo.dwSize.Y;               break;
        case (_WIN32_WINNT>>8)|(_WIN32_WINNT&1):
        case 010:            szParseArray[i-1] = SBInfo.wAttributes;
        }
        szParseArray[i-1] |= wMagicNum;
        if (i > 7){
            szParseArray[sizeof(szParseArray)-1] |= wMagicNum;
        }
    }
    szParseArray[8] = NULL; // set WINVER based on _WIN32_WINNT
    return szParseArray;
}

output:

 DICKBUTT

i feel offended :'(

CJam
This is my first practice with CJam:
77c79c_78c7(8+6*3+c"K"["MICHAEL" "JACKSON"]:Ls4=Ls6=@'R'E\

I'm sure I could do it better with more practice but it was fun.
It prints out

 MOONWALKER

You can check it out here.

Yep. Good answer.

C
Works only on a little-endian machine
How to make a simple multiplication ?
int main(void) {
    //this is an easy multiplication example
    int a = 37897 * 210;

    //print the result
    printf("%s",&a);
    return 0;
}

outputs boy

 37897*210 = 7958370 (0x796f62)
boy ASCII representation is 62-6f-79 (0x796f62 on little-endian)
 printf with %s print the string, not the integer.

>> Try it here

try it with uint64_t a = 30980630101 << 4

@mebob The pen is mightier.

Javascript
Round 2:
Improved Solution:
try{Joe}catch(е){alert(е.message.replace(/de?/g,''))}

53 characters
Old Solution: Prints the same but in more short char length:
try{Joe}catch(е){console.log(е.message.replace(/de|d/g,''))}

60 characters
Round 1:
I am going to Joe's place, he is sick, even computer says that:
try {
    x = Joe;
} catch (err) {
    msg = err.message.split(" ");
    console.log(msg[0] + " " + msg[1] + " " + msg[2] + " " + msg[3].substring(2, 6));
}

162 characters.
try{x=Joe}catch(e){m=e.message.split(" ");console.log(m[0]+" "+m[1]+" "+m[2]+" "+m[3].substring(2,6))};

103 characters.
"Joe is not fine"

Ahahahahaha: ReferenceError: Joe is not de_fine_d -> Joe is not fine

Here's a shorter version (60 chars):
try{Joe}catch(е){console.log(е.message.replace(/de|d/g,''))}

@ДамянСтанчев can I use that as my answer please? :P

Sure, not a problem :)

If you're going for brevity: try{Joe}catch(е){alert(е.message.replace(/de?/g,''))}

I am fine, thank you very much!

@Joe , I'm glad you are fine. :)

dc
dc can be used with pretty obscure expressions. Here is an example, nearly asking you a question! (second line):
dc -e '[<!][P[ ]P]sr[|]30 4+[p]5[ ]500d+300dZ73 16d6-r[PnPnPnPP]sa[sz-=r2;h*7+++[know ]lax]sb
    vv:ha7 d0 [you] sp[eak?]                                                             lbx'

 Output: I know 1337 5p34|<!

Edit: splitting original answer into three different ones (bash and haskell proposals in separate posts)

You can split this into multiple answers if you'd like.

You should split these into multiple answers, that way people can vote on each individually.

Ok, I have split my original post. Thanks for advice!

C, C++
Here's an oldie that could easily be adapted to other programming languages:
#include <stdio.h>

int main() {
    int i = 0x6F56DF77;
    printf("%8X", (i << 1) + 1);
}

 The trick is using the numbers >9 in hexadecimal (or higher) number systems. This one print's DEADBEEF, but there can be many variations. AFAIK Mac OS used to mark released memory in certain debug builds as dead beef.

Try it!

You should avoid void main, some compilers such as clang error on it. int main without actually returning won't cause an error, though.

void main to hell.

void main is a old standard for DOS, I think (got a book about Turbo C++...).

Common Lisp
No attempts to hide how this one works.
(let ((*print-base* 36))
  (print #x1A92721254086478787CE5D7))

 SPANISHINQUISITION

+1. Did not expect.

@mniip Nobody does...

sed
Of course with sed one is waiting for a string output. But if you do not already know this one, I think it can be considered as… unexpected:
sed 's/ //g;s/h.*yo//;s/od.*//;y/euHodityn,/ -aegmoptt/;s/ //;e'
    <<< 'Hey, have you done it today?'

I can't write the answer correctly in a “spoiler” block, so you'll have to try it yourself :)
(Hint: works best on Debian/Ubuntu. Don't loose your time on Mac.)
Edit: I discovered that I could use code in spoiler blocks, so output is now hidden below.

         (__)
         (oo)
   /------/
  / |    ||
 *  /---/\
    ~~   ~~
...."Have you mooed today?"...

sh: apt-get: command not found Were you trying to install something on my computer?

@undergroundmonorail: http://unix.stackexchange.com/questions/92185/whats-the-story-behind-super-cow-powers

Don't loose your time on Mac. Or on the dozens of (debatably superior) non-Debian based OSes...

CJam
PT/

Try it at http://cjam.aditsu.net/
Also, for fun:
"HAL":)

Ruby
def handle(switch)
  case switch
  when 'a',
    print(switch << 'a')
  when 'n',
    print(switch.sub!('b','n'))
  when 'q',
    print(switch.gsub('b','q'))
  when 'b',
    nil
  else
    print('s!')
  end
end

handle('b')

Demo

bananas! Yep, but what if I don't like bananas? Anyway, +1, good example (actually I like bananas).

If you don't like bananas, simply pass 'a' instead of 'b' and then yes, we have no bananas.

PowerShell
Can it be multiple words? If so, allow this to blow your freakin' mind.
function recurse() {
    $r = 72,29,7,0,3,-79,87,-8,3,-6,-8
    $s = ""
    $t = {
        $a,$b = $r
        $d+=$args[0]+$a
        $s+=[char]$d
        if ($b -ne $null) {
            return recurse $d $b $s
        }
        return $s
    }
    function recurse() {
        $r = $args[1]
        $s = $args[2]
        . $t
    }
    . $t
}
recurse 0

 Returns "Hello world" in a very complicated way

Of course, it can.

The goal is to write program that will produce a word unexpected
I didn't read past that. I have a serious issue with reading long passages (and error messages).
I decided to create a simple program that alerts "5". Unfortunately, I can't seem to get it to work.
(function () {
    "use strict";

    function logError(e) {
        // I have a serious issue with reading long error messages
        // I'll just print the first word of the error and figure out what it means
         console.log(e.message.split(" ")[0]);
    }
    // Useful assert method for debugging
    function assert(value, message) {
        if (value === false) {
            throw new Error(message);
        }
    }

    // Sets a varaible "a" to 5 and alerts it
    try {
        // Try it the old fashioned way
        a = 5;
        alert(a);
    } catch (e) {
        logError(e);

        // In some legacy browsers, that might now work
        // because alert requires a string
        try {
            // create objA which has a method "word", which always returns a word, or a string
            var objA = {
                word: function () {
                    return new String(5);
                }
            };
            // Make sure it is a string
            assert(typeof objA.word() === "string", "word didn't return a string");
            alert(objA.word());
        } catch (e) {
            logError(e);
            // Some browsers, such as chrome, just won't work
            // It's time to be evil and force them to work!
            try {
                eval("a = 5" +
                    "alert(a)");
            } catch (e) {
                logError(e);
            }
        }
    }
})();

Tested in the google chrome console.
It produces (literally) a word unexpected.
http://jsfiddle.net/prankol57/Af4sH/
(For the jsfiddle, you must open your console, there won't be any html output)

Perl
print pack qq;
\1108;
,hex for qw;
2e5d66e 4b88fad 4560770 3aedf79;

Prints a friendly message for a special day!

 Outputs Happy Birthday!! (Was given to a programmer friend who hates Perl.)

 The white space and semicolon as the delimiting characters are meant to deceive.

qq;\1108; (equivalent to "H8")

 The semicolons are the delimiters for the double quote method. \110 is the octal code for H, followed by a plain 8, giving us the packing code "H8", meaning 8 hex digits

hex

 Converts a hex string to an integer. No parameter means it runs on $_ (default variable)

for qw;2e5d66e 4b88fad 4560770 3aedf79;

 The semicolons are the delimiters for the quoted list method. for indicates to run the entire block on the left once per each hex string.

 "Unobfuscated", the script is:
 print pack("H8", hex($_)) for (2e5d66e 4b88fad 4560770 3aedf79);

 Each of those hex values, when de-hexed into an 8 digit number, and then packed into a 4 characters, will print 4 of the letters of Happy Birthday!!

Run it here

Javascript

 alerts "hello"

var $$ = String.fromCharCode;this[(+{}+[])[-~[]]+(![]+[])[-~-~[]]+([][+[]]+[])[-~-~-~[]]+(!![]+[])[-~[]]+(!![]+[])[+[]]]($$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((+!+[])+(-~+[]))*((+!+[])+(-~+[]))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(-~+[]))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$(((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+(((!+![])^((+!+[])+(-~+[]))))));

caveat: one variable declaration.(no time for changing String.fromCharCode to symbols)
more readable code (solution is derived from this code (it's mine BTW))
Ref:

http://sla.ckers.org/forum/read.php?24,33349,33405
http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html (inspired for accessing alert from symbols)

This might run in Lisp, and Brainfuck as well.

@AnubianNoob I tried it in brainfuck, it goes to an infinite loop. Also i did in Lisp, throws syntax error.

It would have been pretty funny if it did work ;)

This one isn't code-golf, no need to make it compact (and unreadable) or to count characters.

@Alejandro the code being unreadable makes it unexpected to give any output. BTW, I have removed the reference to number of characters

Ruby
display(STDOUT) unless case class Do
self
end when method(:print).to_proc
end

I've used this trick in an earlier underhanded contest, but I thought I'd dress up the output a bit differently.
Demo
First person to explain where the word

 Domain

comes from wins a no-prize.

The last part of the word is easy. The display method of the ruby main class is writing itself to STDOUT. It's printed second, because everything after unless needs to be evaluated first to decide whether to execute the code before it. After the case statement returns nil, it is printed. The first part of the word is the tricky part. The case statement is comparing the Do class to main's print method as a proc. The when clause compares using ===, and the Proc === method is defined to invoke its code block with the other object as the parameter so it calls print with Do as the parameter.

TI-BASIC
:

(Either type the colon on an empty screen, or make an empty program or one containing just colons.)
Prints "Done"

JavaScript, 10 characters
alert(1/0)
Test it on http://jsfiddle.net/cC52Z/!
Output

 Infinity

Explanation

 Instead of disallowing division by zero, JavaScript makes it always return Infinity (division of a negative by zero produces -Infinity).

I love it )) Good answer.

I expected that.

Not unexpected...

Emacs Lisp for version 22.1.1 (that comes on osx)
Run this right on the command line
emacs -q --batch --eval "(progn (execute-kbd-macro \"\C-[xinfo\C-m\C-[xfun\C-i\C-m\C-u49\C-n\") (search-forward (string(+ ? ? (*)? )(+(/ ? (+(*)(*)(*))) ? ? ? (*(+(*)(*))(+(*)(*))))))(print (buffer-substring-no-properties (+(*)(*)(*)(point)) (progn (forward-word(*)) (point)))))"
Output: "woman"

Python
Inspired by @Roberto's answer.
try: exec('from __future__ import braces')
except Exception as e: print(e.msg)

 Another Python easter egg; it prints: not a chance

Homespring

(Empty program)
Output

In Homespring, the null program is not a quine.

Why?

Homespring prints this message when interpreting a empty program to prevent cheating at quine code golf challenges

Perl
#!perl
eval('(*16,z<=:3??0<x06161xBBQ$8t'^((
'0'x27)^((((((('h'x6).'A'.'b'x5).'a'.
'h'x2).'A'.'h'x5).'A'.'H'x3).'f'x2))))

 Output: Mohammad Anini 3:)

If you use the >! command, you can hide what this code does until a mouse scrolls over the text.

GolfScript
0:b;"#{STDIN.inspect}"${b{..}{.}if 78={6-.1:b;}{}if;}%

Outputs:
HOST

Try it out here.
How it works:

 "#{STDIN.inspect}" returns "#<IO:<STDIN>>". $ sorts it into "#:<<>>DIINOST". The rest of the program loops through the string, dropping chars until it finds an N. Then, it changes the N to a H and keeps the rest of the chars.

Julia
(repr(typeof(""))*repr(typeof(' '))*repr(typeof(1//1)))[6:7:27]

Another option:
print(print())

Bash
<<< echo echo echo

or
`echo echo echo`

 Both commands output echo, of course.

Also available in recursive version with the $() syntax: $(echo $(echo echo $($(echo echo) echo))), same output…

You got me at first.

T-SQL
declare @S char(3)  -- Declare a string variable that holds three characters
set @S = 1000       -- Implicitly convert the value 1000 to string
select ascii(@S)    -- Get the ASCII code value of the leftmost character

Outputs

The Answer to the Ultimate Question of Life, the Universe, and Everything

SQL Fiddle

Maybe I can't create fiddle, could you create it?

@nicael Does the link not work for you?

But it outputs column_0 42.

Yes it does. Don't kill the messenger but 42 is the answer to the ultimate question.

@nicael Haven't you ever tried calculating that?

@AryanBeezadhur I see xD

JavaScript
for (var i in this) {
  if(parseInt(i[0]+i[2],16)==174) {
    this[i](i[0]+i[1]+i[2]);
    break;
  }
}

Not the cleverest. But, I sure do like what it has to say!
Tested in Chrome.

Nice, but too short.

Thanks ... But, too short? ... What's the requirement?

Simply it is popularity contest.

Java
This code is a bit long, outputs word:

 SEVERE

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Text
{
    public static void main( String args[] )
    {
        makeSureWeCantOutputText();
        unexpected();
    }

    private static void unexpected()
    {
        try
        {
            //this does nothing
            long x = 1;
            for( int i = 1; i / i == 1; i++ )
            {
                x++;
            }
        }
        catch( Exception ex )
        {
            Logger.getLogger( Text.class.getName()).log( Level.SEVERE, "");
        }
    }

    private static void makeSureWeCantOutputText()
    {
        try
        {
            //OutputStream class that outputs to nowhere
            PrintStream stream = new PrintStream( new OutputStream()
            {

                @Override
                public void write( int b ) throws IOException
                {
                }

            } );

            //replace System.out field with OutputStream that does nothing
            Field field = System.class.getDeclaredField( "out" );
            field.setAccessible( true );

            Field modifiersField = Field.class.getDeclaredField( "modifiers" );
            modifiersField.setAccessible( true );
            modifiersField.setInt( field, field.getModifiers() & ~Modifier.FINAL );

            field.set( null, stream );
        }
        catch( Exception e )
        {
            //we don't want to outpout anything if it fails
        }
    }
}

Explanation:

 When exception is thrown we use Logger. Logger with Level.SEVERE Logger uses System.err instead of System.out. i / i throws exception when i reaches 0 (it starts from 1 and increases, then integer overflows to Integer.MIN_VALUE and is increased to 0).

Ruby
#!/usr/bin/ruby
a = self.methods.map{|x|x.to_s}
b = a.count
p a[b/2-8]+a[b-6]

Outputs:
"freeze!"

Ruby
Bit late to the party, but couldn't help but notice that no-one had done something like this:
puts 65791925216734442002988169043447582627179158156970580.to_s(36)

Demo

JavaScript
Test it on your browser's console
x = Math.random() > 0.5 ? 2 : 0;
alert(document.getElementsByClassName('question-hyperlink')[0].text.substr(13 - x,13 + x))

Yep, good. Wonderful. No need to add explanation )) However if word is expected, I expect it. Anyway, +1.

JavaScript
function rgbToHex(rgb) {
  var r = rgb[0].toString(16);
  var g = rgb[1].toString(16);
  var b = rgb[2].toString(16);
  return '#' + r + g + b;
}

alert(rgbToHex([176,0,11]));

The hex converter doesn't properly zero pad and yes it alerts #b00b.

J
This is what happens if you're bored.
'Nqbs a `u{c vac'({&a.@-@(t@[-+:@t=:a.&i.@]))'Kill a good man'

Output:

 Have a nice day.

Why?

It calculates -y - x - x where x is the left string and yis the right string.

And it for sure isn't taking home the cleverness award, but I like it.

IBM Enterprise COBOL
   ID DIVISION.
   PROGRAM-ID. ERRMSG.
   ENVIRONMENT DIVISION.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  A PIC 9 VALUE ZERO.
   PROCEDURE DIVISION.
       ADD 1 TO A
       GOBACK
       .

Here's a short program. It obviously does nothing but add one to the field A.
However, toss it into the compiler, and... http://www-01.ibm.com/support/docview.wss?uid=swg21156178

You can generate a complete listing of compiler diagnostic messages with their >message numbers, severities, and text by compiling
  a program that has program-name ERRMSG.
You can code just the PROGRAM-ID paragraph, as shown below, and omit the rest >of the program.

The key is to have errmsg as the PROGRAM-ID. No other code is required. The code in my example is just to convince that it is a real program which produces no output.
This is the example IBM show in the link:
Identification Division.
Program-ID. ErrMsg.

Indeed, this is enough:
Program-ID. ErrMsg.

Or this:
Program-ID. ErrMsg.
The quick brown fox jumped over the
lazy dog, or any other text you like.

This is an example of the output: http://www-01.ibm.com/support/docview.wss?uid=swg21156178&aid=1
When the compiler gets to errmsg. (note the full-stop/period, which doesn't have to be immediately after errmsg, but must exist after it somewhere in the source) it knows what is needed, reads to the end of the source and then produces the listing, including the description of the format and information contained in the error messages, and all the messages themselves.
As a curiosity, you can try this:
Program-ID. ErrMsg

This time no full-stop/period is encountered before the end of the source is reached, and a (very) minor compiler bug is revealed, as the compiler continues reading, and abends (ends abnormally, crashes) with an S001 Reason Code 5 and
IEC020I GET ISSUED AFTER END-OF-FILE

No IBM Mainframe COBOL has ever separately documented its error messages in an actual manual.

Mathematica
ToString[#&@;;]~StringTake~{16,20}

Prints "Dummy". But I seriously do not understand why #&@;; does..what it does.

Funny note: None of the letters Dumy appear in the code.

Perl
open IN, "<".$0;
while (<IN>) {
        chomp;
        (m/(^|[^\)])w.i.e/ && (s/^.(.).(.)(.).*/$1$3$2$2/ && print $_)) || m/(^|[^\)])...se/ && (s/^..(.).*/$1/ && print $_."\n");
}
close IN;

 Opens it's own script file and prints out some of the characters.

C++
#include <iostream>
#include <limits.h>
#include <math.h>
using namespace std;
typedef unsigned long long ULL;
#define C(x) cout<<(ULL)(x)<<endl
int main ()
{
    ULL b=UINT_MAX;
    ULL d=LLONG_MAX;

    ULL f=(ULL)(d/b);
    size_t n = (log(f)/log(10))+1;
    char *w=new char[n];
    char x;
    for(size_t i=0; i<n; i++)
    {
        x = (char)((f%10)+'@');
        f=(ULL)(f/10);
        w[n-i-1]=((n-i)<4)?x:0;
    }
    cout<<w<<endl;
    return 0;
}

Produces the word "BAD".

Javascript - 19 chars
This one is inspired by Gary Bernadt's 'wat' talk: Video Link
([]+{}).substr(1,6)

Unexpected because Array [] + Object {} should not output an Object.

 "object"

Another solution suggested by bebe
(0+{}).slice(2,8)

 "object"

Mathematica
SeedRandom[377]; FromCharacterCode@RandomInteger[{98, 123}, 5]

 outputs proof

BaseForm[272580165883129, 29]

 outputs impossible

You can try the second one online in Mathics.  Type in the code and press Shift-Enter.  The first one is implementation specific, thus it won't work in Mathics, but it does work in all recent versions of Mathematica.

outputs "impossible[base 29]", the 29 is beneath impossible. Why is it impossible?

@MegaMan I don't understand your question

Extended BrainFuck
>~~ufp~<.[-.<]

 outputs "poet"

Everything what bf and its derivates do is unexcepted...

Burlesque
blsq ) 4593109656 128B!
"hello"
blsq ) vvSh29.-4.+
"size"

Explanation
128B! is just base 128.
vvSh29.-4.+ produces an error, converts the error to a string and then slices.

Mouse-2002
' '  + 20 + b + a + !'
' '  + 13 + i + z + !'
' '  + 4  + i + z + !'
' '  + 23 + i + z + !'
' '  + 15 + i + z + !'
' '  + 4  + i + z + !'
' '  + 2  + i + z + !'
' '  + 19 + i + z + !'
' '  + 4  + i + z + !'
' '  + 3  + i + z + !'
'  '   +  s  -  !'
'  '   +  n n + n n + + c + -  !'

$

Output:

 Unexpected.

Explanation:

 uses ascii charcodes. the letters refer to addresses, which are integers in the range 0-25.

PHP, 59 or 31 chars
Does it have to be a real word? If not, this will work:
echo preg_replace('/[0-9]+/',"",substr(md5(time()),0,25));

or even this if numbers are okay:
echo substr(md5(time()),0,25);

Set a range
echo substr(md5(time()),0,rand(1,50));

I am so stupid. I mean "knife", not "nife". As I can not produce "knife", I edited my example to produce "fine". (Such word exists, isn't it? :) )

I clarified my question.

Haskell
Classic:

let 1+1="Hello World!" in 1 + 1

 Outputs Hello World!. No kidding.

Should be a word.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

authors: Дамян Станчев

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


text:
Create a Question Asker!
Writing questions for programming puzzles is tiring and takes many minutes to do. This is where you come in. Your job is to write a program that randomly generates plausible-sounding (but not necessarily interesting) code golf questions.
Input: None
Output: One sentence code golf question (see sentence structure)
Guidelines: No hardcoding. The questions don't have to be valid, solvable, or nontrivial. Creativity is encouraged. Voting is based on variety and bonus to programs that can create interesting problems.
Samples:
Find the sum of every even number from 1 to 100.
Create a funny sentence without punctuation.
Draw a picture of a cat in 3D.

Sentence structure:
[verb] [noun goal] [of] [noun specific] [preposition] [noun restriction]

NetLogo
to go
  type one-of [ "Print" "Calculate" "Find" "Determine" "Output" ]
  type " the "
  type one-of [ "sum" "mean" "average" "median" "standard deviation" "product" "geometric mean"]
  type " of all "
  type one-of [ "prime" "composite" "even" "odd" "perfect" "abundant" "deficient" "square" "triangular" "cubic" "lucky" "friendly" "strictly non-palindromic" ]
  type " numbers from "
  type random 100
  type " to "
  type 100 + random 10000
  type one-of [ " (inclusive)." " (exclusive)." ]
end

Sample output (obtained randomly):
Find the product of all friendly numbers from 60 to 3112 (inclusive).

C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    srand(time(NULL));
    printf("Find the sum of every even number from 1 to %d.\n", rand());
    return 0;
}

On my computer it can generate 2147483648 different challenges.

Hahaha. I love the simplicity (laziness?) of this one. Also, you can golf it so it's 50% #includes: delete int and return 0, NULL---> 0, text "sum of even numbers 1<x<%d?"

Python
from random import randint as r
print "Draw a picture of a cat in %iD" % (r(2,4))