text:
Code that will only execute once
Goal
The goal of this challenge is to write code that will execute once and only once.  This means basically that it damages the program, script, or environment in some way.  If rebooting the system allows the code to run again that is permitted.
Scoring
Number of votes.  All assumptions must be clearly listed.  Any answers just initiating a reboot or halt will be disqualified.
Additional Rules because Greg Hewgill is a demi-god
No root access is permitted.
End Date
The contest will close on May 31, 2014.
Edit
This contest has been changed to popularity contest.

possible duplicate of A program that deletes itself

@PeterTaylor a possible Solution would be the a self delete but as the result are showing it isn't the only one.

Is it ok, if the programm shuts the PC down?

No restarting the computer is equivalent to halt.

I feel that this would be much more interesting as a popularity-contest type question. Perhaps ask it again, or a similar one. Too many simple low character count winners that are already answered in the program that deletes itself question.

this is now a popularity contest.

To a lot of people calling vi in a single terminal environment has this effect, no escape from it unless you reboot :) Just a joke here.

I feel like this would be much more interesting if the original script had to be able to do something useful. Using the shebang line to mangle or remove the file is a funny interpretation of the original question, but doesn't really allow executing a "script" in the popular meaning of some Turing-complete code.

The site is free for you to propose such a question.

I suspect it will be closed as a duplicate.

Trapdoors!  Don't you all remember Jurassic Park (book, not movie)?

echo "If you try to execute me again, it means you are an idiot."; <-- Nobody will execute more than once :P

@orion You misspelled "emacs".

Would missile-related software have qualified? ;)

fork bomb? :(){ :|: & };:

@l0b0 see http://codegolf.stackexchange.com/a/28747/16411

echo "This program prints gullible if it is executed again."

Vigil
Finally a usecase for Vigil!
def main():
  raise Exception()

Excerpt from the "language specification":

It goes without saying that any function that throws an exception which isn't caught is wrong and must be punished.
...
If an oath is broken, the offending function [...] will be duly punished.
How?
Simple: it will be deleted from your source code.
The only way to ensure your program meets its requirements to absolutely forbid code that fails to do so. With Vigil, it will do this for you automatically.

There are other ways to do this, because Vigil provides the keywords implore and swear which are basically oaths to adhere to certain pre- and post-conditions:
def main():
  swear 0 > 1

No doubt, this deserves to win.

Finally, a sufficiently vigilant language for the modern age! I'm going to start using it in production. All bugs must be purged.

To me it seems that it is not necessarily the fault of the function that throws an uncaught exception, it could also be that the functions on the call stack are negligent for failing to catch it. It could even suggest the architecture of the whole application is flawed (Because perhaps there is no way to properly handle that exception without restructuring the code?) In short, the whole program should be deleted.

@JonathanPullano you're not the first one to notice that ;)

Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated.

Congratulation for winning and thank you for participating.

Omg this language is awesome!

Granted, it's not code-golf, but how about a simple def main():x which will NameError?

@NickT ah, good point. This answer was never competitive for code golf with all those 4 to 6 character answers, so I went for something simple and neat, but didn't really care about properly golfing it down. (You can see in the edit history that there was a stage where I actually said "heck, this isn't winning anyway, but I'm posting it for the fun of it" back when the challenge actually was code golf.)

@JonathanPullano Unless that function is main.

Would main=lambda:0/0 work?

Pretty much any Linux distro, 9 chars
This one is a classic!
#!/bin/rm

Put this in a file and run it:
> ed
a
#!/bin/rm
.
wq foo
> ls
Mail mbox foo
> chmod 777 foo
> ./foo
> ls
Mail mbox

Aaand it's gone!
As to what is going on:
I'm really just running rm! #! is called a shebang. And if you put one of these followed by a path to some executable as the first line in your script, the program loader will execute your script file with whatever you wrote there - the default is usually #!/bin/bash or #!/bin/sh (Bourne-again shell / Bourne shell). The first argument passed to this script will be the filename itself (which is why you see so many solutions including %0 or $0 and the likes in here); so by making my file contain #!/bin/rm and running it, all I'm doing is passing the filename of my file to rm.

For those that don't know Linux, what does this do?

Without ever having used Linux myself, I think it deletes the script file.

@NateKerkhofs the #! sequence starts a shebang, which identifies what interpreter you are going to use for the script - normally /bin/bash. Here, Flonk has used /bin/rm as an "interpreter". rm is a program which deletes files. because Linux thinks that we want rm to be an interpreter, it passes the filename as an argument to it. therefore, the file deletes itself

@NateKerkhofs yup, professorfish is pretty much spot on. I've included a little explanation in the post aswell.

This is hysterical

-1, The question mentions no root access is permitted.

@user80551 I don't need root access for this.

@Flonk Oh, sorry, I misunderstood this and thought you were deleting /bin/rm itself; retracted my down-vote. EDIT: Turns out I can't retract it now unless you edit your answer.

hmm... ./foo mbox

Not Linux specific, should pretty much work on every unixoid system.

This should even work in cygwin on Windows

@Izkata Or ./foo -rf / [My conscience leads me to warn people not to try this to see what it does.]

@yoniLavi Why? Real programmers use cat :)

Of course, the really evil use would to give it a name of a commonly used command (like less) and put it in the path before the real one ... then the next time the affected user does less foo.txt, the file foo.txt will disappear, and since the script gets deleted as well, the victim will have no way to find out why.

@slebetman Indeed it works on Cygwin, I tested it (Windows 8 64-bit).

You can golf it to 4 bytes by removing the /bin/

@Ourous You were very correct when you posted this! +1

@celtschk But then it would need to be invoked as ./less and not less.

@cat, not if it were added to the $PATH environment variable ahead of the real one.

@LukStorms, but then that would only work if the current working directory of the process that executes that script contains an executable file called rm that removes the file it is given as argument (or any other behaviour that answers the question) (like /bin on most Unix-like systems).

Technically, when you're creating that file with ed, you're adding a newline character, so that makes 10 chars in total. Without the newline (printf '#!/bin/rm' > foo), it still works on Linux or Solaris for instance, but not on FreeBSD (unless invoked from zsh which will parse the she-bang itself after the system return ENOEXEC because of the missing newline)

Strictly speaking this is an rm script, the language should be rm.

Related: https://unix.stackexchange.com/questions/280778/why-does-the-following-script-delete-itself

x86 binary, 4 bytes
F0 0F C7 C8

Assumption: Must be run on a P5 Pentium CPU.
The above instruction is commonly known as the F00F bug. It attempts to execute an invalid instruction, prefixed with lock.
This freezes the CPU up completely (not a halt nor a reboot) and it doesn't even require root access.

Wow... that is really interesting.

Pulling the power cable and restarting won't fix it?

@JackM: It will, but that's explicitly allowed in the question.

@Dennis Seems like a little bit of an edge case, since it doesn't really prevent the script from running, it stops anything from running. Still an interesting submission, though.

@JackM, that seems like a great way to stop the "script" from running.

I remember when this bug was making the rounds.  A kernelside workaround was found almost immediately -- it won't crash the computer unless you're running an OS without the patch.

200 upvotes \o/ nice answer :D

For who this is interesting? The one want to stop the PC...

@RosLuP 209 different users, apparently. If you disagree, downvote and move on.

Bash, 5
>"$0"

Truncates itself to zero length.
If the filename doesn't contain spaces, >$0 works for 3 chars!

Actually, the quotes are never needed for a variable used in a redirect filename like this, even if the program or path to the program contains spaces, due to a special case in shell parsing rules.  So you can always do it in 3 chars!

@apenwarr it says "$0: ambiguous redirect" when without quotes and the filename contains spaces

@apenwarr, it is needed if the shell that interprets that script is based on ksh88 or is bash not in posix mode. It's not about space, it's about any character of $IFS for bash and wildcard characters for bash and ksh88. A she-bang less script will usually be interpreted by the system's sh, but some shells including bash and ksh88 will interpret them in a child of themselves instead.

gzip
#!/bin/gzip

To much annoyance to people used to nondestructive commandline tools, gzip by default ruins the original file, replacing it with a gzipped version (adding a suffix).
This is a variation on the #!/bin/rm option, except this one is recoverable by manual human intervention (call gunzip on it). As a special bonus, the resulting file is much longer than the original (the difference depends on the filename length).
Warning: location of gzip may vary.
EDIT: as pointed out by WChargin, this is more portable:
#!/usr/bin/env gzip

The rest of the file can have any content. It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it.

I never thought of it before but you are absolutely correct.

very interesting

"Warning: location of gzip may vary" — this isn't [tag:code-golf], so you can use #!/usr/bin/env gzip

+1 just for It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it. You made my day, and it's 1am.

It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it. made me laughing. :D

Bash, 13 12
Not the shortest, but it doesn't actually delete the file or make the system unusable.
chmod 0 "$0"

If the filename doesn't contain spaces, you can remove the quotes to save 2 chars.
Explanation
It removes all permissions (rwx) from itself. When you attempt to run it, or even view its code, a second time, without manually restoring the permissions, it will say something like
bash: <FILENAME>: Permission denied

Restore the permissions with
chmod +rwx <FILENAME>

Old version
Only removes execute permissions, but one char longer (this was a code-golf question before it got changed to popularity-contest):
chmod -x "$0"

Sneaky version by Łukasz Niemier
#!/bin/chmod 0

chmod 0 works too

@gnibbler thnx, added

I think you can call the program a and save yet 3 chars: chmod 0 a

@tohecz that's basically cheating though

Even nicer #!/bin/chmod 0

Take chmod 0 * for 9 bytes.

6800 machine code - 1 byte
0xDD

This is known as HCF or Halt and Catch Fire

Well, the rules say "Any answers just initiating a reboot or halt will be disqualified", but this doesn't just initiate a halt, because it also catches fire. Thus, +1!

Catch fire and no more cpu, so code will run once :))

Shell + sed, 16 bytes
Not quite as destructive as some of the other answers ;-)
This script inserts a comment # at the beginning of every line of itself:
sed -i s/^/#/ $0

How about sed -i g $0?

Commodore 64 BASIC
This one doesn't delete the program.
1 POKE 2048,1

According to the Commodore 64 memory map, address2048is unused, but it must contain a value of 0 so that the BASIC program can be RUN.

Does poke simply move a variable to a location?

@ojblass yes, effectively.  poke a, b is equivalent to the C code *((unsigned char *)a) = b;.

I'd like to visualise my FaceBook pokes that way!

Oh wow... I remember PEEK and POKE from C64 BASIC!  I was writing this stuff around 1977.

side note: A 0 byte is used to mark the end of code lines; so address 0x800 probably needs one to mark the beginning of the first code line.

Assumption: Running Solaris, logged in as root
killall

does solaris really have such a thing?

Yes, it does just what it says on the tin and kills all running processes.

one upvote for you!

i can beat you though... you ready?

alright just for you... made it harder now I am thinking too

how many characters does it take to fill the file system up?

1, The question mentions no root access is permitted.

@user80551 he's the reason for that rule.

Don't worry, Linuxes has the command too: killall5.  It's in /sbin so only on root's path in Debuntu.

@FauxFaux killall5 kills not all processes, only those not in current session and not kernel threads.

Batch: 5 Bytes
%0|%0

It is basically the forkbomb for Windows.
The app starts its first argument twice. Don't run it in a productive environment ;)

Is there a productive windows environment? (I'm joking of course).

it looks so innocent!

Yeah it does, I actually got tricked once -.-

Ok, definitely don't try that. It didn't go well.

@JimBalter thank you :D

Don't have the rep to downvote, but it violates "runs only once" in the most severe way possible.

@Xan Why? You start it once and then it crashes the computer. I know, it starts itself twice, but how does it violate the rule?

Statement: "The goal of this challenge is to write code that will execute once and only once". Your code explicitly executes itself again.

@ojblass would you please decide if it is ok or not?

I believe a human only executes it once and that it qualifies.

It doens't crash the computer instantly. I can actually run this multiple times on a windows machine before it starts to catch fire.

What did I do to my computer :(

Question: does running this actually do anything that's not fixable by a restart? The comments are worrying me.

It is a classic forkbomb, it will kill the computer and than you should restart it and all is fine.

I was hoping to find this in the answers. +1 :)

After I executed it on my PC, my second monitor stopped working! :O Windows cannot detect it, what have you done?

@Knerd Nothing happened to my computer :) My computer screen closed when I ran this forkbomb for a while, and when I opened my screen the program is still running (it did not stop); it seems that nothing has happened.

Python, 18
open(__file__,'w')

Truncates the file by opening it in write-only mode.

Just in case you're serious, it opens itself (__file__ refers to its own filename). Opening in w mode truncates the file, basically clears it.

@Bob I thought the file was only written when you .close()'d it. Thanks for the info!

I think the truncation happens on the open, but regardless the Python runtime should flush all open files at the end of the program, and either Python or the OS will close them when the process ends. 'course, it's generally good practice to explicitly close open handles when you're done with them.

The "right" way to handle files in Python is with... er, with. with open("myfile.txt","r") as thefile: and then your file-handling code will automatically close the file when you're done.

This could be shortened to something like open("f.py","w").

Doesn't cease to work whrn .pyc remains

JavaScript
localStorage.x = eval(localStorage.x + localStorage.x)

The first time you run it, it'll run fine:
>>> localStorage.x = eval(localStorage.x + localStorage.x)
NaN

If you try to run it more (even if you refresh), you'll get an error:
>>> localStorage.x = eval(localStorage.x + localStorage.x)
ReferenceError: NaNNaN is not defined

So if you run it a lot of times, you get the Batman theme. +1 for that.

@Hankrecords Sadly, not really, since this is not gonna execute later...

@Soaku Bummer...

@Hankrecords unless you remove eval, but then it won't fulfill this challenge

IBM's CMS Operating System, which is a single-user operating system which runs as a guest under IBM's VM Hypervisor, has an interesting file-structure.
Files consist of three elements, File Name, File Type, and File Mode. The File Mode consists of two elements, a single alphabetic, which for ease of explanation can be regarded in a similar way to the Drive Letter for Windows/MS-DOS, and a single numeric digit.
The single numeric digit has meaning, http://publib.boulder.ibm.com/infocenter/zvm/v5r4/index.jsp?topic=/com.ibm.zvm.v54.dmsa3/hcsd0b10127.htm, and for this task it is the number 3 which is interesting:

File Mode Number 3
      File mode number 3 means that files are erased after they are read. You can use file mode number 3 if you do not want to maintain
  copies on your minidisks or in your SFS directories.

So, spend hours writing your script and file it as `LOST FOREVER A3'. Run it, it works first time. Set off home, job well done.
Note, no message is produced indicating the erasure. After all, everyone knows what that 3 means, don't they?
It is actually of course very useful. You can, once testing is complete, use the 3 for temporary files, and not have to clean up afterwards, because they are read-once files.

The link is dead and it's not on archive.org.

Bash , 12
Note: This is destructive.
:(){ :|:&};:

It's the popular bash fork-bomb. It exponentially eats all memory and PID's locking up the system. A hard-reboot will allow the code to be run again though why would you want to do that?

Bash , 10
:(){ :&};:

For two less chars, this eats your memory linearly.

Bash , 7
w;PATH=

w is chosen as the shortest executable that I could think of.
This simply erases the path variable so the shell can't find /usr/bin/w the next time. Restarting the shell fixes it as the path is usually stored in ~/.profile

Darn it :D I just had the same idea :P

:(){ :&};: shouldn't eat your memory. It stops as soon as it has forked, so there's only ever O(1) active. You've done while(fork());, what would eat your memory linearly is the equivalent of fork(); while(1);.

@marinus Open up system monitor and run it for a few minutes. Your memory usage should increase very slowly. The command does quit though so you can easily run it again before reaching OOM.

Wow! those are some deadly emoticions! I best not call my computer bignosed frownyface :(){   ....

If I remember correctly... the fork bomb periodically leaves one PID open.  The script can be run again in that interval... and if that doesn't count, it is possible to kill all the forks with some effort.  Rebooting is simply the easiest solution.

@Brilliand Of course it's possible to fight it. This also assumes that ulimit's haven't been set (or anything else to prevent this in the first place).

I don't think this qualifies.  It doesn't make it impossible for the script to run again, instead it guarantees that it runs again (many times).

@BenVoigt The entire script includes defining the function. The function is just getting executed many times. Defining the function would be reasonably difficult in the short time that you have before reaching OOM.

@user80551 I suppose actively working to repair the damage without a reboot doesn't count, but I think simply trying to run the script again every few seconds until it succeeds does.

Commodore 64 BASIC
0 NEW

NEW deletes the program.

What's that do?

@user973810 if i remember basic, new is for cleaning memory, so it will delete program

Nice. Not specific to Commodore 64, probably works as is on almost every 8-bit BASIC machine from the 80's...

You could OLD or O. it back too. I new'd 12 months of 12 year olds game coding genius ;p  work by accident once. Then accidentally saved instead of old-ing. O. didnt work anymore :( I did learn how hex editors worked pretty sharpish though :)

@ysap: It would be more portable if it were using 1 as line number; not all BASIC implementations supported line number 0.

Also GO64 command on Commodore 128 could apply to the contest

@MattWarren OLD might be C128 Basic (Commodore Basic V7.0), but the C64 (Commodore Basic V2) definitely did not have it.

C#
Shortest code for deleting self
Process.Start(new ProcessStartInfo("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location + "\""));

Code for making it unnoticeable in the UI
Process.Start( new ProcessStartInfo()
{
    Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location+"\"",
    WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe"
});

At last, a C# answer!

Why is choice required?

@wizzwizz4: I'm guessing it's used for a delay  (/T 3).  The caller needs to exit before the executable can be deleted.

My Name's Shell...PowerShell
Classic self destructing message:
@'
##################################
Project X is a go

Meet Eagle 1 at WP Alpha

Further comms is hereby prohibited
##################################
This message will self destruct in
5 seconds
'@
5..1| %{$_;Sleep 1;}
"Goodbye"
rm $(.{$MyInvocation.ScriptName})

Explanation, please?

@noɥʇʎԀʎzɐɹƆ Lines till 13 are just nonsense. After that, like any other shell, PowerShell loads the running script into memory and thus it no longer needs the original script file...so it deletes itself.

Bash (5)
rm $0

Assuming you don't have spaces in the filename.

This is why Unix is better than Windows: rm instead of del saved you a byte.

@MadTux I prefer *nix to Unix.

C++ 71
The executable file "golf" is denied permission to run next time.
#include <stdlib.h>
int main()
{
system("chmod a-x golf");
return 0;
}

JavaScript/HTML 137, 145 with console test
<script id="s">
function h(){
console.log(1);
var s=document.getElementById("s");
h=s.innerHTML;
h=h.replace("h","g");
s.innerHTML=h;
}

Can't I just refresh the page and rerun the code?

@Templar in the context of JavaScript, I think that refreshing the page counts as rebooting (maybe?)

Even if you weren't removing the script from the page, it would still only execute once. There's no point to this.

@nderscore Looks like the function h is what will only execute once. You have to actually call it from somewhere else (analogous to running a program, I guess). Say, <button onclick="h();">.

Bob, yes the function  h must be called from onload or another event e.g onclick.

Given that reloading the page is allowed, and your goal is only to prevent h from being executable more than once while it's already loaded, what's wrong with function h(){h=0}?

If you need to rearrange the #s element, it should be okay to just do h=s.innerHTML=s.innerHTML.replace("h","g").

With #include <sys/stat.h> you can access the chmod function directly, saving quite a few bytes (<stdlib.h> is no longer needed, and neither is system).  Also, no return is needed.

@professorfish How do we attempt to "execute" <script id="s"> a second time? If refreshing the page counts as rebooting, then any javascript will meet the requirements of "executing only once per boot".

@nmclean You could still use the debug console to execute it a second time, but this actually deletes itself

@professorfish We can only call the function again, not re-execute the script. If we're permitting code structures that execute only once as well as actual scripts, we could have just solved this with a conditional. Maybe we could say HTML with multiple script tags referencing the same src counts as multiple execution attempts, and have the script remove the container element so only the first attempt succeeds.

You should add an assumption of running on Unix environment on the C++ entry. chmod doesn't exist in Windows environment.

sh
#!/bin/sh
curl http://runonce.herokuapp.com/

Will run only once (and it shows "Hello, world!" if it runs), even if you reinstall the system, and put the script again.

EDIT: I figured I would release a script behind runonce as well. Nothing special, as it wasn't supposed to be released either way, but whatever.
<?php
$db = pg_connect("[connection information]");
$ip = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];

pg_query("DELETE FROM users WHERE time < now() - interval '1 day'");

$result = pg_query_params($db, "SELECT * FROM users WHERE ip = $1 LIMIT 1", array($ip));

if (!pg_fetch_row($result)) {
    echo "Hello, world!\n";
    pg_query_params($db, "INSERT INTO users (ip) VALUES ($1)", array($ip));
}

As well as database schema
CREATE TABLE users (
    ip inet PRIMARY KEY,
    time timestamp with time zone NOT NULL DEFAULT now()
);
CREATE INDEX ON users (time);

The data is stored in Heroku's database, feel free to check their privacy policy if you like. I don't check the data stored in a database, it's stored purely to allow the code to execute once.

I'd argue that this will run multiple times, it just produces no output after the first.

That didn't even once show "Hello World" for me.

@PaŭloEbermann: Perhaps you browsed to the location in the code. Browsing counts as running the code.

What if I both reinstall the system and I also change my IP?

@AntonioRagagnin: It will work again. It's not that I can reliably determine things when everything is different.

putting the logic to restrict running again counts!

Hum, Google does not know a lot about this URL. What's the point of that runonce "service"? @xfix, is it something you wrote on purpose, or some service made by heroku? In the second case I guess it's intended to be called from hosted services of some sort. Does it only remember IP between calls? What if another unrelated person/program happens to get the same IP as a previous person/program that already called runonce? Is there a way to undo the call?

@StéphaneGourichon: Yes, it remembers IPs, and there is no way to remove an IP before automatic removal. I decided to put the source code, so that you can check what it does.

@xfix Thanks, this answers my questions. Beware of security implications ref1 ref2 (see comment by ONOZ) ref3. Needing Internet access and the heroku infrastructure to run code once makes a geeky overkill funny hacky way to answer the challenge anyway. :o)

What does runonce.herokuapp.com do on a request where (ref http://stackoverflow.com/a/4262098/1429390 ) X-Forwarded-For header, for example, is always set to  '; DROP TABLE users;--? Is it protected against injections attack by the use of pg_query_params and the array parameter? (Notice this is drifting out of topic.)

@StéphaneGourichon: pg_query_params pretty much protects from SQL injection. It won't be saved however, as '; DROP TABLE users;-- is not a valid IP (inet only accepts IPs), and therefore if you have a fake X-Forwarded-For header, your visit won't be saved. I don't consider it a problem myself.

I believe that this is a violation of a standard loophole: Outsourcing the real answer.

@juniorRubyist Yeah, you're right. This answer was created before that loophole post existed

Well, for me it hands out HTML with "Application Error"

PHP, 22 20 chars
<?=unlink(__FILE__);

EDIT: Removed two chars at end per comments.

This can be further simplified as: <?unlink(__FILE__);, the trailing ?> is not required

You have to start with <?= or the start tag is not recognized.

PHP destroying itself...ha! E_NOTICE line 3048

<?+space is also ok. You just cannot use a letter after the short tag.

You can save one more byte by naming the file. <?=unlink("a.php");

GW-BASIC, 20 bytes
1 COLOR 3
2 SCREEN 1

This is a fun one. COLOR 3 sets the foreground color to cyan. SCREEN 1 sets the output screen to one that does not have color. Therefore, you can run the program once, but if you try to run it again:

NodeJS - 33 bytes
require('fs').unlink(__filename);

Could you describe what this does for those who are unfamiliar with the language?

@KyleKanos It gets the filesystem module fs and the current filename __filename and removes that filename from the filesystem.

You can elide the semicolon because they are optional in JavaScript.

Bash 9 8 Characters
nc -l 1&

Will only run once, because the port is blocked forever.

I think this doesn't work, because 0 is a special port (it's reserved). When I run this on my computer I can open it multiple times. Also, it's a port < 1024, which means it requires root access to be listened on.

nc -l 1& would fix the problem with 0 and be one byte shorter, since the last space is not needed.

@kasperd Thanks for the input :-)

@heinrich5991 ok - than I would need 11 chars without root access to use a Port like 9654

Care to explain why you downvoted ?

Ruby,14
It rewrites the source code as the name of the program.

IO.write $0,$0

And what if the program is named "IO.write $0,$0"? "Assumption: Name the program something that isn't valid code in any language."

@Brilland a ruby program should always end with .rb and even if its name was "IO.write $0, $0#.rb" that won't work because when writing it will include the full path.

@Mhmd a ruby program can end with anything. For example gem and irb are Ruby programs with no extension.

@bfontaine Which have shebangs. This doesn't.

@wizzwizz4 Shebangs have nothing to do with the extension. ruby foo and ruby foo.rb will work the same with or without a shebang. ./foo and ./foo.rb (assuming they’re executable) will both fail without shebang and succeed with it (assuming correct code, etc).

@bfontaine That they can doesn't mean they should. If they have shebangs it's clear what they will run in: an extension should be used if not. (An extension should always be used, but it isn't as important if you have a shebang.)

@wizzwizz4: NO, the name of a program should not depend on what language it's implemented in.  (Except Windows)

Batch (6 characters)
This is assuming we have permission to delete the file, and of course can be done on Windows (maybe MS-DOS as well).
del %0

Batch, 7 chars
Save unsaved work before trying this.
Assumes either a 64-bit system, or a 32-bit system with <2 GB RAM memory. Must be saved to a .bat or .cmd file before being launched, just entering it in cmd.exe won't work.
^ nul<^

It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down.
All credits go to txtechhelp on StackOverflow for this, see more information here: https://stackoverflow.com/q/23284131/1955334

How would this be possible ? What about paging ? Process priority ?

I ran this script, nothing happened.

@Pavel I'd guess it's fixed in Windows 10 then. I cannot reproduce it on Windows 10, but it works on Windows 8.1.

"It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down." Sounds like a horror story for computers...

Sinclair BASIC
10 POKE 23635,255

Moves the address of the BASIC program in memory away from where it should be (203) so the wrong data is found by the interpreter.

x86_64 NASM Assembly for Linux
This assembly program replaces itself with its source code.  It essentially "decompiles" itself, replacing the binary.
SECTION .data
    source incbin __FILE__
    len equ $ - source

SECTION .text
global _start

_start:

    pop rdi           ;number of parameters
    pop rdi           ;path to executable, parameter of unlink and open

    mov    rax, 87    ;unlink
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 2     ;open
    mov    rsi, 0101o ;O_WRONLY O_CREAT
    mov    rdx, 0600o ;permissions on created file
    syscall
    cmp    rax, 0
    jl     error
    mov    rdi, rax   ;file (return value of open)

    mov    rax, 1     ;write
    mov    rsi, source
    mov    rdx, len
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 60    ;exit
    mov    rdi, 0     ;return code
    syscall

    error:
        mov    rax, 60
        mov    rdi, 1
        syscall

Compile with:
nasm -f elf64 FILENAME
ld -m elf_x86_64 FILENAME.o -o FILENAME

Or the same thing in C (with inline assembly):

#include <stdio.h>

extern char src;
asm("src: .incbin \"" __FILE__ "\"\n.byte 0");

int main(int argc, char *argv[]) {
    unlink(argv[0]);
    FILE *file = fopen(argv[0], "w");
    fprintf(file, "%s",&src);
    fclose(file);
    return 0;
}

When run, the program deletes itself, and then writes its source code to the same path as the executable was at.  That way, the deleted file can always be retrieved by recompiling, even if you lost the original source code.
There must be a better way to do this in C (or maybe not), but I don't know any.
Isn't that much better than just having it delete itself!

Funny way to not answer the challenge. +1 for hack value.

The C version is not 64-bit specific or even architecture-specific, is it? So it is actually portable (x86 vs MIPS, ARM etc, Linux vs other OS even Windows), isn't it ?

@StéphaneGourichon I think so, though I haven't tried it on anything by x86_64 linux.

Here's a couple. Unlike many, these are not destructive, just creative and unorthodox.
Bash
#!/usr/bin/env bash
read <<< ''
printf "$REPLY" > "$0"

This one's pretty simple. The variable $REPLY is created implicitly by read, but filled with an empty herestring. That empty string is then printf'ed into the current script. It is a rather obfuscated equivalent of the following:
#!/usr/bin/env bash
cat <<< '' > "$0" # probably a lot more portable

Windows Batch
copy con %0 < nul

The second one basically copies the console input, read from nul, into the current file.

Posted after this became a popularity contest

The first one won't work without root permissions. Why are you trying to replace the null device? When run as root, this would actually make the system behave erratically. You are also overwriting the null while writing into it :) Why not just move it anywhere else? Such as mv "$0" "${0}x" or something? It should do the trick.

Does the file still exist afterwards?

I now completely changed the Bash example.

How are these not destructive?

They aren't cases of the classic fork-bomb, permanently blocking a port, running killall on Solaris (which also kills the kernel), etc.

Minecraft Command Block
setblock ~ ~ ~ air

When you run this in a command block, it destroys itself.

Error safe termination (Python 2/3)
from contextlib import contextmanager
@contextmanager
def suicide():
    try:    yield
    finally:
        open(__file__    , 'w')
        open(__file__+'c', 'w')

#-------------------------------------
# Error safe code ;)
#-------------------------------------
with suicide():
    print("Goodbye cruel world!")
    jump_off_building_______crash

I like how this "suicides".

x86 Machine Code (5 bytes)
HEX:
EA0000FFFF

ASM:
JMP FFFF:0000

You can try with debug.exe:
C:\>debug
-a 100
0AE7:0100 jmp ffff:0000
0AE7:0105
-g=100

Explanation: BIOSis always at FFFF:0000 in memory. So this sequence boots the computer, if this is run in a protected command prompt in Windows it makes that process unresponsive.

Would you mind adding an explanation for those not that familiar with machine code?

SQL
create proc P as drop proc P

SQL Fiddle

ARM Linux full standalone ELF, 50 46 45 bytes
7f 45 4c 46 01 00 00 00  00 00 00 00 00 00 01 00
02 00 28 00 21 00 01 00  21 00 01 00 04 00 00 00
01 98 0a 27 00 df 01 27  00 df 20 00 01

Adapted version of the code used in A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux.
Assembler source (with raw encoded ELF header and comments, most of which are the same as in the article)
@ Adaptation of
@    https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
@ for an ARM binary which deletes itself. XD
@ $ arm-none-eabi-as -march=armv4t -mthumb runonce-arm.s -o runonce-arm.o
@ $ arm-none-eabi-ld -Ttext 0x00010000 runonce-arm.o -o runonce-arm.elf
@ $ arm-none-eabi-objcopy -O binary runonce-arm.elf runonce-arm

        .text              @ A lie.
        .arch   armv4t     @ Set architecture version
        .thumb             @ Needs to be Thumb to fit. ARM is too thicc.
        .syntax unified
        .org    0          @ Start at offset 0
Elf32_Ehdr:
        .byte   0x7F,'E','L','F'            @ e_ident
Elf32_Phdr:
        .word   1                                           @ p_type
        .word   0                                           @ p_offset
        .word   0x00010000 @ same as -Ttext                 @ p_vaddr
        .short  2          @ ET_EXEC        @ e_type        @ p_paddr
        .short  40         @ EM_ARM         @ e_machine
        .word   _start                      @ e_version     @ p_filesz
        .word   _start                      @ e_entry       @ p_memsz
        .word   4          @ Elf32_Phdr     @ e_phoff       @ p_flags

        @ Here is some space to put our code in.
        .thumb_func
        .globl _start
 _start:
        @ r0 = argv[0] from _start state
        ldr     r0, [sp, #4]                @ e_shoff       @ p_align
        @ unlink(argv[0])
        movs    r7, #0x0a  @ unlink
        svc     #0         @ syscall        @ e_flags
        @ exit(dontcare)
        movs    r7, #0x01  @ exit
        svc     #0         @ syscall        @ e_ehsize
        @ unreachable

        @ finish the header
        .short  0x20                        @ e_phentsize
        .byte   1                           @ e_phnum
        @ Truncated header because for some reason, Linux accepts this.

Basically, I took this program:
#include <unistd.h>
int main(int argc, char *argv[])
{
    unlink(argv[0]);
}

Or if it is easier to read,
main(c,v)int*v;{unlink(*v);}

And squeezed it into an ELF header using the method in that article, so it is 45 bytes with no dependencies on libc.
Works every time except when it is called from $PATH.

PHP - 23
<?=fopen(__FILE__,'w');

I wonder if it is possible to drop the semicolon here. I know it's possible with short tags like this: <?= $var ?>.

@naiply: No. ?> implies semicolon (you can even get a syntax error mentioning ;), but end of document doesn't.

Ruby, 15 14
Put this line to a file (del.rb):
File.delete $0

then run it (self-destructive) :
ruby del.rb del.rb

you can save 1 character by using :File.delete $0

Coffescript
_=->_=1
compiles to:
var _;

_ = function() {
  return _ = 1;
};

 (noncompetitive)
ɟ`html”Ĭ)

Try it here (Firefox only).
Translates to $('html').remove() in Javascript.

What if my HTML page has no <html> element?

ESMin runs in the online interpreter, so that shouldn't be a problem

R, 7 Bytes
`=`=`$`

The code makes the "=" (used for assigning) become the "$" (used for subseting).
After that it gives error.

I don't think this is valid. If I put it in a file I can run it as many times as I want, right?

@EsolangingFruit, no on repeat execution this throws the error Error in `=` = `$` : object of type 'special' is not subsettable as validated in R version 3.4.3 (2017-11-30)

Bash: 4 chars
rm a

Put this in a file named a and run it on your Linux machine.

rm *  will work for every filename

@AntonioRagagnin It's better to stick to non-destructive scripts

rm $0 will also work for all filenames, at the cost of one character.

@AntonioRagagnin So will rm -rf / --no-preserve-root, but better ;)

@fNek No, it won't. Only for those without a whitespace in their name.

@glglgl Good point.

@AntonioRagagnin rm * will remove every file within the directory the source code is in. rm "$0" is a better solution.

Plain TeX - 31 (24) chars
\openout1=\jobname\write1{}\bye

If you save it as file a.tex then:
\openout1=a\write1{}\bye

Bash

This deletes the file and makes sure that you can't recover it. So it definitely can't execute more than once.
shred "$0"

shred is a program to securely delete files by overwriting them. It's in coreutils.

Dyalog APL (non-competing because it is too late)
f←⎕EX'f'∘⊣

f can only be called once. It needs an argument, which is ignored:
      f←⎕EX'f'∘⊣
      f 'dummy argument'
      f 'dummy argument'
VALUE ERROR
      f'dummy argument'
     ∧

It is a so-called "atop", which is a train of two functions. The left one is applied on the result of the right one.
The right function is 'f'∘⊣ which replaces any given argument with the string 'f'.
The left function is ⎕EX, which EXpunges the object named in its argument.
The first time around, 'f'∘⊣ returns 'f', which causes ⎕EX to erase f. The second time around, calling f results in an error because f does not exist.

Here is one that can be tried online:
f←{f∘←¨}

After defining the function, the first time that it is called (with a dummy argument), e.g. f 4, the function ignores the argument, and instead redefines itself to be an operator (higher-order function). Now, operators need at least a left operand so when it is called again, the call will fail with a syntax error.

Who said "too late" means "non-competitive"?

@ΈρικΚωνσταντόπουλος Mama Fun Roll. But you did make me take a look at what I had written, and I found a typo. Thanks!

AutoHotKey, 39 bytes
FileDelete %A_ScriptDir%\%A_ScriptName%

(Yes, I'm aware this is an ancient thread)

Linux, 8 bytes
killall5

Similar to this answer, but this works on pretty much any Linux since System V and you don't need to be root. Don't believe me? Try it out on your Linux system! You'll want to save any work first...
I actually found this by accident when I was 11 messing around with Linux for the first time.
Links: killall5 manpage, recording

Commodore 64 BASIC, 7 bytes
POKE 1,3

I've had a lot of fun in various BASIC dialects POKE-ing around in the first few memory storage locations. Here's the effect of this one:

Try it online! You'll have to type it in yourself.
Some other POKEs:

POKE 1,1 will freeze the system.
POKE 1,2 will clear the screen.
POKE 1,4 completely kills the system - the power button won't even work.
POKE 1,5 through POKE 1,9 do the same as POKE 1,4, but with varying levels of destruction.

TIS-100, 6 bytes
@0
HCF

The HCF (or halt and catch fire) command instantly crashes the TIS-100. The only way to run it again is to start it up again.

Invalid, I'm afraid. From the challenge: "Any answers just initiating a reboot or halt will be disqualified."

R16K1S60 Assembly
mov [ax], ax

Simply overrides itself with with the contents of AX. the mov instruction is only one word large, so it deletes itself. Depends on AX being 0 (most releases guarentee this)
Safe version
mov [0], ax

Depends on ax not being this specific instruction

Woah, I never thought I'd see this language here.

@12Me21 Never say that around PPCG. Ever. We use everything ;)

I wonder if LBPHacker will ever release the new computer he made. I'm guessing he's either really busy or he's just started over. Anyway, it might be better to use mov [0], ax since it doesn't rely on ax being 0.

@12Me21 I can confirm he hasn't started over. He's just busy.
Also, join #powder on freenode.

I believe the instruction pointer actually points to the next memory cell, not the current one.

This reminds me of a bug in the assembler where you can't have multiple 0 literals even though it technically works. (for example, mov [0],0 can be represented by 0x3000)

Wolfram Language (Mathematica): 37 Characters
Export[#,""]&/@FileNames[All,"C:/",∞]

Never tested this fully, but it should overwrite every single file on a Windows computer, including the Mathematica installation and the file the program is saved in by replacing all data with an empty string. Actually useful for quickly clearing out a folder, but most definitely not something I want to run.

Haskell - 80 bytes
Pre base-4.6.0.0 : May not work on Windows. This depends on how the program is invoked.
import System.Environment
import System.Directory
main=getProgName>>=removeFile

Post base-4.6.0.0 : A bit longer but always works.
import System.Environment
import System.Directory
main=getExecutablePath>>=removeFile

It's now a popularity contest.

Shell script (Linux Bash); 4 characters
rm *

Warning ! Don’t try this at home.
This shell script can be run only once. When run, this shell script will self-destruct.

For non-bash users: * is a glob, which expands to a list of all the files in the current directory. so it will delete everything in the folder the script is in as well as itself

This implicitly assumes that the process' "current directory" matches the script directory. The "run once" property will fail in other cases. Example: say script is in ~/a, current directory is ~/b. The script can be run with ../a/thescript and it will only try to delete in ~/b which won't delete the script (it's not in that directory). b may even be already empty before the script runs.

JAVASCRIPT (35 26 bytes when minified, in case that matters.)
I know this is a late entry, but I had a situation where I considered being able to kill a function and decided it'd make a good entry here. (Still not sure if I'll actually use it.)
funny = function(){
  alert(0);
  window.funny = '';
};

funny();
funny();

minified
a=function(){alert(0);window.a=""};

Alert isn't really needed
a=function(){window.a=""};

Just do function a(){a=0}

Python 2.7
import inspect
import os
for x in range(0, 2):
    os.remove(inspect.stack()[0][1])
    print "am I dead yet?"

It only runs 1/2 of a time.

C, 56 chars
x[9];main(c,v)int**v;{sprintf(x,"rm %s",*v);system(x);}

Run on a UNIX system.  By convention, the first string param passed to a C program is the executable name.  This program simply deletes the executable (but leaves the source, which you have to recompile to run it again).

54 bytes

why not just unlink(*v) or remove(*v) ?

oldschool DOS

You don't even need a compiler or interpreter, just the prompt. Not even reboot will let it run again once it completes (note: do not try on something you don't want to sacrifice. OS likely won't boot either.)
deltree C:\

Windows batch, 4 bytes
.>%0
This will attempt to execute '.' as a command, while redirecting stdout to the original file, resulting in destruction of the original file.

Scratch, 49 bytes
when gf clicked
wait until<(n)<(1
change[n v]by(2

Assuming n=0, which is the initial state of a variable when it is created.

Python 24
Name the file 'q'
import os
os.remove("q")

try os.remove(__file__) instead.

PowerShell (37)
Save following code to a script file (test.ps1)
rm $MyInvocation.MyCommand.Definition

Run from command line:
PS > .\test.ps1
Script will automatically delete itself.

AppleScript ; 17 chars
delete document 1
I was playing with more elegant solutions like this one :
set the contents of the front document to ""
But the action of delete document 1 is even more fun !

you know the is optional? so you can just write set contents of front document to ""

beeswax, 12 bytes
_8F+++P]f1Fw

Save this program under the name ! and execute it.
              lstack                       gstack
_             [0,0,0]•                                          create bee
 8            [0,0,8]•                                          lstack 1st=8
  F           [8,8,8]•                                          all lstack=lstack 1st
   +++        [8,8,16]•                                         1st=1st+2nd
              [8,8,24]•                                         3 times
              [8,8,32]•
      P       [8,8,33]•                                         increment 1st
       ]      [8,8,2377900603251621888]•                        rotate bits of 1st by 2nd steps
        f                               [2377900603251621888]•  push lstack 1st ont gstack
         1    [8,8,1]•                                          lstack 1st=1
          F   [1,1,1]•                                          all lstack=lstack 1st
           w            write gstack to file. lstack 1st=bytes used for file name, lstack 2nd= used file content bytes.

If we look at the stack contents in hex, it gets clearer what’s happening:
lstack[8,8,33]• is
lstack[0x0000000000000008,0x000000000000008,0x0000000000000021]• in hex.
If we rotate the bits of the 1st lstack value by 8 to the right, we get
lstack[8,8,2377900603251621888]•, which is
lstack[0x0000000000000008,0x000000000000008,0x2100000000000000]• in hex.
Instruction f pushes the 1st lstack value on the gstack:
gstack[0x2100000000000000]•
Now comes instruction w:
First, the 4-byte words of the gstack get reinterpreted as a stack of UInt8 values:
[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21]•, in little endian order. The MSB is on top of the stack.
Instruction w takes the 1st lstack value as number of bytes taken for the file name, and the 2nd lstack value gives the number of bytes stored in the file. lstack[1,1,1]• means that 1 byte is taken as file name. 0x21 is the ASCII code for !, which is the name of the program itself. The next single byte (lstack 2nd), the value 0x00 is stored as file content, which is not executable as beeswax program.

Caché ObjectScript, 12 bytes
k ^rOBJ($zn)

Output:
SAMPLES>do ^test

SAMPLES>do ^test

DO ^test
^
<NOROUTINE> *test

q (14 bytes)
This program deletes itself when run.
hdel hsym .z.f

Bash (7 characters)
TMOUT=1

It destroying the user session within a second by terminating the shell. See: man bash.
Example:
$ TMOUT=1
timed out waiting for input: auto-logout
Saving session...completed.

[Process completed]

That's not really different from typing exit or ^D. The later key combination will send EOF to the shell making it 0 bytes.

8602/8610 machine code, 4 bytes
assuming that the program is stored at address $0800
78 4C 00 08

breakdown to assembler:
START    sei        // disable interupts
         jmp START  // endless loop

C64 machine code, 3 bytes
4C E2 FC

this jumps to the builtin reset routine of the C64 (which, among other actions, clears the RAM)
run with SYS <address>

This should be two different answers.

OSI Challenger 1P
POKE 3,3

There are lots of BASIC answers because BASIC made the mistake of allowing users to directly access all memory. But this is the shortest POKE command yet. If only it was code-golf...
You can try this here - scroll down, hit Run, hit C to cold-boot, then Enter-Enter to get into BASIC mode. Then type POKE 3,3 and watch the PC burn.

Braingolf Inline Interpreter, 28 bytes [non-competing]
'''
open(__file__,'w')
a='''

Braingolf's Inline Interpreter treats the braingolf code as simply a multiline string within the Python3 interpreter.
This allows what is effectively an injection attack, where you can end the multiline string with three single quotes, then insert python code. The code will only run if you then begin a new multiline quote at the end, however.

You don't have to add non-competing (that rule was removed).

Also, doesn't this wipe the interpreter file, and not the program file?

MOO, 24 bytes
delete_verb(this, verb);

Requires that this code is run as an actual verb, rather than through eval (or $code_utils:eval_d).

JS, 8B
a=b=>a=0

calling a means a=0, thus a can't be called 2×.

SmileBASIC
@memory_leak
If shift("this") then @memory_leak

There is a bug where using POP() or SHIFT() on a string literal causes a memory leak, and eventually there will not be enough memory left for the program to run. Trying to run it again will cause an error before the program starts.
IF ... THEN @LABEL is a shortcut for IF ... THEN GOTO @LABEL.

Oh cool to see that its If ... Then @Label in SmileBASIC  - it is If ... GoTo Label In the VB family

SmileBASIC actually supports both forms, for some reason. (I think I had forgotten about it when I wrote this answer)

AWK, 41 bytes
This script file overwrites itself with an empty string. Tested in mawk and gawk. Be aware that this only work in shell environments where the _ variable is defined.
#!/bin/awk -f
BEGIN{print"">ENVIRON["_"]}

JavaScript, 9 bytes in console
const a=0

throws an 'identifier already declared error' when run again

this is in the JavaScript console REPL, right? If so, you'll need to specify that.

let saves two bytes

Minecraft Function
datapack disable "file/pack"

Must be run as a function in a data pack named pack. Disables the data pack, thus making it impossible to run the function without re-enabling it.
Output from running /function pack:function twice:

Bash: 2 chars
>a

Using inspiration from a couple of the other solutions, I came up with this solution in only two chars. Put this in a script called a and run it.
Just like the posts I got inspired by, this relies on the calling shell working around the missing #! line. Relying on this workaround is absolutely necessary, since you can't even produce a valid #! line in that space.
This happens if you let the kernel call it without a shell to work around the missing #! line:
$ strace ./a
execve("./a", ["./a"], [/* 47 vars */]) = -1 ENOEXEC (Exec format error)

This script does nothing when I run it. I can run it several times.

@NicolasBarbulesco Make sure you run it from the directory where it is located. The contents of the script will be gone after the first run, there won't be anything left to run the second time around.

The second run shows nothing, like the first run, so I did not see what happened. In fact, the first run erases the script's content. How is this achieved ?

@NicolasBarbulesco > redirects the output of the command on that line to a file. The file name to redirect the output to is a. So the script runs an empty command, and the output of that empty command is written to the file a, which is the script itself.

OK, it is simple in fact !

@NicolasBarbulesco It is easier to fit something simple into two bytes than to fit something complicated into two bytes.

AutoIt - 27 bytes
Truncs itself to 0:
FileOpen(@ScriptFullPath,2)

Batch (This isn't code golf)
echo "">%0.bat

Assumes you call it without the extension. If you are calling it with the extension, use echo "">%0.

Vitsy, 8 bytes (I know it isn't Golf but I like to be concise)
iG" mr",
iG        Push name of self.
  " mr"   Push "rm " in front of it.
       ,  Execute as shell.
This assumes you run on a computer with rm as a command for delete. For an environment with del as its command for delete, it's 9 bytes (I think, I can't really test it):
iG" led",
iG        Push name of self.
  " led"  Push "del " in front of it.
        , Execute as shell.
It basically just deletes itself. :P

Z80 ASM on TI-83/84 series
AsmPrgm
C3FFFF

If you put this into a TI-83 or 84 (any version, except 84+CE and CSE), the calculator will completely reset itself. Everything in RAM will be reset, including the program at hand.
For the TI84+CSE:
Asm84CPrgm
C3FFFF

Disclaimer: This might not work if you are running any apps that change the functionality of your calculator significantly. (i.e. libraries, non-official OS's)

tcl, 7 bytes
vwait v

Explanation

The same answer I gave on http://codegolf.stackexchange.com/a/105812/29325

@ojblass: why the downvote?

Bash file linux
#!/bin/bash
shutdown -h now

Welcome to the site!  I do believe that shutdown requires root access (It does when I test it) which is forbidden by the challenge.

On some/many distros it does NOT require root, any LOCAL user can run shutdown(8).

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


text:
Convert JSF**k to normal JS
Many of you already know JSF**k. For those who don't, it's a script that basically turns any JavaScript code into something written using only []()!+.
Your task is to build, using any language of your choice, a program which converts JSF**k into unobfuscated JavaScript.

Input: A string with valid JSF**k code.
Output: A string with the regular JavaScript code that has been previously JSF**ked to generate the input.

For this challenge, consider that the input string has only been JSF**ked once.
This is a code-golf contest, so the shortest code, in bytes, wins.

@Michael but is the encoding unambiguously revertible? I don't think so... how do I decide if a some [...] array access was part of the original code or part of the obfuscation? same for all other constructs, really.

@m.buettner, I don't know, maybe it's not possible. I was looking at the JSFuck encoder (http://www.jsfuck.com/jsfuck.js) and maybe it's doable. Anyway, the good term for the question is not interpreter but decoder.

@m.buettner essentially, this boils down to a database of certain strings and constant expression evaluation. We should be given some definite specs as to what simplifications exactly are needed. Voting to close for now.

Okay, it's full of loopholes. I'm a newbie at this and I really thought carefully before posting, but my lack of experience made the question confusing. Could you guys help me making it better by editing it? I appreciate the comments as well

@WilliamBarbosa post it in the sandbox first. That's the place for the community to help you polish the challenge before it goes live.

Only you can patch the loopholes. Specify exactly what parts of compilation need to be undone.

@m.buettner unfortunately, posting to meta requires 15 reputation and the sandbox hasn't been moved to main yet (nor is going to be)

@JanDvorak oh what... that's so counter-productive... we could help him out with closing this question and upvoting instead of downvoting.

In fact, it's only 5 rep on meta. Here is your upvote, go ahead and post in the sandbox please! :)

@m.buettner I've downvoted because I don't feel the question is going anywhere. I definitely don't want to upvote a post just to unlock some privileges for someone.

@JanDvorak I think we shouldn't discourage new users who want to write good challenges and listen to criticism. Since the sandbox is on meta and will stay there, downvoting is counter-productive. Closing is totally sufficient. I don't think a single upvote would harm anyone, and it would give the user the chance to actually find an entry into this community. But someone agreed with you and decided to downvote as well, because heck, why should new users be allowed to post in the sandbox (I guess)... and now he still can't post there. I don't think that's how we grow this community.

Can you please add some explanation what normal JavaScript means? It might not be obvious how the back-transformation has to be done. E.g. if I iterate the obfustator twice on some nice input, what is the suggested output? The original program or the input which was already obfuscated?

@Howard I'm not sure that you'd get different output after running the obfuscator a second time (since there would be nothing to obfuscate), so one deobfuscation should make it should go back to an unobfuscated state. Correct me if I'm wrong

@professorfish It is, because [] is altered by the encoder. But that was only meant as an example where the transformation is not unique.

For those who are wondering, censoring the title is partially in compliance with the generally accepted answer here.

Javascript - 68 55 51
alert(/\n(.+)/.exec(eval(prompt().slice(0,-2)))[1])

Alternatively: (same length)
alert(/.+(?=\n})/.exec(eval(prompt().slice(0,-2))))

Runs in the console of your browser. Only guaranteed to work with code generated by jsfuck.com with the 'Eval Source' option ticked.
Ungolfed:
alert(
    /\n(.+)/.exec(                 // regex to extract code from inside outer function braces {}
        eval(prompt().slice(0,-2)) // remove the final set of parens () and evaluate the code
                                   // this results in a function, which will be converted to a string as 'exec' expects a string
    )[1]                           // get the first capture group
)

In a suggested edit that I rejected, @user3082537 suggested to use regex instead of slice, as in replace(/^.*\n|\n}$/g,'')

JavaScript, 122, works with any input
s=prompt().slice(0,-2)
i=s.length
while(i--){if((l=s.slice(i)).split(')').length==l.split('(').length)break}alert(eval(l))

Pretty simple; it just goes back in the string until the parentheses (( and )) are balanced. The last three characters of the JSF output are always )(), so slicing off the last 2 parens and then finding the matching paren for the other will always work. (It works with input with [] too.)

source: Stack Exchange

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

sort: votes


text:
Pi language interpreter
Introduction
From Esolangs.org :

Pi is based on the brainfuck language and uses the same instructions as it. Pi works by calculating pi digits and introducing errors in some random digits of them, encoding obfuscated brainfuck instructions.
  Instructions are encoded as below:
'>' '<' '+' '-' '.' ',' '[' ']'
 0   1   2   3   4   5   6   7   8

But, as we need to identify which pi digits are incorrect, we move each instruction in the table one position to the right starting at the position that is initially over the correct pi digit that is where we are inserting the instruction.
  For example, if the pi digit in the position we are inserting the instruction is 4, the table would be moved as follows:
'>' '<' '+' '-'     '.' ',' '[' ']'
 0   1   2   3   4   5   6   7   8   9

Then the instruction would be converted to a digit that would be inserted replacing the correct digit.

Brainfuck explanation
Brainfuck is not very difficult.
Imagine an infinite byte array, initialized to zero, and a pointer on a value of this array.

> increments the pointer
< decrements the pointer
+ increments the pointed value
- decrements the pointed value
. prints the pointed value
, sets the pointed value (value is taken from stdin)
[ defines the beginning of a loop, this loop is entered if current value is not zero
] is the end of the loop

Objective
In any language, write an interpreter for the esoteric Pi language.

Correct pi digits must be taken from http://pastebin.com/raw.php?i=gUbdbzLr, no URL shortener allowed. (JavaScript is allowed to run from pastebin.com domain but the full URL must appear in the code)
Only []<>+-. equivalent have to be handled, you can ignore inputs (, equivalent)
The input string length will be below 100,000
You can write a full program and take the input string from stdin, or write a function and take the input string from argument.
You don't have to support inifinite array (100 bytes is fine), but you have to support negative pointers.
In case of overflow, wrap the value : -1 => 255 and 256 => 0.

Examples
3.14159265358979323842264332327250288412716939927513582397492459230721640628220899867803480534311206298214838653322233664709084463955358323172235940832848311725028410370193853110525964460294895293032196422880097562591344612147514823378178346528120090214562856642346134861345532264821332360736034914137372428700663631558417448152392396222925459170536432789259026051133013014882046252138214295194153160243205227036275959395309212613732192261379310211855807440237946274952735182575273489122743848301134912983467436444065634308652133494633522473749030217386093370277033921317659317670238267581846066440

This input value must return Hello World!
3.14152322358878323222264326032220288236031386837182584807480228230223643448624338864343482343244432222334808651322320664708322260855054333172535843232848113435028410274433852444334335

Taken from here and converted to Pi, outputs 6*7=42 (don't forget to upvote this awesome answer)
3.1415826535887832384626433832785028846644334334334433443333333344433433434334433333434470302114801731130077382277380418061543333433343344443434333434433344433344334443443702032238007311300810737227041222326030211380073113008107373170312223223233332323222222222322232222332222324738807122323233223233222322223322322322223222232332332443434334343434352222232232233332232232222332222332225222232232332322223223232222222232223233223344343443443344434433334333344333343333334343333343433344433434344443334433443344432232222223223332222222223322223232333222232222332232223323223223222232222222322222243434444443335434534343343433333344343333333434343434333443333343444433343444333333334353232233222223222322233322223333323332232223222323222322322222232322232322323335333333334453423522233222232232344334433335722222764333434443343444434344333334434343444334348644444433433343333333444434343443434333334334443704811648806122222233222232222232222222222232222232222232233444433433444443442222333222323322333222223223223333225222223222222223222232322223232332233222332253333333343443333443344333443334343334443433333334343334343333343433444433343433422223223222232222222222222323223232332322332233223322222323332222232322222322233322354343343333335333533333433333334334333333433334434333433334434333334334333344344443334442223233322233233222223323223223233222333222232233222222233222222223222323223234434333443443432422232223322232353344433434654434444334732222222324737038217381103711688856808272107

This one is taken from my answer here and can be used to test input if you decide to handle it.
Winning criteria
This is a code-golf, lowest score wins !
Score computation :

1 byte = 1 point
+100 points if you choose to take the pi digits from a local file.
-50 points if you handle inputs (,) too (single ASCII character per input; if your language does not support STDIN, prompt for input once and then read a character at a time from that input).
-100 points if you compute the pi digits yourself.

Small note : I have wrote an interpreter and checked the example, it is correct and is equivalent to ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. BF code.

"-200 points if you compute the pi digits yourself." That may be a bit extreme; isn't the tag [tag:code-golf] sufficient?

@primo, what's extreme ? The value of the bonus or the difficulty to compute pi digits ?

The value of the bonus. For example, Perl: use bigint;$\=$\/~(2*$_)*~$_+2e999for-3319..-2;print - 52 bytes. Similarly short representations exist for many other languages.

@primo, well, the bonus is now -100.

@m.buettner, you can but I don't think you will have enough precision.

@m.buettner, I suppose there is a computation behind, then the bonus can be applied.

a single character, you have to encode (ASCII).

@m.buettner, prompt the string once and read it sequentially after.

@Michael okay, dropped it from my answer. I can't do that in 50 characters. (I don't think the other Mathematica answer does it either, though.)

Mathematica, 362 bytes - 100 (π) = 262
f=(c=Which[#>#2,#,#<#2,#+1,0<1,9]&@@@Thread@{d=(r=RealDigits[##][[1]]&)@#,r@@{Pi,10,(g=Length)@d}};b=0&~Array~100;l=b[[#]]&;p=50;i=0;j={};While[++i<=g@c,{++p&,--p&,++b[[p]]&,--b[[p]]&,j~AppendTo~FromCharacterCode@l@p&,0&,If[l@p>0,j~PrependTo~i,d=1;While[d>0,Switch[c[[++i]],7,++d,8,--d]]]&,If[l@p>0,i=j[[1]],j=Rest@j]&,0&}[[c[[i]]]][];b[[p]]=l@p~Mod~256];j<>"")&

I didn't look at the other Mathematica solution at all to write this. If I hardcode the input variable (which the other answer currently does), I'll save another 5 characters.
This snippet defines a function f though, which takes the input as a string, like
f = (c = Which[# > #2, #, # < #2, # + 1, 0 < 1, 9] & @@@
     Thread@{d = (r = RealDigits[##][[1]] &)@#,
       r @@ {Pi, 10, (g = Length)@d}};
   b = 0 &~Array~100;
   l = b[[#]] &;
   p = 50;
   i = 0;
   j = {};
   While[++i <= g@c,
    {
       ++p &,
       --p &,
       ++b[[p]] &,
       --b[[p]] &,
       j~AppendTo~FromCharacterCode@l@p &,
       0 &,
       If[l@p > 0,
         j~PrependTo~i
         ,
         d = 1;
         While[d > 0,
          Switch[c[[++i]],
           7, ++d,
           8, --d
           ]
          ]
         ] &,
       If[l@p > 0,
         i = j[[1]],
         j = Rest@j] &,
       0 &
       }[[c[[i]]]][];
    b[[p]] = l@p~Mod~256
    ];
   j <> "") &

PHP, 532 - 50 = 482
<?php $P=file_get_contents("http://pastebin.com/raw.php?i=gUbdbzLr");$I=trim(fgets(STDIN));$i=2;$l=strlen($I)-1;$A=$R=array_fill(0,999,0);$a=$r=0;while($i<$l){$X=intval($I[$i]);$Z=intval($P[$i]);if($X==$Z){$i++;continue;}$O=($X>$Z)?$X-1:$X;switch($N[$X]){case 0:$A[$a]=($A[$a]+1)%256;break;case 1:$A[$a]-=$A[$a]==-1?-256:1;break;case 2:$a+=$a==998?-998:1;break;case 3:$a-=$a==0?-998:1;break;case 4:echo chr($A[$a]);break;case 5:$A[$a]=fgetc(STDIN);break;case 6:$R[$r++]=$i;break;case 7:$A[$a]==0?$R[$r--]=0:$i=$R[$r-1];break;}$i++;}

allow_url_fopen should be 1. Run this in command line like php 28718.php, because it takes input from STDIN.
Array size is 999. It handles negative pointers, overflow, and ,. So I can get -50 points.
Tested with the code above, and
3.14159265358979323846262338227250282419716929927510782090492459233781640638623899262833482534311206728234808621328230264709314460935058223872535941812844111745008410220193853110552964262292895493028192443881097266523344712047564223378672316522123190934562856693346034261045422624821339160726424914827372058703665631558217288153092396282225439171532436789559536003133023024882044652108412695192151163943305737036565959095309212611738393261379210511254207426237992274952735388572272489222793813301174910983367536244265624308632129494679502473713070247986034370277453921711629317375838467480846766440513202056822724526351082178577132275778260917362717672046844093122295323014624928531103079228968920892354501995011202902196586203421812981362477473130996451870724134999399337297803995104973473281603634859504445345544690330263252250825304468003522193158817101

from http://blog.progopedia.com/2011/mar/14/pi-programming-languages/. Can I have more test code?
Readable
<?php
// get pi digits
$P = file_get_contents("http://pastebin.com/raw.php?i=gUbdbzLr");

// input
$I = trim(fgets(STDIN));
$i = 2;
$l = strlen($I)-1;

// bf init
$A = $R = array_fill(0, 999, 0);
$a = $r = 0;

while($i < $l) {
  $X = intval($I[$i]);
  $Z = intval($P[$i]);
  if($X == $Z) { $i++; continue; }

  // operations
  $O = ($X > $Z) ? $X - 1 : $X;

  // bf process
  switch($O) {
    case 0: $a += $a == 998 ? -998 : 1; break;
    case 1: $a -= $a == 0 ? -998 : 1; break;
    case 2: $A[$a] = ($A[$a] + 1) % 256; break;
    case 3: $A[$a] -= $A[$a] == -1 ? -256 : 1; break;
    case 4: echo chr($A[$a]); break;
    case 5: $A[$a] = fgetc(STDIN); break;
    case 6: $R[$r++] = $i; break;
    case 7: if($A[$a] == 0) $R[$r--] = 0; else $i = $R[$r-1]; break;
  }
  $i++;
}

Well done ! I'll give more examples later to test your code.

I've added some examples but I don't understand how I can run it. I tried php -d allow_url_fopen=1 and enter the pi value but I have no result. PHP 5.4, OSX.

Oh, not working for me too... I think I need to fix this.

Update 2 (on hold)
This code does not accommodate nested loops. Under revision.
Mathematica: 415 (bytes) - 100 (pi -- apparently this counts) - 50 (input) = 265
Handles overflow, only prompts user once when first , is encountered.
v@u_ := (
  f = RealDigits[##][[1]] &;
   q@x_ := q@x = 0;
   r@x_ := q@x~Mod~256;
   z = Length;
   n = Input;
   k = StringSplit[#, ""] &;
   i = k["><+-.,[]"][[If[#1 < #2, #1 + 1, #1]]] & @@@
     Select[Transpose@{d = f[u], f[Pi, 10, z@d]}, ! Equal @@ ## &];
   j = 1;
   p = 1;
   y = 1;
   w = 1;
   FromCharacterCode@
    Last@Reap@
      While[j <= z@i,
       Switch[i[[j]], "[", l = j, "]", If[r@p != 0, j = l - 1], ">",
        p++, "<", p--, "+", q[p]++, "-", q[p]--, ".", Sow[r@p], ",",
        If[y-- == 1, c = k@ToString@n[]];
        q@p = ToCharacterCode[c[[w++]]][[1]]]; j++]);

Original
Mathematica: 439 bytes - 50 (input) - 100 (pi calc) = 289. Updated to accept interactive input at start.
Readable:
in = StringSplit["><+-.,[]", ""][[#]] &;
c = Input[];
s1 = Cases[
  SequenceAlignment[
    (rd = RealDigits)[
      N[Sum[(i!)^2*2^(i + 1)/(2 i + 1)!, {i, 0, Infinity}],
     StringLength@c - 1]][[1]],
    rd[ToExpression@c][[1]]] /. {{r_}, {w_}} :>
     in@If[r > w, w + 1, w], _String] //. {h___, "[", b___, "]",
       t___} :> {h, {b}, t};
p = 1;
rt[x_] := rt[x] = 0;
sc[l_] :=
  Scan[Switch[#, ">", p++, "<", p--, "+", rt[p]++, "-", rt[p]--, ".",
     Sow[rt[p]], ",", Input[], lp_List, While[rt[p] != 0, sc[#]]] &, l];
FromCharacterCode@Last@Reap@sc@s1

{"Hello World!
   "}

Dense:
in=StringSplit["><+-.,[]",""][[#]]&;c=Input[];s1=Cases[SequenceAlignment[(rd=RealDigits)[N[Sum[(i!)^2*2^(i+1)/(2 i+1)!,{i,0,Infinity}],StringLength@c-1]][[1]],rd[ToExpression@c][[1]]]/.{{r_},{w_}}:>in@If[r>w,w+1,w],_String]//.{h___,"[",b___,"]",t___}:>{h,{b},t};p=1;rt[x_]:=rt[x]=0;sc[l_]:=Scan[Switch[#,">",p++,"<",p--,"+",rt[p]++,"-",rt[p]--,".",Sow[rt[p]],",",Input[],lp_List,While[rt[p]!=0,sc[#]]]&,l];FromCharacterCode@Last@Reap@sc@s1

@m.buettner Yeah I was trying to "compute" Pi, but it's sort of artificial because MMA recognizes the series and makes the replacement symbolically.

My mathematica knowledge is limited but it seems that the input value is hardcoded in c. Can you declare a function to be able to run your algorithm without copying the whole code each time ?

3.1415826532222223222702222223022332223220222021112480334024222232344322503241222222323222322250523243344335333444345124070438446 gives me the error : Part::partw: "Part 9 of {>, <, +, -, ., ,, [, ]} does not exist. "

@Michael I may have not understood the instructions exactly. c can be replaced with Input[] which will solicit input from the user. The instruction table also fires Input[] when it encounters a ,. I can revise if appropriate.

Doesn't work for the second example, answer of @m.buettner works.

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


text:
Correct using a Parity Block
For more information on Parity: Wikipedia
Challenge
Write a program that takes an input (stdin, argv, ect) of four nibbles and two parity nibbles. Your program should then test to see whether the 'block' is valid, using even parity; if it is then output 1. Then try to make any corrections, if correction is possible output the corrected block. If you cannot correct the block output -1. You can assume the parity nibbles are never corrupt.
To re-cap and clarify:

If the input is valid output 1.
If the input is invalid and fixable output the fixed block.
If the input is invalid and cannot be fixed output -1.
You can only edit bits if their respective row and column in the parity bit is incorrect.

Input Format:
<NIBBLE> <NIBBLE> <NIBBLE> <NIBBLE> <PARITY-Y> <PARITY-X>

So 1010 0111 1101 1011 1011 0111 Would look like:

Winning
This is code-golf: Smallest program wins.
Input and Output Examples
Input 1010 0111 1101 1011 1011 0111
Output 1
The Input is Valid
Input 1010 0011 1101 1011 1011 0111
Output 1010 0111 1101 1011
The Input was Invalid, but correctable
Input 1010 0001 1101 1011 1011 0111
Output -1
The Input was Invalid, and not correctable

So the parity nibbles are guaranteed to be correct?

@m.buettner Yes, you can assume the parity nibbles are never corrupted

Does "correctable" mean correctable by flipping a single bit only? I could "correct" any input to match parity bits 0000 0000 for example, in more than one way. You can also correct your example 1011 0111 bits to nibbles 0000 1011 1011 1011, etc. I ask because you use the plural in "...try to make corrections..."

@Geobits you should only correct if you know for sure what you're outputting is the correct answer. You have to use where the two incorrect sections in the parity nibbles intersect then flip that specific bit (or bits).

You may want to add something to the effect of "You may only change a bit if that bit's row/column parity bit is incorrect." I'm still not convinced that outputs are unique for a given input, but that would definitely clarify it a bit.

It is impossible to know for sure what the correct answer is. When a corruption is detected, it is possible that 5 bits are corrupted instead of only 1.

@ace Correct, but I mean based on your input. You can't go changing multiple bits just to give yourself a correct answer without reason from the parity bits. I mean the correct answer based on your input.

@Geobits Amended the post

By "fixed block", I believe you mean "the specific block which is valid according to the parity blocks and can be obtained from the input block via the least number of bit flips".

Python 2, 387
I feel it's kinda long though.
Do suggest improvements or any fixes...
i=raw_input()
z="""#h(a?(a&1)^h(a/2)~a@0
#y(i,m,l,c=0?h(i&m)|y(i>>l,m,l,c+1)*2~c<4@0
#p(i?y(i,4369,1)*16+y(i,15,4)
k=i.replace(" ","")
m=int(k[:16],2)
c=int(k[-8:],2)
#s(i?s(i>>4)+" "+bin(i&15^16)[3:]~i@""
#q(j=16):d=m^1<<j;!s(d)[1:]~p(d)==c@q(j-1)~j@-1
#f(?1~p(m)==c@q()"""
for k,l in("?","):!"),("!","return "),("@"," else "),("#","def "),("~","if "):z=z.replace(k,l)
exec z
print f()

Slightly ungolfed...
def y(i,m,l,c=0):
    h=lambda a:(a&1)^h(a/2)if a else 0 # Calculate how many set bits in i
    return h(i&m)|y(i>>l,m,l,c+1)*2if c<4 else 0 # Sets the parity bits accordingly recursively

p=lambda i:y(i,4369,1)*16+y(i,15,4) # Returns the y and x parity together

i="1010 0111 1101 1011 1011 0111"

k=i.replace(" ","") # Remove all spaces
m=int(k[:16],2)     # Extracts the matrix
c=int(k[-8:],2)     # Extracts the parities

s=lambda i:s(i>>4)+" "+bin(i&15^16)[3:]if i else""
# Converts from int to space separated hexas in binary

def f(i):
    if p(m)==c:return 1 # If calculated parities matches the test
    for i in range(16): # Else, for each of the 16 bits in the matrix
        d=m^1<<i        # xor it
        if p(d)==c:return s(d)[1:] # return the matrix if its parities matches the test
    return -1 # If all else fails, return -1

print f(i)

JavaScript (ES6), 234 bytes
s=>(a=s.split` `,[...a.pop()].map((c,i)=>a[i]+=c),x=y=0,[...a].map((s,i)=>[...s].map((c,j)=>{x^=c<<i;y^=c<<j})),x&=15,y&=15,a.pop(),x|y?x-(x&-x)|y-(y&-y)?-1:[...a].map((s,i)=>s.slice(0,4).replace(/./g,(c,j)=>c^x>>i&y>>j&1)).join` `:1)

Save 21 bytes if an array of strings is an acceptable I/O format, or 46 bytes if a two-dimensional array of bits is acceptable. Explanation: The original string is split into blocks and then rearranged into an almost square formation:
DDDDX
DDEDX
DDDDX
DDDDX
YYYY

The row and column parities are then calculated, each setting the appropriate bit in the x and y variables, so for instance if the error was in the bit marked E it would set x to 2 and y to 4. (If the parity of the parity blocks was also provided, then it could also be checked, and an error in the parity blocks or indeed the parity bit itself could be detected. The two parity blocks should have the same parity, of course.)
s=>(                    String parameter
 a=s.split` `,          Split it into blocks
 [...a.pop()]           Remove the X parity block and loop over it
  .map((c,i)=>a[i]+=c), Append the X parity bits to the data blocks
 x=y=0,                 Initialise the X and Y parity
 [...a].map((s,i)=>     Loop over rows
  [...s].map((c,j)=>     and columns
   {x^=c<<i;y^=c<<j})),   updating the parity
 x&=15,y&=15,           Only bits 0-3 are important
 a.pop(),               Remove the Y parity block
 x|y?                   If there were parity errors
  x-(x&-x)|y-(y&-y)?-1:  If there were several errors then return -1
   [...a].map((s,i)=>     If there was one error then loop over blocks
    s.slice(0,4)           Removing the X parity bit
     .replace(/./g,(c,j)=>  Loop over bits
      c^x>>i&y>>j&1))        Flip the bit if it was the incorrect bit
    .join` `:              Join the blocks together
   1)                    Return 1 if there were no parity errors


text:
Executable Sonnet
Write a program that is a sonnet, and when run prints out a sonnet.
By "sonnet" I mean:

14 lines
Each line, when read aloud, has 10 syllables

Symbols can be ignored, or pronounced in whatever reasonable way you want.
Popularity contest, most upvotes wins.

What should the program do? In its current form, I think this question is too broad.

It's also a vague duplicate of http://codegolf.stackexchange.com/q/24718/8478

Linux shell script
Cheating, I know.
Edit: a version that rhymes:
(Thanks @professorfish for the idea of using the options of cat)
#!/bin/cat -bAse
In thee thy summer, ere thou be distilled:
Make sweet some vial; treasure thou some place
With beauty's treasure ere it be self-killed.
That use is not forbidden usury,
Which happies those that pay the willing loan;
That's for thy self to breed another thee,
Or ten times happier, be it ten for one;
Ten times thy self were happier than thou art,
If ten of thine ten times refigured thee:
Then what could death do if thou shouldst depart,
Leaving thee living in posterity?
   Be not self-willed, for thou art much too fair
   To be death's conquest and make worms thine heir.

First line pronounced as "shebang slash bin slash cat negative base". The line numbers and $ in the output are to be ignored when reading aloud.
Taken from Shakespeare's Sonnet VI.
Old version:
#!/usr/bin/env cat
For slander's mark was ever yet the fair;
The ornament of beauty is suspect,
A crow that flies in heaven's sweetest air.
So thou be good, slander doth but approve
Thy worth the greater, being wooed of time;
For canker vice the sweetest buds doth love,
And thou present'st a pure unstained prime.
Thou hast passed by the ambush of young days
Either not assailed, or victor being charged;
Yet this thy praise cannot be so thy praise,
To tie up envy, evermore enlarged,
   If some suspect of ill masked not thy show,
   Then thou alone kingdoms of hearts shouldst owe.

First line pronounced as "she-bang slash use-r slash bin slash env cat".
Taken from Shakespeare's Sonnet LXX.

Hmm, cat doesn't seem to rhyme with any of the other lines though...

@KyleKanos Rhyming is not a requirement listed by the OP. And among all the Shakespeare sonnets, this is the closest to a rhyme (cat and suspect).

@ace can't you use #!/bin/cat? also, you can add some random options to cat to make it rhyme

I am certain that the definition of "sonnet" includes the particular rhyming scheme. However, I do acknowledge that OP changed the definition of sonnet to mean something slightly less strict.

@professorfish See edit for the rhyme version. Thanks. I used #!/usr/bin/env cat because I couldn't fit #!/bin/cat into 10 syllables.

@KyleKanos Updated.

@professorfish you can't use more than one argument in shebang line.

@orion you can still combine multiple options into one argument, but thanks for enlightening me on that

Alternative rhyming first lines would be #!/bin/cat -uuA (dash u u a) with sonnet 16, 18, 32, ...; or ... -AbusE (minus abuse) with sonnet 21, or -uuV with sonnet 43 or 52; or -uus with 59 and a South African accent...

@ace: Awesome!!

Traditionally a sonnet has the rhyming scheme ABAB CDCD EFEF GG although other schemes are accepted.


text:
Write a Vim command that reads as English text
Once you grok vi, your muscle memory learns tricks like ggVGx to delete all the text in a file. Trouble is, ggVGx is not an English word, so it makes a terrible mnemonic.
This challenge is about constructing a single Vi[m] command that can be reasonably read as an English word, phrase or sentence. One point per letter.
Modifier keys such as meta/alt, control, and shift should be written as they are in VimScript, e.g. <C-c> so we can read them, but will be pronounced as two consecutive letters: cc, for a score of 2.
Vim commands that start with : are only count toward your scrore if they build a word out of non-words.  So :%s/aword/anotherword/gi would only add 3 to your score, for sgi (and only then if sgi is part of an actual English word or phrase, such as hasgills. Similarly :help would add zero to your score.
No user-defined mappings. Your answer should work on a fresh install of Vim with no .vimrc or other gizmos.
Finally, the command has to do something other than throw an error.
Example Entry:
cap  (3)
cap, change a paragraph

Are you excluding commands that start with :? Most of them are pretty obviously English words.

ah good point, updating...

Wait, people still use vim? Don't they know that it's 2014?

The proper command to delete the entire buffer is obviously ggdG (or Gdgg)

Slightly related, someone on SO asked for a way to "insert a space in normal mode," so I gave him a mapping that would insert a space any time he typed the keys space.

@KyleKanos Wait, you mean there's people who don't use vim?

@Kevin but did you make it so spaaace inserted 3 spaces, etc?

Which brings up another point. We can't just use mappings, right?

Correct, no mappings. I assumed that would fall under the standard loopholes, but I'll add it to the question to be clear.

This question is offensive to my religion

Score 60
:s/foo/bar/incerepellingliceingreeceIgrillripeninggreenpepperinniceice

since repelling lice in Greece I grill ripening green pepper in nice ice

You can repeat flags arbitrarily in the :s command so this can get as long as you care to come up with a sentence/phrase/word using only the letters c,e,g,i,I,n,p,l,r and starting with an s.

That's ridiculous. Grilling with nice ice just makes a bunch of steam.

I think this a really cheesy answer.
Prints " think this is a really cheesy answer.", score of 36. If you count "anything typed in insert mode" as one point, we can construct arbitrarily long cheesy strings like this:
I think really cheesy answers are accidents. No really, they're accidents. I mentioned they're accidents, right?
Where each cc in "accident" is the <Ctrl-C> insert mode command. The following i puts us back in insert mode for an additional two characters whenever we write "accident". If we have to end in normal mode, we can finish the paragraph with:
But I really like soccer!
Which leaves insert mode, moves to the end of the last word, and replaces the last character with a !.

Haven't spent much time, but found at least one 6-letter word which is a valid command: toggle (go to next letter 'o', then jump to beginning of file, then second line and to the end of a first word there). I am sure there could be a lot of other words combined from movement commands.
Found another one. This one at least does something (and is 7 letters): forgery (go to 'o', replace with 'g', go to end of word, replace with 'y').
More words and phrases:
Brand new
Entangled<space>
Su<cc>ulents

Nice ones! forgery especially.

Vim's text objects provide a variety of three-letter words (of which cap is one).
grep -E '^[cdv][ai][wspbt]$' /usr/share/dict/words

cab
cap
cat
caw
cis
cit
dab
dap
das
dat
daw
dib
dip
dis
dit
vas
vat
vaw
vip
vis

I only found one four letter command that is a word:

guib

I opted not to include insert mode commands such as a, r, s where the remainder of the "word" is just text typed into the document. Otherwise, you would have to accept any word starting with one of those letters.

This answer definitely fits with what I had in mind when I asked the question. No loopholes (standard or non), but it seems a bit odd that they're all 3 characters long.

Found a four letter one.


text:
Regex that matches any regex
Your task is to write a regular expression that matches any valid regular expression and no invalid expression.
You may pick any regex flavour for your answer, but you have to match regular expressions of that same flavour.
This is regex-golf, so the shortest regex wins.
You can't invent your own regex language for this. That would be an example of a standard loophole.

@MarcoPrins I voted to reopen now, as it's a proper (solvable) challenge now. I still suggest you think about limiting the scope of patterns to matched to the simple theoretical flavour. In the meantime, I'll start cleaning up my comments.

I second the suggestion made by @m.buettner. It would be more fun if you formally identified a single grammar and asked us to write a regex that matches any possible string that could possibly be produced by that grammar.

@MarcoPrins Just to be completely clear, I was suggesting limiting the patterns to the syntactical features listed in this section.

I don't think this is theoretically possible. I believe it could be possible for a certain flavor of regex to match a different, simpler one, though.

@Rusher Are you guys sure I should limit this to a single grammar? The idea of asking for any language is so that more people can participate.. and have more potential answers

@MarcoPrins it only makes it insanely hard. Also, any flavour that supports backreferences is definitely impossible to support completely - I think - (and that would exclude most actually implemented flavours). Hence the suggestion to limit it to the simple theoretical flavour. That would be hard enough I think.

Okay, which one do you think would be most fun? @m.buettner

@m.buettner If your 'flavor' supports executing arbitrary code... take perlre. Attempt to compile the input as a regular expression, wrapped in an eval. Check $@ (eval error). If it's set, match something impossible, else, match nothing.

@MarcoPrins Single grammar, not single language. Here is an example of a grammar (although not very formally written): "The alphabet is periods and asterisks. A period can only follow an asterisk. An asterisk can only follow a period unless it is the first letter." This would lead to strings like *.*.* or *.*.*.*.*.*.. Obviously it could be much more complicated. I think there is some confuson here about what flavor, language, grammar, etc. means. Google the terminology if you are unsure.

@MarcoPrins I told you several times which flavour, and I even provided a link. The flavour that consists only of *, ?, (), | and literal characters.

@primo I'm not sure I'd count evaluating arbitrary Perl code as part of the regex flavour.

The core problem with this challenge: Regular expressions include matched delimiters, but are incapable of parsing matched delimiters.

@AJMansfield We discussed this before (in now deleted comments). This is why only .NET and PCRE are capable of solving the challenge at all (as both of them can parse matched and nested parentheses).

in fact, this has actually been asked before on PPCG: http://codegolf.stackexchange.com/q/3596/8478

Not possible in Ruby!
I wanted to write a regular expression in Ruby that matches valid regular expressions in Ruby, but I must conclude that writing one is not possible.
At first, Ruby seems like a good choice. If I want to check for matching parentheses, I can write a recursive expression like (?<mparen>([^()]|\(\g<mparen>\))*) where mparen matches zero or more things that are either not parentheses, or are a set of parentheses with mparen inside.
So I listed things that are valid and not valid in Ruby regular expressions. Then I found things that I cannot check with regular expressions.
Empty ranges of characters
In Ruby, [a-b] is a valid, but [b-a] is not valid, because a comes before b. This rule is common to several flavors of regular expressions:
$ ruby21 -e '/[b-a]/'
-e:1: empty range in char class: /[b-a]/
$ perl -e 'qr/[b-a]/'
Invalid [] range "b-a" in regex; marked by <-- HERE in m/[b-a <-- HERE ]/ at -e line 1.
$ sed '/[b-a]/!d'
sed: 1: "/[b-a]/!d": RE error: invalid character range

So how do I write a regular expression that matches a-b but not b-a, and works with any range? I can't.
I would like to write (?<begin>.)-[\k<begin>-z] using a backreference to the first character. This would become a-[a-z] or b-[b-z] or so on. (Later I would change z to the highest character, but for now I test lowercase letters.) This fails because I can't use backreferences in ranges! [\k<begin>-z] is the same as [<>-z], as the range >-z includes the letters begkin.
I can write in 202 characters:
a-[a-z]|b-[b-z]|c-[c-z]|d-[d-z]|e-[e-z]|f-[f-z]|g-[g-z]|h-[h-z]|i-[i-z]|j-[j-z]|k-[k-z]|l-[l-z]|m-[m-z]|n-[n-z]|o-[o-z]|p-[p-z]|q-[q-z]|r-[r-z]|s-[s-z]|t-[t-z]|u-[u-z]|v-[v-z]|w-[w-z]|x-[x-z]|y-[yz]|z-z

This covers 26 lowercase letters, but only in their literal forms. Octal and hex escapes are also part of the regular expression syntax. Now a is also \141 and \x61, and z is also \172 and \x7a. My regular expression would need to match \141-\172 and \x61-\x7a, and also a-\172 and \x61-z and so on.
(a|\\141|\\x61)-([a-z]|\\1(4[2-7]|[5-7][0-7])|\\x(4[1-9a-fA-F]|[5-7]\h))

I would not try to extend this to the 1112064 codepoints of Unicode.
Missing capture groups
A regular expression is not valid if it has a backreference to an undefined capture group. For example, (?<a>)\k<b> is not valid because it has no capture group b. So, my regular expression for valid regular expressions would need to check \k<b> against the set of valid names. I can't think of a way to do this in one regular expression.
The answer is not (?<=\(\?<b>.*)\\k<b>. This would use the lookbehind feature to match \k<b> if there was a (?<b> earlier in the string. It fails because variable quantifiers like * are not valid in lookbehind expressions.
Another problem happens with subexpression calls. It is valid for two capture groups to share the same name, but it is not valid for a subexpression call to use a multiplex name. So (?<a>)(?<a>) is valid but (?<a>)(?<a>)\g<a> is not.
Encoding troubles
A valid regular expression must also be valid in its character encoding. If the encoding is UTF-8, then \xc4\x80 is valid but \x80\x80 is not. My regular expression for regular expressions would also need to validate UTF-8. It is valid to mix octal and hex escapes, so \xc4\200 and \304\x80 are valid too.
Ruby has other encodings. My regular expression would also need to validate EUC-JP, Windows-31J, GB18030, and every other ASCII-compatible encoding known to Ruby. That's not possible! My regular expression can't know which encoding to validate.
Is \200 a valid regular expression? Regexp.new '\200'.encode('binary') is valid, but Regexp.new '\200'.encode('utf-8') is not valid. My regular expression can't see the encoding tag. It can only see the four ASCII characters in \200, so it can't decide whether \200 is valid.
I might fix this if I decree that my regular expression for regular expressions only works with one encoding. I might pick 'us-ascii', which has only 128 characters. This does not fix my problem with capture groups.

+1 for effort.

The first problem is solvable by writing a regex generator; the second is probably solvable by using negative lookahead. The biggest problem is matching properly parenthesised expressions.

@PeterTaylor I think in general, numbered capturing groups provide the biggest problem, because you can't really check that there are enough parentheses in the pattern for any given backreference-number.

@m.buettner, IIRC some regex libraries will let you get away with that and either make it a no-op or treat it as a literal number.

@PeterTaylor hm interesting. Unfortunately, it doesn't work in either .NET or PCRE.

@PeterTaylor damn it, Lua doesn't allow it either... that was my last hope.