text:
Shut down the computer!
Challenge:
In the programming language of your choice, shut down the machine that your code was executed on.
Rules

No shutting down by resource exhaustion (e.g.: forkbomb to force shutdown)
You are allowed to write code that only works in a specific environment/OS, if you wish.
Standard loopholes are forbidden

This is code-golf, thus the lowest amount of bytes wins!

I got friends, who do this in school and think they are 'hacking' :D

We should come up with some rule once to stop such \whatever`;` Bash/Perl/PHP/Ruby/etc. stupiglots.

Full shutdown / Power off @TheBitByte

Okay, are programs that shutdown after a specific time, and not instantly, allowed? The batch answers shuts down after one minute.

@TheBitByte as long as the other rules are followed, it's allowed.

Windows, 0 bytes. Leave the computer on for a few days and let automatic updates do their work

@LuisMendo automatic updates do not shut down the machine, only restart.

@briantist  Automatic updates have at times crashed my system, and I have mine set to not restart after a BSOD or other failures.....does that count? :P

@NZKshatriya the rules say no, it must be powered off  :-p

Crapola Well, that is one idea out the window.

@briantist On my computer, restart is shutdown followed by power-on

Is it acceptable, if the computer shows a confirmation dialog before shutting down but after running the program?

can the code be a function or does it need to be a programm ?

Anybody else notice the lack of TIO-links?

http://notaverb.com/shutdown

@MontyHarder After reading that page I have decided to coin the term shatdown: past tense of the verb shutdown

@MontyHarder People nowadays will verb almost anything.

If the machine catches fire, does that count as a "shutdown"? ;-P

Does killing the computer by deleting all the data on it count as a shutdown. ie: running any invalid bash script on suicide linux

@LuisMendo Depends on your settings really.

@LliwTelracs Resource exhaustion isnt allowed, and I guess important files for the OS are resources, that you "exhaust" by deleting.. or whatever.

@P.Ktinos But you are freeing up more space by executing rm -rf /

TI-BASIC, 2 bytes
Note that this only works on an actual TI-84+, not an emulator. Works great on a TI-84+CE with low battery charge.
:Pause
Waits for enter keypress. Don't press enter and it will run out of batteries sooner or later.

On systems that don't support shutdown, such as microcontrollers, can we reset or sleep?

@steenbergh Had you read the link, you'd see it's not an objection to verbifying other parts of speech. It's about the fact that "shutdown" (as a single word) can't be a verb.  Conjugate the alleged verb. Do I say "Every night before bedtime, steenbegh shutdowns the computer?" Would I say "The impasse between President and Congress shutdowned the Federal government for three days?"  If you can see that these are wrong, you can see why the correct "phrasal" verb form is "shut down" as two words, not one.

If the code turns off the machine, it is considered a shutdown?

@LuisMendo the rule requires the machine to be powered off, so the power on later is not allowed

I thought about the opposite challenge, "write a code that turn on the computer". But, I guess that beside wake-on-lan and options in BIOS/UEFI, there isn't much options around… (Cf. this question on ubuntu).

Just waiting for someone to find a JavaScript exploit for this challenge.

PC tower before ATX, 1 keypress. On Power buton!

@MontyHarder: dead link!

I was about to answer "%0|%0 windows batch, 5 bytes" when I saw the rule about resource exhaustion. Bummer.

Is "melting the CPU" considered to be "resource exhaustion"?

Assembly (x86/x64, Linux, as), 22 21 19 bytes
mov  $0x58,       %al  # 2 bytes: b0 58
mov  $0xfee1dead, %ebx # 5 bytes: bb ad de e1 fe
mov  $0x28121969, %ecx # 5 bytes: b9 69 19 12 28
mov  $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
int  $0x80             # 2 bytes: cd 80

Must be run as root.
This is equivalent to pressing the power button and not a safe way to power off your PC. Make sure you close all open applications and execute sync to flush all file system buffers before executing this program, to at least minimize the risk of file corruption.
Test run
$ as -o poweroff.o poweroff.s
$ ld -o poweroff   poweroff.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
$ sudo sh -c 'sync && ./poweroff'
root's password:

Followed by darkness.
How it works
int $0x80 invokes a software interrupt. It works on both x86 and x64, but has been deprecated for over a decade now and should not be used in production code. x64 code should use syscall instead. x86 should use sysenter, but it is too cumbersome for code golf.
The resulting action from the syscall depends on registers EAX - EDX, ESI, and EDI. The Linux Syscall Reference shows all syscalls that are available via int $0x80.
When EAX holds 0x58 (88), reboot is called, which can also be used to power off, put to sleep, or hibernate the computer, as well as switching kernels and disabling or enabling the Ctrl - Alt - Del key combo.
At the start of the program – and by compiling with as or gcc -nostdlib, we can make sure that we're actually at the start of the program – most registers are set to 0. This includes EAX, so we can use mov $0x58, %al to set the lower 8 bits of EAX to 0x58, thus setting EAX itself to 0x58. This saves two bytes over manually zeroing the register with xor %eax, %eax and one more over the straighforward mov $0x58, %eax which encodes 0x58 in 32 bits.
The first two arguments to reboot are magic numbers, presumably to prevent accidental reboots, and are read from registers EBX and ECX. Unless these numbers are equal to certain constants, reboot refuses to perform any action.

The first magic number must equal 0xfee1dead (feel dead), probably referring to the power off / death of the PC.
The second magic number can be equal to four different constants, although the latter three did not work in ancient versions of Linux. All of them seem to refer to the subsequent power on / birth of the PC.

0x28121969 represents Linus Torvalds's birthday (December 28, 1969).
0x05121996 represents Patricia Torvalds's birthday (December 5, 1996).
0x16041998 represents Daniela Torvalds's birthday (April 16, 1998).
0x20112000 represents Celeste Torvalds's birthday (November 20, 2000).

Patricia, Daniela, and Celeste Torvalds are Linus Torvalds's three daughters.
The EDX register selects the type of "reboot" we want. 0x4321fedc is RB_POWER_OFF, shutting the PC down and powering it off.
Finally, the value of the ESI register is ignored for RB_POWER_OFF; the value of the EDI register is ignored entirely by reboot.

Alternate version, x64-only, 19 bytes
On x64, we can use a proper syscall for the same byte count.
mov     $0xa9,       %al  # 2 bytes: b0 a9
mov     $0xfee1dead, %edi # 5 bytes: bf ad de e1 fe
mov     $0x28121969, %esi # 5 bytes: be 69 19 12 28
mov     $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
syscall                   # 2 bytes: 0f 05

The only differences lie in the instruction (syscall vs int $0x80), the value of __NR_REBOOT (0xa9 vs 0x58), and the involved registers.

Do we normally count assembly as compiled bytes without the framing bytes required for exe header?

Yes, because each instruction corresponds to specific bytes in the binary file. ELF files (or whatever format your OS uses) are considered a different language and would have to be created manually to achieve a decent score.

Could you add the hex dump after assembly of the code?

@ckjbgames Here it is.

I fee1 so dead right now.

PowerShell, 13 bytes
Stop-Computer

Pretty self-explanatory? Doesn't work on PowerShell core, so it won't work on PowerShell for Linux/MacOS (already tried it on TIO :-D ).
Bonus Garbage Submission, 12 bytes
gcm s*r|iex

In my testing, this works on Windows 2003 with PowerShell 2.0. It won't work on most of the newer versions, and it may not work depending on which modules are installed. It's quite terrible!
This searches the list of commands for any with the pattern s*r and then runs all of them! To be clear, this is dangerous, don't do this!
The trick of course, is getting a list of commands that don't have any mandatory parameters, otherwise PowerShell will prompt for a value.
On my 2003 machine, the 3 commands it returns are:

CommandType     Name                                                Definition
-----------     ----                                                ----------
Application     scrnsave.scr                                        C:\WINDOWS\system32\scrnsave.scr
Application     ssmarque.scr                                        C:\WINDOWS\system32\ssmarque.scr
Cmdlet          Stop-Computer                                       Stop-Computer [[-ComputerName] <String[]>] [[-Cr...

Yes, it does launch the marquee screensaver, but no, it does not wait for it to complete before launching Stop-Computer.
This approach can work on newer machines, again depending on which modules are installed, but the best I could do on Windows 2012 and 2016 was 14 bytes:
gcm sto*er|iex

(and yeah, sure, the winbatch submission will work in PowerShell and it's shorter, but.. that's no fun)

Shorter one for Win7 & Win10 (and maybe more): gcm *p-c*|iex -- and there's only the one result too!

@Bob highly dependent on installed modules still; on my Win10 machine it returns 6 results, several of which will have mandatory parameters (so they'll prompt and never make it to Stop-Computer, which is the last result).

Batch, 10 bytes
On windows, this would suffice
shutdown/s

This will set up a shutdown in one minute.
Alternatively, as @flashbang points out:
shutdown/p

This shuts down the computer immediately.

Press the big button on the front of your computer = 0 bytes

@RaisingAgent Here at PPCG we solve our problems in code. Physical labour is frowned upon.

Is it possible for a shorter code to exist written in assembly or parallel language(s) ?

@steenbergh I don't know... pressing one big button vs 10 keystrokes? I'll go with the button

@RaisingAgent  Your proposal has scalability issues. Try doing it for 10.000 computers four times a week.

@RaisingAgent Unfortunately is not always on the front :P

@RaisingAgent real men use the switch that's right on the PSU

(smashes computer with sledgehammer)...hunh...puny switch... :-)

Pretty sure toggling a switch would at least count as 1 bit (or 0.125 bytes, if you prefer)

@RaisingAgent: and how do you press the big button when the box is on another continent?

@ccpizza: You use an ICBM. Which, incidentally, also includes pressing a big button.

@Cruncher The one to switch from 230 V to that weird American 120 V? Works once only...

x86 machine code, Lenovo Z510, DOS COM or Bootloader, 7 bytes
BITS 16

mov ax, (1 << 13) | (7 << 10)
mov dx, 1804h
out dx, ax

Assembled into B8 00 3C BA 04 18 EF
I'm exploiting "You are allowed to write code that only works in a specific environment/OS, if you wish" to the ultimate level: this will only work on Lenovo Z5101.
This writes SLP_TYPa << 10 | SLP_EN to the PM1a_CNT ACPI register, I dumped this values from the ACPI tables months ago for an answer about shutdown (where I give a bit of context to the code above).
This can be run either under DOS as a COM (just write the binary data into a file and change extension to "com") or as a bootloader.
For the latter write the standard signature and beware of the issues with modern firmware.

1 Not strictly true, any system that happens to have the same ACPI configuration will also shutdown.

Upvoted because of the limited platform.

Ha! Somebody beat Dennis!

If you're going with the 7-byte count, you should call this a machine code submission rather than an assembly solution. The assembly submission is 63 bytes.

@Jakob You are right!

You look like the right person to answer this question: https://stackoverflow.com/questions/2019463/shutdown-computer-in-ms-dos-using-acpi (I failed miserably at it, had to delete my "answer" out of shame.)

@Prof.Falken That question is quite old, any particular reason you would like to see it answered? I'm asking just because as it is right now it doesn't seems worth answering unless you can find some value in doing that.

@MargaretBloom, no, not in particular - just as some kind of hobby. I have a thing for old and weird stuff, and combinations of old and new. DOS + ACPI hits just that note with me. Didn't mean to take your time, have a good day. :-) Looking at it holistically, answering that question may well represent an opportunity cost with a  net negative. I.e. you might have better stuff to do...

@Prof.Falken More than "better" I'd say mandatory stuff do to :P Like everyone else. Well, if I can find the time I'll be glad to answer that question and ping you back :)

GRUB shell, 4 bytes
Golfed
halt

Command: halt --no-apm
The command halts the computer. If the --no-apm option is specified, no APM BIOS call is performed. Otherwise, the computer is shut down using APM.

Bonus
Here is a proof that GRUB shell is indeed Turning-complete (see comments):

grub shell is not a "programming language" - it's not Turing complete

@Alnitak really? Even though you can load lua as a module? But note this code also works in bash.

@Alnitak, what makes you think so ? It features a rather advanced built-in scripting language, which has a syntax quite similar to that of GNU Bash and other Bourne shell derivatives and supports variables, conditional constructs, functions and more, so obviously, it is Turning-complete, by any measure.

OK, I'll take that back - I didn't find that stuff when I looked

@abligh It doesn't work in bash since the bash version doesn't actually power off the machine without the -p

When it cannot display a spinner it is obviously not Turning-complete

@J_F_B_M ha ha :)

@J_F_B_M what about those spinners which go like: _  \  | / _  | \ | ... etc

In Bash it's the same command.

65C02 machine code, 1 byte
STP instruction (0xDB):
STP stops the clock input of the 65C02, effectively shutting down the 65C02 until a hardware reset occurs (i.e. the RES pin goes low). This puts the 65C02 into a low power state. This is useful for applications (circuits) that require low power consumption, but STP is rarely seen otherwise.
(Source: http://www.6502.org/tutorials/65c02opcodes.html)
xxd dump:
00000000: db                                       .

Noice. I was an Apple II hacker back in the day and didn't even remember this opcode.

Yeah, after writing a 65c816 emulator with more features and saw this challenge I knew what to do :P
Also, looks like this is the only 1 byte answer so far! \o/

Matlab, 21 Bytes
system('shutdown -s')

I haven't tried this (closing all programs to do a restart in the middle of the day isn't really tempting), but it should work.. This works...
I'll add a short explanation later, my laptop is currently off.

"I'll add a short explanation later, my laptop is currently off." <- The danger of a shutdown challenge

Axaxaxaxa, well, restarting your computer every once in a while can't be bad :)

Does ruin your uptime, though

Why submit this as MATLAB, instead of submitting shutdown -s as shell?

Because for me, shell is either something I find on the beach, or a gas station.

MATLAB, 11 bytes
!shutdown/p

Somewhat similar to Stewie Griffin's approach. However, MATLAB has way shorter ways of invoking system commands; in this case, ! is used. Windows does not need .exe for command names, so that's left out as well. The / option is still supported (I'm running Windows 10), and negates the need for the space. Alternatives are:
system shutdown/p % 17 bytes; uses so-called 'command' syntax.
dos shutdown/p    % 14 bytes; the 'dos' command can be used just as well.

SmileBASIC, 14 11 6 bytes
OPTION

Triggers a crash causing the 3DS to restart.
I hope this counts.
Works in the most recent version.

I thought this had been patched... Please include a version number.

It has been patched in version 3.5, which hasn't been released outside of Japan yet.

@12Me21 Sure it counts. Nice choice of environment.

If only REBOOT from SBv2 counted as a valid answer.

Bash, 7 6 bytes
init 0

Assuming that the program is run as root.

Indeed, powering off the machine is required. Thus you need 'halt -p' as a valid answer

This editing massacre :)

@P.Ktinos: poweroff is a single word, although slightly more letters.

@ccpizza Right, but the typical scoring criteria is byte count

Also, init 6 would restart the machine, but not sure that would completely count as "turning off."

Python 2, 29 bytes
import os;os.system('init 0')

Works on Linux systems and needs root privileges.
For Windows, 33 bytes
import os;os.system('shutdown/p')

Someone else posted the Linux shell version.

Ah ok, my bad..

Commodore 64, 11 bytes
0 sys64738

This is from the BASIC prompt. Or...
Commodore 64, 6502 assembly, 3 bytes (assembled), 16 bytes (source)
*=8000
JMP $FCE2

I think that using the Commodore 64's direct input mode from BASIC with sys64738 will use zero bytes as there is no program or anything else to store; You are using screen RAM but that RAM will already be filled with spaces, so you're just replacing those spaces with text.

The source code takes up space. Just because it doesn't reserve space on the target machine doesn't mean it takes up 0 bytes. Otherwise the answer would be ``.

I agree with @wizzwizz4 but even with the line number and space isn't your submission 10 bytes? Or are you counting the newline too?

You don't need the space between the 0 and the sys64738, you can replace the sys with the shortcut form sY, and I don't count the trailing newline in program length.  However, I don't think your code meets the requirements: the code at 64738 does a soft reset, not a poweroff.

I used the PRINT FRE() function to determine the number of bytes used. Even if I obfuscate the BASIC 2.0 keywords, the FRE() function will still return the same number of bytes, and missing out the space between the 0 and the keyword will still produce the same result as Commodore BASIC adds in a space after the line number for presentation purposes.

Does not power off.

I once spilled beer on my Commodore 64, that powered it off permanently. Does this count?

Java, 101 98 62 42 bytes
()->{Runtime.getRuntime().exec("init 0");}

As @Snowman pointed out, the question didn't specify if a full program was needed, so this should still be acceptable.

It's shorter to replace class with interface as that allows you to omit public from main.

You can use a method, since the question did not specify the submission must be a full program: void f()throws Exception{Runtime.getRuntime().exec("shutdown/s");}

Wouldn't the Linux version be a bit shorter?

()->{Runtime.getRuntime().exec("init 0");} or tentatively ()->Runtime.getRuntime().exec("init 0") (can't check at the moment). It's a lambda implementing a custom void, no-args-throwing interface.

This should be labeled as a Linux-specific answer, e.g. "Java on LInux".

C++, 51 40 bytes
-11 bytes thanks to Ingve!
#include<os>
int main(){OS::shutdown();}

Only works in IncludeOS (v0.10.0-rc.1)
Test:
$ pwd
/home/simon/IncludeOS/examples/demo_service

$ cat service.cpp
#include<os>
int main(){OS::shutdown();}

$ mkdir build && cd build && cmake .. && make && cd ..
[...]

$ boot build/IncludeOS_example
[...]
================================================================================
================================================================================
 IncludeOS v0.10.0-rc.1-9-g151a2b9
 +--> Running [ IncludeOS minimal example ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

$

Now i am curious about IncludeOS

@KarlNapf Alfred held a great presentation at CppCon 2016 about IncludeOS: https://www.youtube.com/watch?v=t4etEwG2_LY if you want to know more :-)

You don't need to use void Service::start, int main works in IncludeOS as well.

AppleScript, 30 bytes
tell app "Finder" to shut down

Does exactly what it says: tells Finder to shut the computer off.

TI-Nspire CX CAS, 3 bytes
" "+" "

summing two empty strings.
On an older version of the calculator, this would crash the device and cause it to reboot (there's no way to shutdown a device without reboot apart from physical button combinations).
Video by Adriweb

Isn't that 7 bytes?

http://meta.codegolf.stackexchange.com/a/4764/62824 @RomanGräf

Sounds convincing to me.

AutoHotkey, 11 10 Bytes
Saved a byte thanks to Gurupad Mamadapur
Shutdown,9

AHK Supports a Shutdown command by default. The 9 is a flag, consisting of Shutdown=1 + PowerDown=8.

AHK is mysterious.

Do you need the space after the comma?

space after , is not needed. Try testing it with a different flag.
I thought this will not immediately shut down the computer, and put it in my main script which loads at startup :D Now I've to load in safe mode and solve the problem. Sigh.

Machine code (x86, boot loader) 18 bytes
b8 01 53 33 db cd 15 b8 07 53 bb 01 00 b9 03 00 cd 15

Disassembly:
mov ax, 0x5301 ; connect to real-mode APM services
xor bx, bx     ; device id 0 - APM BIOS
int 0x15       ; call APM
mov ax, 0x5307 ; set power state
mov bx, 0x0001 ; on all devices
mov cx, 0x0003 ; to Off
int 0x15       ; call APM

You can test it in Bochs' debugger with the following commands (after starting simulation, having some disk drive set up):
pb 0x7c00
c
setpmem 0x7c00 4 0x335301b8
setpmem 0x7c04 4 0xb815cddb
setpmem 0x7c08 4 0x01bb5307
setpmem 0x7c0c 4 0x0003b900
setpmem 0x7c10 2 0x15cd
c

This same machine code will also work as a DOS executable (*.COM).

C#, 79 54 53 bytes
This works on Windows.
79 bytes:
class _{static void Main(){System.Diagnostics.Process.Start("shutdown","/s");}}

53 bytes, thanks to TheLethalCoder:
_=>System.Diagnostics.Process.Start("shutdown","/s");

Note the challenge doesn't require a full program and doesn't disallow taking an input (unused of course) so you could compile to an Action<int> and do _=>System.Diagnostics.Process.Start("shutdown", "/s"); for 54 bytes.

@TheLethalCoder, updated, thanks!

You can also remove the unnecessary space.

Of course yes! Thank you, @nothrow :)

AutoIt, 11 bytes
Shutdown(1)

Shutdown function gets combination of following codes
0 = Logoff
1 = Shutdown
2 = Reboot
4 = Force
8 = Power down
16= Force if hung
32= Standby
64= Hibernate

To shutdown and power down, for example, the code would be 9 (shutdown + power down = 1 + 8 = 9).

0 (logoff) is a special case here; it does not combine with Standby or Hibernate implicitly.

OK 0 + 32 = 32

Hm, so does it always log off before going to standby/hibernation?

@Ruslan I do not  know exactly  how it works, You can refer to AutoIt user forum to receive more feedbacks:-)

Windows - NativeAPI, 212 bytes
Ok this is not really the shortest version.
But maybe interesting to some.
This will not execute on the Win32 subsystem. However it will run when executed within the context of the native api (like autochk.exe does)
Code
#define WIN32_NO_STATUS
#include <windef.h>
#include <winnt.h>
#include <ntndk.h>
NTSTATUS main() {
RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE,TRUE,FALSE,NULL);
return ZwShutdownSystem(ShutdownPowerOff);
}

Build
To build this either use the WinDDK build.exe tool (with an appropriate source file for NMAKE)
Or use these commands to compile and link:
cl /Gd /D_X86_ /showIncludes /I%DDK_INC_PATH% /I%CRT_INC_PATH% /c main.c
link /verbose /nodefaultlib /subsystem:native /machine:X86 /entry:NtProcessStartup@4 C:\WinDDK\7600.16385.1\lib\win7\i386\nt.lib C:\WinDDK\7600.16385.1\lib\win7\i386\ntdllp.lib C:\WinDDK\7600.16385.1\lib\win7\i386\BufferOverflow.lib .\main.obj

Note: This will build an x86 native executable. Change the appropriate bits if you want to build this for a different architecture.
Test
To test a native executable you have to execute it before the win32 subsystem is loaded. One common way to do it is to append the executable in the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute

Warning
If you do this however, you need to have an option to edit the registry hive of the target OS from another OS. Since you will not be able to boot the target OS anymore!
I did it on a VM where i could easily revert to a previous snapshot!

Groovy, 23 bytes
'shutdown /p'.execute()

Is the space before the slash necessary?

@steenbergh Yes, it is needed.

@GurupadMamadapur are you sure?

J, 14 bytes
2!:0'poweroff'

Works on Linux systems. 2!:0 executes the string in /bin/sh.

AppleScript, 44 bytes
tell application "Finder"
shut down
end tell

I don't know how AppleScript syntax works or anything, so if anybody knows how to shorten this, please tell.
Also, I'm doing this on my phone at school ("hacking"), so I can't test it.
At 14 fewer bytes (thanks to kindall) you can say
tell app "Finder" to shut down

Someone came up with a shorter solution (with same program) a few hours after you (but posted it instead of commenting here) http://codegolf.stackexchange.com/a/107958/62824

You can probably remove the indentation

tell app "Finder" to shut down should work, I believe (though the compilation may replace 'app' with 'application').

Most Linux shells, 15 bytes
# echo o>/p*/*ger

It could be made to be 11 bytes long, if you happen to be in the /proc directory:
# echo o>*ger

This is very straightforward (has no side effects, like unmounting filesystems or killing processes) and rather brutal.

Last time I tried wildcard expansion on redirect it generated a file with the wildcard in it despite a matching file existing.

I believe you have to add "/proc/" to your byte count

@Joshua It might be shell dependent. I actually tested it (with bash) on my computer :-)

@zeppelin Not if you are already in the directory. For all we know, it might be your $HOME - unusual, but not impossible...

@Radovan Garabík - I don't think that is really valid. This is basically the same as implying that there is an alias "p=poweroff" (which is not "impossible" too) and claiming "p" to be a valid 1 byte solution.

But you can probably make it valid at expense of just 3 bytes, like this echo o>/p*/*ger

@zeppelin True. Anyway, going for the shortest command was not my primary goal. My goal was to have a command that does what has been asked, nothing more - other answers have the OS perform various side effects, like killing processes or umounting filesystems :-)

Android shell, 9 bytes
reboot -p

Welcome to PPCG!

Clojure, 40 39 bytes
(.exec(Runtime/getRuntime)"shutdown/s")

-1 byte by changing the flag from -s to /s, which allowed me to get rid of the space.
Basically the Java answer.
Testing this was fun. Windows decided to do a firmware update on my Surface the second it shut down. Of course.
(defn shutdown []
  (.exec (Runtime/getRuntime) "shutdown -s"))

C++,  48 47 (Windows)  46 45 (Linux) bytes
Removed 1 byte thanks to Snowman
#include<cstdlib>
main(){system("shutdown/p");}

This should shutdown the system for windows
#include<cstdlib>
main(){system("poweroff");}

This should shutdown the system for Linux

do you need the ;?

@LliwTelracs Pretty sure it is "shutdown /p" and not "-p" and the space is not needed.

The semicolon is required for proper c++ syntax, using a slash allows for a shorter answer for windows but makes it no longer work for linux. Although I added the wrong character for shutdown that is shared between windows and linux

@LliwTelracs Although you can do whatever you want, I suggest abusing the 2nd rule and not caring about Linux functionality, since this is a code-golf and low amount of bytes is better.

I separated it into windows and linux power off

@P.Ktinos shutdown /p and shutdown -p are the same thing

@TrojanByAccident What he meant is that i could remove the space if i used slash for on windows, which removed 1 byte

#include<cstdlib> will shave off a byte.

Node.js, 39 bytes
Linux
require('child_process').exec('init 0')

Bash 15 bytes
shutdown -h now

alternatively : init 0

useless use of sudo

you're right given that only one user is logged in! :)

Mathematica on Windows 16 Bytes
Invoke the shell command with Run.
Run@"Shutdown/p"

Does this work on every OS, or a specific one?

@GregMartin Windows only.  Maybe a Linux guy can comment on modifying this to pass the appropriate shell command there.

I'm sure a Linux person of any gender could! Perhaps "Mathematica on Windows" is more precise in the post itself?

Lol. I use "guy" in the gender-neutral sense. http://www.slate.com/blogs/lexicon_valley/2016/02/10/the_gender_neutral_use_of_guys_is_on_the_rise_but_it_s_a_slow_rise.html

Although this term is still being debated, it is certainly the case that "guys" is not uniformly gender-neutral; and research definitely shows that gendered language has a harmful effect on STEM disciplines and the women participating in them. I believe it's important to bend over backwards to be inclusive with our language, since the gender equity problem is not solving itself.

Linux shutdown code: shutdown +0 is the traditional way to do a shutdown and power off (using the tersest representations of the flags); shutdown with no arguments will delay 60 seconds then shut down. On recent systemd-based systems you're supposed to use systemctl halt or systemctl poweroff instead, but that's more bytes so who cares about that. Note that any of these commands require root permissions (as shutting down the system could cause data loss for anyone else logged in at the time, it's an action that affects other users, so you need enough permissions to be able to do that).

AHK, 19 15 bytes
Run,Shutdown -s

Works on windows only.

TI-Basic, 3 bytes
ClrHome:"

Basically, this displays a blank screen and then waits for automatic timeout to kick in and shutdown the calculator, although you will not notice when this happens. The blank screen resembles a shutdown so you will not notice when the device actually shuts down.

PHP, 20 bytes
shell_exec("init 0");

DOS 7.1 (Windows 98) command prompt/batch, 5
WIN/P

Only works from real mode (MS-DOS command prompt).

Isn't the switch for soft-power-off /Z?

Might be. It's been a long time.

Assembly (Z80, Amstrad CPC), one byte
Amstrad CPC cannot be physically shut down by software, but system can be reset.
The following one-byte assembly program is enough to reset system:
C7    ;RST 0

It is a valid assembly program (in RAM) since no header of any kind is needed on this system.
You can install this program from BASIC e.g.:
poke 999,&c7

Then call it:
call 999

Can I haz test?
You can test at once on CPCBox - Amstrad CPC emulator in Javascript.

If using keypresses as a metric instead of program bytes, see this other answer for a shorter variant: http://codegolf.stackexchange.com/a/108248/38578

R, 20 19 bytes
shell("shutdown/s")

Previous answer :
system("shutdown/s")

shell("shutdown/s")? (19 bytes)

@djhurio well done ! Thanks !

Lisp, 38 bytes
(trivial-shell:shell-command "init 0")

Which dialect of Lisp does this work in?

Alternative Python on Linux + SysRQ, 47 42 bytes:
open("/proc/sysrq-trigger","w").write("o")

Can be  run either from python -c or from script, and requires root privileges to write to the file. The idea isn't python-specific. Writing to that file on Linux can be done in any other way - bash, perl, ruby , etc.
Note that this isn't a graceful shutdown, so expect that there is potential for data to be lost. See the Wikipedia article for more info on sysrq keys.

open("/proc/sysrq-trigger","w").write("o") saves a few bytes.

EthOS Shell - 1 byte
Just type the letter r to reboot, i.e.:
r

Python 3, 53 bytes
import subprocess
subprocess.call(["shutdown", "/s"])

This does give a window and shutdown warning.  If you wanted to shut it down immediately then you would use "/p".
You could also call the function from the USER library but this is a longer solution than the submitted version.

Would os.system('shutdown\s') not work? I don't want to try it right now in case it does work :)

@Farhan.K No. It tries to find s inside the shutdown directory. (Windows 10)

@wizzwizz4 Sorry I meant os.system('shutdown/s')

JScript, 53 bytes
new ActiveXObject('WScript.Shell').Run("shutdown /s")

JScript is Microsoft's implementation of JavaScript. Run with wscript scriptname.js.

VBScript, 46 bytes
CreateObject("WScript.Shell").Run "shutdown /s"

Run with wscript scriptname.js.

Amstrad CPC Basic, 7 keypresses.
Amstrad CPC cannot be physically shut down by software, but system can be reset with this BASIC call:
call 0

How it works
General info
At the beginning of memory (either RAM or ROM, both are prepared for this), there is a table for Z80 RST instruction. These instructions, related to Z80 interrupt handling, are also used (even on machines other than Amstrad CPC, like TI-81) for other tricks because one-byte long assembly instruction is enough to reach any of the 8 entries.
On the Amstrad CPC they are used to space-efficiently call code in ROM, RAM, expansion RAM/ROM, see BIOS Function Summary - CPCWiki or ref page 8+.  This is used extensively to make RAM-based indirections that allow easily calling ROM routines from RAM (even from BASIC, like call &bd19 that waits for screen refresh) and also, by changing them, modifying system behavior even though system is in ROM (like changing how text is displayed, or even redirecting it to printer by changing two bytes of RAM). See BB00 and following in BIOS Function Summary - CPCWiki or Firmware Guide
Specific use
Entry zero jumps to a ROM-base routine that performs full machine reset.  The simplest way to call it from BASIC it call 0.
Variant
If you insist on a program that can be run rather than a direct command, it takes 8 keypresses:
1call 0

Then you can run.
Can I haz test?
You can test at once on CPCBox - Amstrad CPC emulator in Javascript.

Commodore 128 (from native mode), 6 characters including user response and return
GO64

You will then be prompted with:
ARE YOU SURE?

Press Y and enter. This shuts down the C128 native mode (I know it doesn't power off the computer, but that's as close as I can get).

Perl 5 (on a unix-like OS), 6 bytes
`halt`

Requires you to be root.

Machine code (x86 boot loader), 2 bytes
fa f4

Disassembly
cli ; disable all maskable interrupts
hlt ; stop the processor until an interrupt or hard reset happens

The HLT instruction causes the CPU to stop execution and enter low-power mode, until any interrupt (maskable or NMI) or hard reset happens. This doesn't power off the whole system, but the original IBM PC didn't have any way to power off without the user mechanically pressing the switch. Also, if there happens an NMI, and its handler returns, the program will resume and execute arbitrary code which happens after f4. This is unlikely though, since NMI usually signals about hardware faults.
This same code will work as a DOS .COM program.

IIRC, this could be used to hang Win9x, where the DOS box had an IOPL of 3

Jelly, 25 bytes
It makes use of the undocumented monad ŒV, which takes a list, concatenates it and evaluates it using Python's eval.
“WƒuUḤøMŒƁEḄV#ẆṄⱮṁƬṅȯV»ŒV

The compressed string translates to import os;os.system("poweroff") so it only works on Linux (with root). The following code was used for compressing.
Compress().dictionary('import')
          .string(' os;os.')
          .dictionary('system')
          .string('("')
          .dictionary('power')
          .dictionary('off')
          .string('")').go()

By changing the poweroff it can be extended to other systems (but power and off are in the dictionary so this will probably be the shortest). For example, following 33-byte version worked on a Mac.
“¡Ṁ\\meṾṭ£ȧ+⁾⁸}ḶṠȯƇọṣỴ\\Ḃ⁴8ġṢṾ»ŒV

AppleScript (45 bytes)
tell application "System Events" to shut down

That's considerably more verbose than telling app "Finder" to shut down.

shortC, 10 bytes
A$shutdown

Explanation/ungolfed:
A           main function
 $          execute system command
  shutdown  shutdown

Vimscript (Linux Bash) 8 bytes
:!init 0

Vimscript (Windows CMD) 12 bytes
:!shutdown/p

Vimscript (Windows PowerShell) 15 bytes
:!Stop-Computer

Two dots : are required for the vim command, and the '!' redirects the command to the shell runing behind. You may require some extra permissions for this to work.

ARM Thumb machine code, Nintendo DS,  30 bytes
05 48 05 49 00 23 02 88 12 0a fc d2 01 80 43 80
09 0c 40 23 f7 e7 c0 01 00 04 02 88 02 80

Thumb function. Runs at an address that is 2 byte aligned, 4 byte unaligned, on the ARM7. The ARM9 cannot access these registers.
This version follows the spec by writing the two halfwords separately, like the code in libnds. Known to work on DeSuMME (it will log it in the console menu) and melonDS, and should work on hardware.
Assembler source:
    .syntax unified
    .arch armv4t
    .thumb

    // Force misalignment to align PC load
    // Not part of function
    .p2align 2,0
    .hword 0
    // Begin code
    // void shutdown(void);
    .thumb_func
    .globl shutdown
shutdown:
    // Load address of SPI register
    ldr     r0, REG_SPICNT
    // Load packed SPI commands
    ldr     r1, SPI_COMMANDS
    // Set SPIDATA to select PM_CONTROL_REG
    movs    r3, #0x00
.Lloop:
    // Wait for REG_SPICNT & SPI_BUSY to clear
    ldrh    r2, [r0]
    // Test bit 7 by shifting into carry flag
    lsrs    r2, r2, #8
    bcs     .Lloop
    // Store the low 16 bits of the command to REG_SPICNT
    strh    r1, [r0]
    // Store data to REG_SPIDATA
    strh    r3, [r0, #2]
    // Shift in the next SPI command
    lsrs    r1, r1, #16
    // Set SPIDATA to PM_SYSTEM_PWR
    movs    r3, #0x40
    // Run again with the new commands
    // Then spin again until the SPI powers off the system.
    b       .Lloop

REG_SPICNT:
    // Address of ARM7 IO register
    .word   0x040001c0
    // Two packed halfwords
SPI_COMMANDS:
    // Start a command on the Power Management device,
    // read a byte to select the register
    // SPI_ENABLE | SPI_BAUD_1MHz | SPI_BYTE_MODE | SPI_CONTINUOUS | SPI_DEVICE_POWER
    .hword  0x8802
    // Finish the command on the Power Management device,
    // read a byte to run the action.
    // SPI_ENABLE | SPI_BAUD_1MHz | SPI_BYTE_MODE | SPI_DEVICE_POWER
    .hword  0x8002

ARM Thumb machine code function, Nintendo DS, unsafe, 28 bytes
03 48 04 49 02 88 12 0a fc d2 01 60 02 49 f9 e7
c0 01 00 04 02 88 00 00 02 80 40 00

This function runs at a 4 byte aligned address on the ARM7.
This cheats 2 bytes by writing to SPICNT and SPIDATA at the same time in a full word write, something that has not yet been confirmed to work on hardware. It does not work on DeSuMME, but this might just be an emulator bug.
I am including this because it uses different code.
Assembler source:
    .syntax unified
    .arch armv4t
    .thumb

    // Force 4 byte alignment
    .p2align 2,0
    // Begin code
    .thumb_func
    .globl shutdown
shutdown:
    // address of SPI register
    ldr     r0, REG_SPICNT
    // Set SPI register bank
    ldr     r1, SPI_SELECT_PM_CONTROL_REG
.Lloop:
    // Wait for REG_SPICNT & SPI_BUSY to clear
    ldrh    r2, [r0]
    // Test bit 7 by shifting into carry flag
    lsrs    r2, #8
    bcs     .Lloop
    // Store to both SPICNT and SPIDATA
    str     r1, [r0]
    // Send SPI command
    ldr     r1, SPI_SEND_PM_SYSTEM_PWR
    // Loop again with the new value.
    b       .Lloop
    .p2align 2,0
REG_SPICNT:
    .word   0x040001c0
    // SPICNT = SPI_ENABLE | SPI_CONTINUOUS | SPI_BAUD_1MHz | SPI_DEVICE_POWER
    // SPIDATA = PM_CONTROL_REG
SPI_SELECT_PM_CONTROL_REG:
    // Combined halfwords
    .hword  0x8802
    .hword  0x0000
    // SPICNT = SPI_ENABLE | SPI_BAUD_1MHz | SPI_DEVICE_POWER
    // SPIDATA = PM_SYSTEM_PWR
SPI_SEND_PM_SYSTEM_PWR:
    // Combined halfwords
    .hword  0x8002
    .hword  0x0040

AWK, 39 bytes
#!/bin/awk -f
BEGIN{"poweroff"|getline}

Assumes running on Linux and that AWK is located at /bin/awk and that the poweroff command is in the users path.
Since it uses the BEGIN block, no input is necessary.  It simply pipes the output of the poweroff command into getline which it precedes to ignore.
Should work for Windows users provided they are in an environment similar to Cygwin.

You don't need to provide the shebang; just add 3 bytes for the flag in your title (something like ### AWK, 39 bytes + 3 (\ -f`)`

Do you really have to use poweroff? Wouldn't init 0 or halt -p work?

@wizzwizz4 The request was for a program, so to make a standalone program requires the #! and the -f.  If I just wanted a script I would leave out that line entirely since: awk 'BEGIN{"poweroff"|getline}' works just fine. That would save me 13 bytes or so, but I wouldn't consider it a program. Just me being pedantic I guess. :)

@statox You are very probably right.  I can't actually run those commands on my work machine, so I was writing from memory.  As I recall on my machines init 0 often stops the kernel but does not turn off the machine, and I didn't recall halt -p.  So I could save 1 or 2 bytes using those commands.  I know this is code-golf, but I mostly write these to make sure that AWK is represented in the solutions. :)

@RobertBenson I can't test it right now but given the bash answer I think you can save some bits. Indeed that's nice to have answer with awk that's not the first language which comes in mind when we think about codegolf :)

@statox I know this is beyond the requirements, but poweroff often doesn't require root access, whereas the other options do.  I'm not sure why it doesn't. Maybe I'll re-write this to show the various options, but I should be getting back to working right now :p

@RobertBenson I didn't know about these differences of rights, that's good to know!

@RobertBenson On this site, you're allowed to specify command line arguments used to run the program. So, for example, you'd run the script using /path/to/awk -f filename; that takes 3 bytes more than usual. However, I realise that the -f is only so a file can be provided, so you can completely miss out that line entirely like other AWK programs on the site do. It's not being lazy; it's losing every byte you can.

C, macOS, 18 bytes
main(){reboot(8);}

This is not a proper shutdown. Usual caveats apply. On my MacBook Air, this resulted in a black screen with a spinning indicator, then a shutdown after a few seconds.
x64 Assembly, macOS, 11 bytes (untested)
From disassembling the reboot function in libSystem:
movl    $0x2000037, %eax   # b8 37 00 00 02
pushq   $0x08              # 6a 08
popq    %r10               # 41 5a
syscall                    # 0f 05

AutoIt (windows), 11 bytes:
Shutdown(1)

Python, 53 bytes
import subprocess
subprocess.call(["shutdown", "/s"])

Pretty simple code but can do some damage if you haven't saved anything.
Breakdown
import subprocess

This imports the subprocess module that comes with Python that can be used across the script.
subprocess.call(["shutdown", "/s"])

subprocess.call runs a process as if you pressed Win + R. It requires a list of strings that will be joined with a space between them and executes it on the PC's shell.

Instead of import subprocess you could do from subprocess import* this way you don't spend as many bytes on the next line camping the subprocess module.

Perl 5.x (on CentOS Linux), 27 bytes
system("shutdown -h now");

Make system call to shutdown in Linux to halt (-h) now.
Changing -h to -r will shutdown then reboot Linux.

VBA (32-Bit, Windows Only), 72 Bytes
An anonymous VBE immediate function that calls the declared windows function ExitWindowsEx from user32.dll.
To be clear, this requires a 32-Bit version of MS Office, not a 32-Bit version of Windows
Declared Function
Declare Sub ExitWindowsEx Lib"user32"(ByVal A&,ByVal B&)

Anonymous VBE immediate window function
ExitWindowsEx 1,0

Burlesque - 22 bytes
"cmd"{"shutdown /s"}ex

Obviously you can not try this online.
On linux you can probably get away with "shutdown"ex if your distro offers the shutdown util.

UEFI Shell - 16 bytes
reset -s
In ASCII it would be 8 bytes but since UEFI uses UCS-16, every character takes up 2 bytes.

05AB1E (legacy) prior to commit June 4th, 2018, 10 bytes
’À…„‹/p’.E

Try it online without the .E.
Explanation:
In the commit of June 4th, 2018, the builtin .E has been changed from run_as_Bash_code to run_as_Python_code. So this only works prior to this commit.
’À…„‹/p’    # Push dictionary string "shutdown/p"
        .E  # Run it as Bash code

05AB1E, 25 bytes
’£Ø os;os.‚«('À…„‹/p')’.E

Try it online without the .E.
Explanation:
The .E builtin is eval_in_Python in the current version of 05AB1E.
’£Ø os;os.‚«('À…„‹/p')’    # Push dictionary string "import os;os.system('shutdown/p')"
                       .E  # Evaluate as Python code

See this 05AB1E tips of mine (section How to use the dictionary?) to understand why ’À…„‹/p’ is "shutdown/p" and ’£Ø os;os.‚«('À…„‹/p')’ is "import os;os.system('shutdown/p')".
Note: Both work only on Windows. Could be modified to also work on other OS, i.e. "init 0".E and ’£Ø os;os.‚«('„‡ƒŸ')’.E for Linux.

authors: Bob Jarvis - Слава Україні


text:
Guide the Alphabet
Guide the Alphabet
Given an array of directions, where the directions are defined as follows:
NW  N  NE
W   .   E
SW  S  SE

Or as indexes (you may use these indices for directions instead of the strings above):
0 1 2
3 . 4
5 6 7

You may choose either format, supporting both is not required by the challenge. Generate the corresponding alphabet String that represents the drawn path, starting with A. The number of directions will never exceed 25, meaning that it can never go past Z, so you don't have to handle this scenario. No other input formats will be accepted unless you can explain why these formats do not work due to a language limitation. This is easier to explain using a verbosely worked out example.

So, lets look at a quick example:
[E,SE,N,S,S,S,NW,W,N] or [4,7,1,6,6,6,0,3,1]

Always start with A.
A

Go East to B.
A-B

Go South East to C.
A-B
   \
    C

Go North to D.
A-B D
   \|
    C

Go back South to E, overwriting C.
A-B D
   \|
    E

Continue South for 2 cycles to both F and G.
A-B D
   \|
    E
    |
    F
    |
    G

Go North West to H.
A-B D
   \|
    E
    |
  H F
   \|
    G

Go West to I.
A-B D
   \|
    E
    |
I-H F
   \|
    G

End to the North at point J.
A-B D
   \|
J   E
|   |
I-H F
   \|
    G

The final value you would return is by reading the final graph left to right, top to bottom:
ABD
JE
IHF
G

Resulting in:
ABDJEIHFG

This is code-golf, lowest byte-count wins.

Related

Can we take as input  7 distinct pair of values instead of your proposed values. for example instead of 0 we get [-1 -1] or for 1 we get [-1 0]?

@rahnema1 no, the input is as described.

Can we return an array of chars instead of a string

Is it possible that you can return a test case where the values end up to the left of A such that A won't be the first result printed?

Can we assume that the path will never go above or left of the A?

@titus no, that's possible. [NW] does this.

is lowercase output allowed?

@edc65 lower vs upper doesn't matter.

MATL, 64 58 57 50 46 40 37 36 35 30 bytes
O'!":<TUV '59-G)hYsIH$6#u64+c!

Try it at MATL Online
Explanation
O           % Push the number 0 to the stack
'!":<TUV '  % String literal
59-         % Converts this string literal into [-26 -25 -1 1 25 26 27 -27]. These
            % are deltas for the linear indexes into the matrix corresponding to each
            % of the directions. Note that the -27 is at the end since a 0 index wraps
            % around to the end
i)          % Grab the input and use it to index into the delta array
h           % Horizontally concatenate this with the 0 (our starting point)
Ys          % Take the cumulative sum to get the absolute linear index (location) of
            % each successive letter
IH$6#u      % Find the index of the last (sorted) occurrence of each location
64+         % Add 64 to this index to create ASCII codes
c!          % Convert to character, transpose, and display

Oh wow! I thought Mendo did this! Nice :). Usually he wins my matrix questions, good to see someone else using this language. I'm trying to lear nit too.

JavaScript (ES6), 108 107 94 87 bytes
Saved a whopping 13 bytes, thanks to Titus!
Saved 7 more bytes, thanks to edc65!

let f =

a=>[i=9,...a].map(d=>r[p+=(d+=d>3)*9-d%3*8-28]=(++i).toString(36),r=[],p=646)&&r.join``

console.log(f([4,7,1,6,6,6,0,3,1]));

How it works
The formula (d += d > 3) * 9 - d % 3 * 8 - 28 translates the directions 0..7 into the following offsets:
0   1   2       -28 -27 -26
3   x   4  -->   -1  x   +1
5   6   7       +26 +27 +28

We use these offsets to move the pointer p into the one-dimensional array r and write the letters at the resulting positions.
We iterate on [i = 9, ...a] rather than just a in order to insert the starting letter 'a'. Because we initialize i to 9 at the same time, we introduce a special offset of 54 (the result of the above formula for d = 9). After the first iteration, p equals 646 + 54 = 700, which leaves just enough space to support up to 25 moves to North-West: 25 * -28 = -700. That's why p is initialized to 646.
Then we just have to join the array to get our final string. Undefined values in between letters are simply ignored by join().

d+=d>3,p+=d*9-d%3*8-28 saves 11 bytes.

@Titus Thanks, nice spot! (I can now initialize i in the array definition, saving 2 more bytes)

As OP specified that lowercase is allowed, maybe you can save 7 bytes starting from 9 and using (++i).toString(36) (still not trying to understand your math, but it seems to work)

@edc65 Damn right. Thanks!

Octave, 145 138 131 123 105 103 90 87 85 bytes
@(a){[~,k]=unique(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1),'rows');[k'+64 '']}{2}

Try It Online
Thanks to Suever 2 bytes saved!
Previous answer 103 bytes:
@(a)[nonzeros(accumarray(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1)+30,65:nnz(++a)+65,[],@max)')' '']

Try It Online!
First try 145 byts
@(a){[x y]=find(~impad(1,1,1));c=cumsum([0 0;([y x]-2)(++a,:)]);c=c-min(c)+1;n=nnz(a);[nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' '']}{5}

Some Explanations
@(a){
    [x y]=find([1 0 1]|[1;0;1]);                            %generate 2d coordinates corresponding to 1d input indices
    XY = [y x]-2;
    c=cumsum([0 0;XY(++a,:)]);                              %cumulative sum of coordinates to find position of characters
    c=c-min(c)+1;n=nnz(a);
    [nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' ''] %using sparse matrix to place characters at specified positions
    }{5}

I believe that since you need the image package part of your bytecount has to be loading the image package pkg load image

Thanks,no need to load if the package is properly installed you can test it in Octave Online

I believe that's only because Octave Online calls pkg load * at the beginning. ideone.com may be a better choice

package should be installed this way pkg install -auto image-1.0.0.tar.gz so can it load automatically Please see the manual

Ok then maybe it's fine. I was just going off of what I had seen before here.

I think the third output (~) for unique is unnecessary, right?

@Suever OK Thanks 2 bytes saved!

MATLAB, 87 85 bytes
saved 2 bytes thanks to Luis Mendo
function a=f(s);i='()*BD\]^'-67;[~,a]=unique([0 cumsum(i(s+1))],'last');a=[a'+64,''];

'%&''?AYZ['-64 nice trick... actually 66 bytes if you rewrite in octave

PHP, 93 bytes
Operating on a single array like Kodos Johnson´s answer.
But this has so many more ideas that I posted on my own.
for($r=[$c=A];""<$d=$argv[++$i];)$r[$p+=($d+=$d>3)*9-$d%3*8-28]=++$c;ksort($r);echo join($r);

takes numbers from command line arguments. Run with -nr.
moving the cursor
initial calculation:
$d+=$d>3;           // if $d>3, add 1
$p+= ($d/3-1|0)*26  // add/subtract 26 for line change
    +$d%3-1;        // add/substract 1 for column change

golfing:
$d+=$d>3;$p+=($d/3-1|0)*27+$d%3-1;          // +0: multiple of 3 instead of 26
$d+=$d>3;$p+=($d/3|0)*27-27+$d%3-1;         // +1: distribute `line-1`
$d+=$d>3;$p+=($d/3)*27-$d%3/3*27-27+$d%3-1; // +8: distribute `|0`
$d+=$d>3;$p+=$d*9-$d%3*9-27+$d%3-1;         // -8: `/3*27` -> `*9`
$d+=$d>3;$p+=$d*9-$d%3*8-28;                // -7: combine duplicates

merging the assignments doesn´t save anything, but kind of improves readability:
for(init;input loop;$p=$d...)$d+=$d>3;
for(init;input loop;)$p=($d+=$d>3)...;

breakdown
for($r=[$c=A];                  // init result, init letter
    ""<$d=$argv[++$i];)         // loop through command line arguments
    $r[
        $p+=($d+=$d>3)*9-$d%3*8-28  // move cursor
    ]=++$c;                         // increment letter, plot
ksort($r);                      // sort result by index
echo join($r);                  // print result

Python 2, 180 178 176 bytes
def f(d,a=[[""]*26 for _ in[1]*26],x=0,y=0,j=66):
 a[0][0]="A"
 for i in d:y+=(i>4)-(i<3);x+=(`i`in'247')-(`i`in'035');a[y][x]=chr(j);j+=1
 return"".join("".join(i)for i in a)

PHP, 121 bytes
$r[0]=chr(65);for(;($n=$argv[1][$i])!=null;)$r[$c+=[-27,-26,-25,-1,1,25,26,27][$n]]=chr($i+++66);ksort($r);echo join($r);

This runs in the command line with the -r flag and takes a char array (string) of indices as an argument.

You can save 5 easy bytes with ""<$n=$argv[1][$i] instead of ($n=$argv[1][$i])!=null

R, 160 bytes
a=scan()
e=f=26
x=matrix(0,51,51)
x[e,f]="A"
for(i in a){g=function(q)grepl(q,i)
T=T+1
f=f-g("N")+g("S")
e=e-g("W")+g("E")
x[e,f]=LETTERS[T]}
cat(x[x>0],sep="")

source: Stack Exchange

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

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

sort: votes


text:
Count spelling errors in text; minimize the number of spelling errors in your code
Write a program or function that takes two inputs:

A text message
The dictionary of English language, as it appears in this Github file (containing about 60000 words)

and outputs the number of spelling errors in the message (see below for definition and test cases).
You can receive the dictionary as a parameter to your function, as a pre-defined file that your program expects to find, as hard-coded data in your code, or in any other sensible manner.

Your code should itself look like a text message, with a minimal number of spelling errors. So, you will calculate the score of your code by feeding it to itself as input.
The winner is code that has the lowest score (minimal possible score is 0). If there are several answers with the same score, the winner is decided by code size (in characters). If two answers are still tied, the winner is the earlier one.

If required, you can assume the input message to be ASCII (bytes 32...126) with newlines encoded in a conventional manner (1 byte "10" or 2 bytes "13 10"), and non-empty. However, if your code has non-ASCII characters, it should also support non-ASCII input (so it can calculate its own score).
Characters are subdivided into the following classes:

Letters a...z and A...Z
Whitespace (defined here as either the space character or the newline character)
Punctuation . , ; : ! ?

Sentence-ending . ! ?

Garbage (all the rest)

A word is defined as a sequence of letters, which is maximal (i.e. neither preceded nor followed by a letter).
A sentence is defined as a maximal sequence of characters that are not sentence-ending.
A character is a spelling error if it violates any of the spelling rules:

A letter must belong to a dictionary word (or, in other words: each word of length N that doesn't appear in the dictionary counts as N spelling errors)
The first character in a sentence, ignoring any initial whitespace characters, must be an uppercase letter
All letters must be lowercase, except those specified by the previous rule
A punctuation character is only allowed after a letter or garbage
A newline character is only allowed after a sentence-ending character
Whitespace characters are not allowed in the beginning of the message and after whitespace characters
There should be no garbage (or, in other words: each garbage character counts is a spelling error)

In addition, the last sentence must be either empty or consist of exactly one newline character (i.e. the message should end with a sentence-ending character and an optional newline - let's call it rule 8).
Test cases (below each character is a rule that it violates; after => is the required answer):
Here is my 1st test case!!
           711           4                => 4

main(){puts("Hello World!");}
2   777    883     3     77 78            => 12

  This message starts with two spaces
66                                   8    => 3

What ? No apostrophe's??
     4              71 4                  => 4

  Extra   whitespace   is   BAD!
66      661111111111 66   66333           => 21

Several
lines?
Must be used only to separate sentences.
                                          => 1 (first linebreak is en error: rule 5)

"Come here," he said.
73         7                              => 3 (sentence starts with '"', not 'C')

I was expecting a bunch of loopholes, but you've seemed to cover them all.  +1 from me.

I think SPL is the winner here.

.Gertrude is even better. Commands are arbitrary sentences, only word count and average word length matter.

I thought "Applescript" when I saw this. Don't have a Mac, though.

I think the second test case has two errors: the H and W are wrong because of rule 3, not rule 2. And it would be nice to have some test cases covering the less intuitive aspects of the definition of sentence. E.g. in "Come here," he said. the C should be lower-case because it isn't the first character in the sentence. (IMO that's an error in the definition of sentence; it might be worth deleting the question before anyone answers so that you can sandbox and see whether anyone picks any more holes).

Shouldn't the fourth testcase be 21 instead of 17?

@PeterTaylor I don't want the rules to become too complicated. Your test case is fine; I added it to my post.

@smls That was a bug in counting. I don't have a solution to this challenge, so was counting stuff manually.

@anatolyg Why is the word whitespace full of 1s? What am I missing?

@Masterzagh Rule 1 says "a letter must belong to a dictionary word", and "whitespace" isn't in the dictionary.

@ETHproductions So that rule means that for every group of letters that doesn't form a dictionary word you count group length errors? I just got really confused by the rule.

@Masterzagh Yes. I have updated the post to clarify this.

Oh, this is going to be fun. Here's my first line: Def check message, words out errors? (Sadly DEF isn't a word...)

Since lenguage can easily reach score 0, do other language reach score 0 without so long code?

Surprised nobody tried this in inform 7 yet

Perl 6, 134 spelling errors
my token punctuation {<[.,;:!?]>}
my \text = slurp; my \mistakes=[]; for split /\.|\!|\?/, text { for .trim.match: :g, /<:letter>+/ -> \word { (append mistakes, .comb when none words slurp pi given lc word) or (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./) }}
append mistakes, comb / <after \s | <punctuation>> <punctuation> | <!before <punctuation> | <:letter> | \s> . | <!after \.|\!|\?> \n | [<before ^> | <after \s>] \s /, text; say mistakes.Numeric

With extra whitespace for readability:
my token punctuation {<[.,;:!?]>}
my \text = slurp;
my \mistakes=[];
for split /\.|\!|\?/, text {
    for .trim.match: :g, /<:letter>+/ -> \word {
        (append mistakes, .comb when none words slurp pi given lc word)
        or
        (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./)
    }
}
append mistakes, comb /
  <after \s | <punctuation>> <punctuation>
  | <!before <punctuation> | <:letter> | \s> .
  | <!after \.|\!|\?> \n
  | [<before ^> | <after \s>] \s
/, text;
say mistakes.Numeric

Notes:

Expects the dictionary in a file called 3.14159265358979 in the current working directory.
The only inspired part is the line
append mistakes, .comb when none words slurp pi given lc word,
the rest is pretty bad. But maybe it can at least serve as a baseline for better solutions... :)

The most readable perl code ever

Python 3, 287 spelling errors
    import re
    def function(message):file = open("dictionary", "r");dictionary = file.read().split();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);return sum(len(word) if word.lower() not in dictionary else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\n') != 1)

Try it online!
Definitely not the best, but I gave it a solid shot, I think!
Here it is in an actually readable format. Assumes there is a file called "dictionary" (no extension) in the cwd.

import re
def function(message):
    file = open("dictionary", "r")
    dictionary = file.read().split()
    words = re.findall("[a-zA-Z]+", message)
    sentences = re.findall("[^.!?]+", message)
    errors = 0
    errors += sum(len(word) if word.lower() not in dictionary else 0 for word in words)
    errors += sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)
    errors += sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)
    errors += len(re.findall("[\s.,;:!?][.,;:!?]", message))
    errors += len(re.findall("[^.!?]\n", message))
    errors += len(re.findall("^\s", message))
    errors += len(re.findall("\s\s", message))
    errors += len(re.findall("[^a-zA-Z\s.,;:!?]", message))
    errors += int(not sentences[-1] and count(sentences[-1], '\n') != 1)
    return errors

I don't think this works all of the time; it seemed to output the wrong value for the second test case?

Python, 32 spelling errors
import re;be = open('be').read().split();exec(''.join(chr(be.index(it)) for it in 'aboriginal abominable aborting aborting abolishing abominate abominable abbreviated abetting abbreviated abominates aboriginals aborigines abortionist abortion abdicating abdication abets abortions aborigine aborted abolitionists aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolishing abdominal abound abhorrent abdominal abnormally abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborigines aborted abominates aboriginals abortion abdicating aborting abortionist aboriginal abdicating abominations abominable aboriginals abdicating abortions aborigine aborted abolitionists abdication abbreviated abominates abominably abbreviated abortions aborigine aborted abolitionists abduct abominations aborigine abortions abominable aborted abdicating abdication abbreviated aboriginals aborigine abortion abbreviated abominates aboriginals abbreviated abolition abominable abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abortions aborigine aborted abolitionists abbreviated abominates aboriginals abbreviated abortions aborigine aborted abolitionists aborting abdication abdomen aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abolishing abominations aborigines abominated abolishing abdicating abdication abbreviated abolishing aboriginals abolitionists abbreviated aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen aborting abortionist aboriginal abdicating aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abduction abet abodes abdication abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abode aborting abduct abdomens abets abet abbreviates abhorred abodes aboard abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abode aboriginals abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abolish abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abode aborting abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abolishing abdominal abound abhorrent abdominal abnormally abode aborting abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominates aboriginals abortion abdicating aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abbreviated abolishing aboriginals abolitionists abbreviated abolitionist aborigine abortionist aboriginals abortion abdicating aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abdomens abbreviated abdicates abode aboriginals abdicates abdication abbreviated abbreviates abetting abbreviated abduction abdication abdication'.split()))

Takes in input from standard in and outputs to standard out. This requires a dictionary in a file called be the same directory as the code.
I took the Python answer from GotCubes and encoded each character as an index into the dictionary, interpreted as an ASCII code point.
Here's the code that I used to generate my code:
be=open("be").read().split()
code="""message = input();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);print(sum(len(word) if word.lower() not in be else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\\n') != 1))"""
words=" ".join(be[ord(c)] for c in code)
print(f"""import re;be=open('be').read().split();exec(''.join(chr(be.index(it))for it in '{words}'.split()))""")

You can definitely lower the score even more, but I will try that when it's not past midnight in my time zone.

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

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


text:
Press any key to continue
Your task is to create a program that will display the following text, wait for the user to press a key (it is okay to ignore keys like ctrl, alt, caps lock, etc., as long as keys like letters, numbers, symbols, and enter are not ignored), and then terminate the program:
Press any key to continue...

Trailing newlines are allowed. The program must exit immediately after a key is pressed. Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.).

The prompt must be exactly as shown above, unless a trailing newline cannot be avoided.

This is code-golf, so the shortest answer in bytes wins. This is also my first code-golf question, so I apologize if I do not know the rules on PPCG.

Is the output text case sensitive? Would WinBatch PAUSE be a valid answer (ellipsis is spread from ... to . . .)?

Also, you should stick your proposed challenges in the sandbox first so you can get feedback and flatten out the edge cases / loopholes.

I'm curious whether (for example) an empty C++ program is valid. Solves the task if ran in certain environments.

@TuukkaX It would not be valid.

Also I'd suggest waiting for a week or 2 before accepting any answer

I agree with @KritixiLithos ... This challenge is code-golf, and the 89-byte Processing solution is not the shortest answer.

@JungHwanMin In fact it is the most verbose of all the answers :/

Most language's pause functions are probably insensitive to keys like Caps-Lock or Control (pressed on its own). Maybe you should clarify if the program is allowed not to notice those keys

@JungHwanMin It has been changed to the MATL answer, which is the shortest (valid) answer as yet.

You should wait for a few weeks before accepting an answer, as countless others have advised you (yet you've chosen to ignore their advice)

Also, I think you should state that you should wait for a character to be typed rather than a key to be pressed, as most solutions will rely on something along the lines of getch(), which doesn't take into account control characters.

@JungHwanMin I agree with others. Please wait to accept a solution until entries have stopped rolling in. I really don't enjoy riding the Reputation Roller Coaster

Should I just take this question down?

@ckjbgames No, why? Just wait some days before accepting an answer definitively. And edit the challeng text to include the information that control keys can be missed by the program

Keys like Alt, Ctrl, Shift are called modifier keys. What you probably want is to allow ignoring modifier keys (but not require it) and to require to react to all non-modifier keys.

You probably should mention "space" key specially because it doesn't seem to fall into any listed category.

SmallBasic, 18 17 bytes

Version 2.0

17 bytes
TextWindow.Show()

Version 1.0

18 bytes
TextWindow.Pause()

Couldn't you also just do TextWindow.Show()? Based on this site that should have the same effect.

Batch, 46 bytes
@echo Press any key to continue...
@pause>nul

Because pause's output contains a space before each ..

Nice redirect. Could you also send the output to, say, x? Then a file x would be created that holds the text Press any key to continue . . .. Saves 2 bytes, but I'm not sure if that goes against this challenge or any standard loopholes.

I'm on choice.exe-free system since a while, but I have a feeling @choice /n /m Press any key to continue... was also possible some decades ago.

Choice has default values as J and N, so the program would only go on when  J or N are pressed if I remember correctly.

@geisterfurz007 Also, the default value is localized. For example, to me choice is equivalent to choice /c SN (for sim (yes) and não (no) in Portuguese).

Ah, you are right, @geisterfurz007. Now I remember how silly looked my batch files having the entire alphabet enumerated. Ok, then this was a dead idea.

HTML + JavaScript (ES6), 36 + 25 = 61 bytes
You can't really exit a JavaScript program, so clearing the webpage is the best I can think of.

onkeyup=_=>a.innerHTML=''
<a id=a>Press any key to continue...

HTML + JavaScript (ES6), 33 + 28 = 61 bytes
Alternate solution suggested by @LarsW that redirects to about:blank.

onkeyup=_=>location='about:blank'
Press any key to continue...

HTML/JavaScript, 60 bytes
Another awesome solution by @Ismael Miguel that doesn't use standalone JS. 1 byte saved!

<html onkeyup=this.innerHTML=''>Press any key to continue...

HTML + JavaScript (ES6), 26 + 28 = 54 bytes
Yet another solution by @George Reith making use of document writes.

onkeyup=_=>document.open()
Press any key to continue...

HTML + JavaScript (ES7), 23 + 28 = 51 bytes
Same program using the proposed ES7 bind operator:

onkeyup=::document.open
Press any key to continue...

As most of these solutions are not my own, do a courtesy and vote them up in the comments!

Perhaps a redirect to about:blank?

36 + 25 is 61 or am I missing something?

@LarsW That would add more bytes

@ckjbgames yeah, but it would exit the 'program' in a better way, IMO

@LarsW Still, this is code golf, so we save bytes :)

@LarsW, ckjbgames Well, what are the chances? You never know until you write it! ;)

@darrylyeo It turn out that the two snippets are the same length. :)

<html onkeyup=this.innerHTML=''>Press any key to continue... <-- 60 bytes. Try it on https://jsfiddle.net/xhb69401/ (it works with both <html> and <body>)

Shorter way to clear the document and doesn't need anchor. onkeyup=_=>document.open() with  Press any key to continue... for a grand total of 54 bytes.

Brilliant! You're all blowing my own solution out of the water.

Also with the es-next proposed bind operator it could be reduced to onkeyup=::document.open.

MATL, 35 bytes
'Press any key to continue...'D0$Y.

Explanation
'Press any key to continue...'      % String literal
D                                   % Display the string (has trailing newline)
0$Y.                                % Pause until the user presses any key

@LuisMendo Ah good catch

On the other hand, Y. doesn't either. Maybe the OP should clarify. Keys like Control and Caps-lock will fail in most of the solutions

@LuisMendo It is fine to miss control keys, caps lock, etc.

@LuisMendo Wouldn't your modification require an enter key? Or maybe I'm mis-remembering it

@Suever Oh, of course! Enter is required

Still the best.

@ckjbgames What about this one?

@ckjbgames And that is precisely why it is recommended to wait weeks before accepting an answer.

TI-Basic, 55 bytes
Basically, it loops until a key is pressed. Too bad lowercase letters are two bytes each in TI-Basic...
Disp "Press any","key to continuesin(
Repeat getKey
End

P.S. See the comment by @GoldenRatio for the explanation as to how this works. It's genius!

First of all, your byte count is currently off, that is actually 55 bytes (just made a program on TI-84+ and tested). Second, this technically isn't valid, because it doesn't display Press any key to continue... and instead it cuts to 15 chars plus ... Instead, preserving byte count, make it two disp commands. :Disp "Press any (don't forget : in your code, it counts) and Disp "key to continuesin( (The sin forces a ... in 1 byte to make up for the new line and disp, and this saves a space between any and key)

Beat me to this, first language I thought of.

Thanks for the tip @GoldenRatio, I guess I was thinking getKey was 2 bytes when it's actually 1. I suppose with Text( or Output( you could fit it all on one line. But, your suggestion is better. I didn't think about using the implicit ellipsis at the end of a line. Thanks again, I'll edit that now.

Thx for updating it, and I guess using disp with a comma has a good reason finally, since it never saved bytes. I usually put them on seperate lines because of my tendency to hit the clear button :D. Also, is there any official method of how to score the size? By this I mean, should the 9 bytes I did not count for a program name count? And should the 1 byte for the start colon that cannot be deleted count? I did mark that as 0 bytes, because for finding space I'm used to subtracting 10 for program size, but maybe the colon should count.

No, basically if you make a completely empty program it counts for 0 bytes, then you start from there. That would be like counting the filename of a source file. Also, the beginning colon is just for show and is not actually a part of the program. In fact, every newline automatically shows a colon in the editor on the calculator, but again, these are just for show (try cemetech sourcecoder to see what I mean). Last, the bytecount is the same whether we split the Disp over two lines or not (but, it is not always this way).

Bash, 46 43 42 bytes
Saved 1 byte thanks to @DigitalTrauma
read -rn1 -p"Press any key to continue..."

Uses the read built-in. -r makes sure it doesn't allow the user to input escapes. -n 1 allows just one character. -p is the prompt

Doesn't continue until I hit a

@GlennRanders-Pehrson I believe that can happen if your bash does not support -n 1 . It works without hitting enter for me however (v3.2.57) and on my debain machine (v4.3.30)

Also doesn't work if I type a quote (")

I have #bash --version
GNU bash, version 4.3.46(1)-release (x86_64-pc-linux-gnu) on Ubuntu 16:04

Does work OK if I put the line in a file (anykey.sh) and run that.  Works fine too even if I remove the space between "-rn" and "1".

-rn1 saves 1 byte

Haskell, 51 50 bytes (Thanks @villou24)
main=putStr"Press any key to continue...">>getChar

Try it online!

That waits for enter. You can use getChar instead.

You can save a byte by removing the space between putStr and the string.

Let the answerer edit his own post, @ckjbgames , don't do it for him

Octave / MATLAB, 42 bytes
disp('Press any key to continue...');pause

I upvoted this answer a month ago, assuming it was optimal... But you've been outgolfed :)

Processing, 89 81 bytes
void setup(){print("Press any key to continue...");}void draw(){if(key>0)exit();}

Explanation
void setup(){print("Press any key to continue...");}

This is required since I am using more than one function in my program. Anything inside setup() gets called, in this case the string "Press any key to continue...".
if(key>0)exit();

Checks if key (key will always contain the int value of the last key pressed) is more than 0 (ie not a null byte). If the condition is satisfied, then the program exits.
void draw(){}

draw() ensures that that the program will always keep looking for a key instead of stopping once the program starts.
(That feel when a builtin in a Java-like language is still verbose...)

I don't really know Processing, but I think you should be able to replace void steup(){...} with static{...}

@Pavel Nope, doesn't work

Bash 48 44 42 bytes
read -rn1 -p"Press any key to continue..."

@mame98 Thanks for saving 4 bytes.
@RaisingAgent Thanks for saving 2 bytes.

You can improve this by adding up the flags, like read -srn1 -p".." and remove the last space in the promt quote. Also, I'm not sure if you need the 's' flag

remove the last space in the quotes _ & -s

@RaisingAgent Thanks, updated :)

QBasic (QB64), 37 (42?) bytes
Unfortunately, QBasic's built-in end-of-program prompt doesn't have the ellipsis, so we'll have to print it ourselves:
?"Press any key to continue..."
SLEEP

(SLEEP without an argument waits until a keypress.)
This code does what the question literally asks for, but it doesn't seem like it fits the spirit of the question because, of course, QBasic then displays "Press any key to continue" and waits for a keypress before returning to the IDE. Here's one that goes straight to the IDE, for +5 bytes:
?"Press any key to continue..."
SLEEP
STOP

STOP is a debugging statement. In regular QBasic, it sets a breakpoint: execution halts and we return to the IDE, but execution can be resumed again with F5. It's unclear whether that would count as the program "exiting." However, I'm using the QB64 emulator, which can't do breakpoints. Upon encountering STOP, it simply halts--returning straight to the IDE without the redundant "Press any key" message.

Oddly enough, the 'Press any key to continue' also shows up when executing a standalone QB64 exe. I tried to use LOCATE to just print the dots after it, but QBasic clears the entire bottom row when it prints this message...

Pascal, 75 65 bytes
This was tested with the Free Pascal Compiler, version 3.0.0.
It may work with TurboPascal 7 or newer.
uses Crt;begin write('Press any key to continue...');readkey;end.

Sadly, I can't replace readkey with readln since the challenge requires that any key be accepted.

I've tested this code on http://rextester.com/l/pascal_online_compiler, with and without supplying an input.
As expected, the program is terminated after 10s, since it sits waiting for a keypress that never happens.

Thanks to @manatwork for saving me 10 bytes by proving me wrong, and showing that I don't need the program _;.

Neither FreePascal nor TurboPascal requires the use of program keyword. (Actually I never met such ancient implementation that did.)

@manatwork I tried it without program and it complained. Also, I sometimes use TurboPascal. That one requires (notice: requires) the program there. If you know any place I can test where it runs without the program, I will remove it. I hate having it there. And that uses Crt;.

I don't get you. It works fine including the rextester service you linked. In my command line: http://pastebin.com/pVr9dqxd

@manatwork You're right. I know why it complained: I wrote program; instead of actually removing that bit. Thanks for alerting me to that.

Python 2, 110 bytes
import curses as c
s=c.initscr()
c.cbreak()
s.addstr(0,0,'Press any key to continue...')
while not s.getch():1

Cutting it down to 98 bytes (current Python 3): from curses import* s=initscr() raw() s.addstr('Press any key to continue...') while 0>s.getch():1

Scratch, 81 bytes

when gf clicked
say [Press any key to continue...
wait until <key [any v] pressed

(Scratchblocks link)
If you wanted it to stop the entire program when you pressed a key (including other threads) you'd have to add a stop all. If you want to get rid of the say dialog you need an empty say block (stop all works as well).
Convenient that Scratch has a builtin for this!

Ruby (2.3) (+ Batch), 52 55 54 53 46 bytes
Now 46 bytes thanks to Alexis Andersen.
Note: Tested on Windows, might not work if there is no pause command.
puts"Press any key to continue...";`pause>nul`

Explanation
Puts the required text:
puts"Press any key to continue..."

End the line:
;

Run the Batch pause command and pipe output to nul:
`pause>nul`

Hello, welcome to PPCG.  I see that you have a list of edits in the body of your submission.  While this may be customary on other sites, since anyone can see the edit history of a post, we generally leave the history of the post out of the body (aside from the strike throughs for byte counts).  This seems like a good first golf and I hope you have fun here.

@WheatWizard Thanks, should I leave the edits there or remove them?

I think that it makes for a much more readable answer if you remove them and I would personally recommend doing so.

you can shorten that by replacing system with backticks:  pause>nul  or even shorter, just use gets (also, there's no good way to include a backtick in a code block in a comment)

@AlexisAndersen doesn't gets wait for enter, and not just any key?

facepalm yes, you're right. The backticks are still valid though

I think you could consume pause's output with assignment: x=`pause` .

R, 56 bytes
cat('Press any key to continue...');keypress::keypress()

This works in Linux and OSX terminals.

Java, 127 bytes
class P{public static void main(String[]a)throws Exception{System.out.print("Press any key to continue...");System.in.read();}}

Note: the console must be set to raw mode in order for this to work.

Then I'm afraid your code should set the console so, like original.legin's Perl solution does.

@manatwork Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.) if you follow that SO link there is no OS-independent way to do this. Meaning, the answer you linked is equally as valid as this one.

SmileBASIC, 52 bytes
?"Press any key to continue...
WHILE""==INKEY$()WEND

Mathematica, 62 bytes
EventHandler["Press any key to continue...","KeyDown":>Exit[]]

Explanation
EventHandler["Press any key to continue...","KeyDown":>Exit[]]
EventHandler[                                                ]  (* Create a new EventHandler *)
             "Press any key to continue..."                     (* Print the dialog text *)
                                            "KeyDown":>Exit[]   (* When a key is pressed down, exit *)

SmileBASIC, 55 bytes
?"Press any key to continue..."@L IF INKEY$()!=""GOTO@L

Explained:
?"Press any key to continue..."  '? means PRINT
@L                               'start of loop
IF INKEY$()!="" GOTO @L          'if no key pressed goto @L

WHILE""==INKEY$()WEND is smaller

Python 3, 65 bytes
Requires the Windows version of Python.
from msvcrt import*
print("Press any key to continue...")
getch()

msvcrt.getch() doesn't wait for the enter key to be pressed like input(), it returns the first key pressed.
Python Docs for msvcrt.getch():
https://docs.python.org/3/library/msvcrt.html#msvcrt.getch
Thanks to @Fliptack for saving some bytes

This answer is invalid without an import msvcrt somewhere

As this is code-golf you should remove the comments from your code. Also, using from msvcrt import* appears to be 1 byte shorter

cool, thx @FlitTack

Python 2/3 POSIX, 85 bytes
import sys,tty
print('Press any key to continue...')
tty.setraw(1)
sys.stdin.read(1)

Node.js, 102 101 99 bytes
with(process)stdout.write('Press any key to continue...'),s=stdin,s.setRawMode(1),s.on('data',exit)

Not much gain, just 1 character shorter with with: http://pastebin.com/BhrAyq2K

@manatwork Nice one! First time with has saved me bytes (or byte)

Now you can remove the curly brackets and replace line breaks with commas for 2 more bytes.

Also if I'm not mistaken, stdout.write\Press any key to continue...`` will save 2 bytes in ES6.

@darrylyeo Commas work thats awesome thanks! Unfortunately a tagged template literal can't be used here as it actually passes in an array and process.stdout.write doesn't do implicit conversions to string (it just errors).

Nice. Yeah, I suspected that might be the case.

Shouldn't console.log be shorter?

@MatthewRoh "The prompt must be exactly as shown above, unless a trailing newline cannot be avoided." Because this doesn't add a trailing newline and console.log does I can't use it.

Wait, now they are allowing trailing newlines.

Sinclair ZX81/Timex TS1000 BASIC: Method 1 approximately 41 bytes
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 GOTO (INKEY$<>"")+VAL "2"

Method 2 approximately 38 BYTES
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 PAUSE VAL "4E4"

I prefer method 1 as on the ZX81, there is a screen flicker when PAUSE is called, and if you want long enough (providing the ZX81 doesn't overheat or crash) the pause will eventually come to an end, whereas method 1 is stuck in an infinite loop until a key is pressed, and no screen flicker.
I'll work out the correct number of bytes used later when I have the right bit of BASIC that will tell me. By the way, using VAL "x" instead of the number saves valuable RAM on a ZX81 (I think that this is the same for the ZX Spectrum as well).

Both methods will work on the Sinclair ZX Spectrum as well, the advantage being that the Spectrum has upper and lower case letters, whereas the ZX81 does not by default (and doesn't have a single quote either as a standard character).

Method 2 on the Sinclair ZX Spectrum could be condensed to 1 PRINT "Press any key to continue...": PAUSE 4e4

PAUSE 0 pauses for ever.

Yes I've not programmed in Sinclair Spectrum BASIC for so long that I forgot about that. PAUSE 0 in ZX81 BASIC does not pause forever.

Perl 5, 79 bytes
system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)

used as:
perl -e 'system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)'

No prizes of course. I'm sure some perl person will have a better way.
(89 bytes if the interpreter invocation as well needs to be included in the count)

@Pavel, he counted system in his bytecount, so I don't know what you meant with that comment.

@original.legin I think Perl won't do much better than this. A few bytes you can golf still: $|=1 isn't necessary, you have a space after print, you can drop the parenthesis around the arguments of read, you can use backticks instead of system, and finally, print returns 1, so you can use it instead of the litteral 1 in the call to read. So in the end, we get: perl -e '\stty cbreak`;read STDIN,$a,print"Press any key to continue..."'`

@Dada You can also shave off 2 bytes with say, although I think this approach fails the "portable" requirement. The best portable solution I can find is perl -MTerm::ReadKey -E'say"Press any key to continue...";ReadMode 3;ReadKey' (52 bytes + 16 bytes for -MTerm::ReadKey<space>). Be careful, this will screw up your terminal unless you restore the read mode at the end with ReadMode 1.

@ThisSuitIsBlackNot Indeed, I didn't see that requirement about portability. About say, I tend not to use it anymore (I agree mostly with this meta post). Now back to a short code, IO::Prompt will be shorter than Term::ReadKey (40 + 13 = 53 bytes) : perl -MIO::Prompt -e 'prompt"Press any key to continue... ",-1'. And as it happens, it's even shorter than what I suggested in my previous comment.

@Dada I can see both sides of the -E argument. The last time I checked, though, J B's answer had been uncontested for four years, so that's what I've followed. Maybe I need to revisit it again. As for IO::Prompt, good find! Although it doesn't work on my Strawberry 5.20.2 on Windows, while Term::ReadKey does.

I don't think this works with perl on my windows box.  Was it meant to be portable?

8th, 47 bytes
"Press any key to continue..." . cr con:key bye

This program ignores keys like ctrl, alt, caps lock. Quits with keys like letters, numbers, symbols, and enter.
Explanation
"Press any key to continue..." . cr \ Print message
con:key                             \ Wait for key input from console
bye                                 \ Quit program

On Windows only you can save 3 bytes omitting cr

PHP, 73 bytes
echo"Press any key to continue...";$h=fopen("php://stdin","r");fgets($h);

Run it in the PHP interactive shell (php -a)

“The program must exit immediately after a key is pressed.” – This waits until Enter or blackout…

C#, 101 bytes
using C=System.Console;class P{static void Main(){C.Write("Press any key to continue...");C.Read();}}

Tested on Linux, should run on any system having the .NET libraries and the Common Language Runtime.
Ungolfed program:
using C = System.Console; // creating a shorter alias for the System.Console class

class P
{
    static void Main()
    {
        C.Write("Press any key to continue...");    // prints the message
        C.Read();   // waits for key press
    }
}

CTRL, ALT, SHIFT are ignored. The pressed key will be echoed on screen if printable.
Echo can be disabled by replacing C.Read() with C.ReadKey(0<1) at the cost of 6 more bytes.

C#, 29 bytes
class P{static void Main(){}}

Not sure if this is considered valid because it prints:

Press any key to continue . . .

But there is a Batch answer that prints this as well.

Forth (gforth), 39 bytes
." Press any key to continue..."key bye

(Yes, there is already an 8th solution but this is shorter)

SmallBasic 17 bytes
TextWindow.Show()

I had this answer before the accepted answer added it to their answer by the way. (To avoid unjust flags)

Comments are not for extended discussion; this conversation has been moved to chat.

HTML + Javascript, 58 bytes

<html onkeyup=document.open('')>Press any key to continue.

MATLAB, 41 bytes
or it could be Octave, 40 bytes.
This is quite similar to the obvious approach posted by Suever, but is one glorious byte shorter.
disp 'Press any key to continue...'
pause

or in Octave:
disp"Press any key to continue..."
pause

A little known and little used feature of both MATLAB and Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces).
For instance:
nnz PPCG
ans = 4

size PPCG
ans = 1  4

str2num 12
ans = 12

Now, if the input is a word with multiple words, then we need the quotation marks, so disp('Press any key to continue...') is reduced to disp 'Press any key to continue...', saving one byte. Instead of the semicolon separating the disp call and the pause, we now separate them using a linefeed.

C64Mini/C64 BASIC (also VIC-20 BASIC) 52 tokenized BASIC bytes
 0?"PRESS ANY KEY TO CONTINUE...":POKE198,0:WAIT198,1

The ? is short-hand for PRINT; thereafter, POKE 198,0 will clear the keyboard buffer, whilst WAIT 198,1 will wait until the keyboard buffer has something in it again.
Because the keyboard buffer isn't cleared whatever key is struck when the program executes is displayed. You may tidy this up with another 4 BASIC tokens by adding :GETA$ to the end of line zero.
The screen shot shows the VIC-20 in action, which by default only has a 22 column display source