text:
What's the time, chap?
I honestly cannot believe that this is not a question yet on Code Golf, but....
Print the local time (with a.m. or p.m.) as a string to the console, preceded by "It's ".
Example:
Run code....

Output:
It's 12:32p.m.

Shortest code wins.
Code away!
Leaderboard

var QUESTION_ID=57552,OVERRIDE_USER=42854;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Are builtins allowed?

@UndefinedFunction - yes, you can use builtins

What is the output format? Does it matter?

@mbomb007 - see edit

No, I mean, should it be yyyy-MM-dd hh:mm:ss UTC or does that date format not matter?

@mbomb007 - it should be hh:mm a.m./p.m.

in what way is this [tag:kolmogorov-complexity]

I really wanted to put up an answer that prints It's beer o'clock, but I resisted.

I expect a Pyth or CodeJam answer of no more than one byte at some point!

Can we use 12:32 PM or 12:32PM? Instead of 12:32p.m.?

Is it 02:32 or 2:32 if it's less than 10:00?

@StewieGriffin - no. You must use p.m or a.m. For your second comment: it doesn't matter. Whichever you want

Can we use 24 hour notation?  e.g.  23:00p.m.

@LukStorms - no. It should be like 11:00p.m. not 23p.m. However, if many people already answered with 24 hour notation already, I might have to change the rule. Anyhow, that's no the case I think.

This is one of the rare questions where a CJam answer is not on the top.

Bash, 39 33 bytes
date "+It's %I:%M%P."|sed s/m/.m/

Wasted a bunch of chars because the spec requires a.m. or p.m. while date outputs am or pm. Thanks to @DigitalTrauma for saving 6 bytes!
This might not be very portable. It works on Ubuntu 15.04.
A solution that uses essentially the same method in Ruby, which is surprisingly the exact same length:
Ruby, 39 bytes
$><<`date "+It's %I:%M%P"`[0..-3]+'.m.'

%P gives me uppercase AM or PM. I'm on a mac if it makes a difference.

@flodel Works On My Machine™. On Ubuntu 15.04, %P gives lowercase, and %p gives uppercase (which is a bit... unintuitive).

GNU date (on Linux et al.) and *BSD date (where OSX is one BSD variant) have wildly different options and behaviors when you venture outside of the feature set specified by POSIX.  So perhaps this answer should specifically mention Bash on Linux. (That goes for sed too; but this particular invocation is firmly within the safe and portable feature set.)

On my machine (zsh or bash on Linux) it prints "It's 04:17." when the time is 16:17. No "a.m." or "p.m."

echo -e "It's $(date +%I:%M%P)\b.m." - instead of sed uses backspace. Doesn't look like a separate answer to me. Also I don't have any am/pm but I think it's because of locale.

@aragaer That's actually 36 bytes. You can shave off a char by using backticks instead of $(), but it's still longer than my version. Interesting idea though!

Aww, used flawed method to count characters... My bad.

You can save a byte by using Bash + rs: date "+It's %I:%M%P."|rs.py m/.m (yes, this is a shameless plug to get an answer with rs that I didn't write).

I find on my Debian system, that %P (or %p) gives the abbreviation with dots in, if LC_TIME is set to es_CR.  So I've got LC_ALL=es_CR date "+It's %-I:%M%p" for 34, but if you can count the locale as part of the environment, then it goes down to 21 bytes.  (Found using for i in $(locale -a); do LC_ALL=$i date "+$i: It's %-I:%M%P" | fgrep .m.; done, of course).

AppleScript, 198
Because AppleScript.  Because why not:
set AppleScript's text item delimiters to {":"," "}
set d to (current date)'s time string's every text item
"It's "&d's item 1&":"&d's item 2&string id ((d's item 4's first character's id)+32)&".m."

That was painful.

AppleScript is the new Java.

PHP, 35 33 bytes
Using the wrong tool for the job!
It's <?=trim(date('h:ia'),m)?>.m.

It simply removes the m at the end of am or pm, to allow to add the dots. The date comes as 00:00am, and with trim it becomes 00:00a.

Old answer (PHP 5.4+ only):
It's <?=date('h:i'),date(a)[0]?>.m.

This works because you can de-reference a value returned from a function. This isn't possible in PHP5.3 or older.

Ah, clever! You beat my php answer

@DankMemes It took me quite a while. And lots of experimenting.

You used a string literal without quotes. Is it OK to use those without the @ operator  and assume people will run it with error_reporting(0)?

@DankMemes You can indirectly assume that error reporting is disabled. Here's a good read: http://meta.codegolf.stackexchange.com/a/1655/14732

Visual Basic 6 / VBA, 42 41 bytes
MsgBox"It's "&Format(Now,"h:mma/p")&".m."

Using MsgBox, as VB6 does not have a console (unless you intercept the linking, link as a console executable, use some Windows API hacks, and do some other dodgy stuff).

Why don't you just replace m by .m.?
i.e. Debug.Print Replace(Format(Now,"hh:mm am/pm"),"m",".m.")

Nice @toothbrush, I sort of expected this to be a one-byte solution in CJam ;)

Julia, 74 54 43 bytes
print(strftime("It's %I:%M%P\b.m.",time()))

You can try it online!
The time() function returns the current time. When passed to strftime with the format %I:%M%P, this results in HH:MMam/pm, where the hours are per a 12-hour clock. We back up one character with \b to remove the m, leaving a trailing a or p, then tack .m. onto the end.
Saved 31 bytes thanks to Glen O!

Might I suggest this? print("It's ",strftime("%r%P",time())[[1:5,12]],".m.") - uses %P to add the lowercase am/pm, to avoid the comparison and the split command.

No problems regarding the help. And don't talk yourself down - you do fine. I just get enjoyment out of trying to squeeze every last byte out of the code. In this case, I just figured that trying to bypass the split command and the conditional statement would be beneficial, and then went looking at the functions you used. I probably wouldn't have found strftime myself (I'd have tried to extract the time directly from time())

@GlenO If you get enjoyment out of squeezing every last byte out of code, PPCG is certainly the right place for you!

Incidentally, I've found a way to squeeze a few more bytes out: print(strftime("It's %I:%M%P",time())[1:11],".m.")

Actually, even better: print(strftime("It's %I:%M%P\b.m.",time()))

@GlenO That's a great solution, thanks!

R, 68 ,59 62 60 55
cat("It's",sub("m",".m",format(Sys.time(),"%I:%M%P.")))

(Thanks to @Alex.A. and @flodel for the comments) Takes the current system time (Sys.time()), formats it correctly using %I:%M%P combination, adds a dot at the end, and replaces the m with .m..

MATLAB, 59 bytes
disp(sprintf('It''s%s\b.m.',lower(datestr(now,'HH:MMam'))))

It's 5:38p.m.

If it's allowed to have a whitespace between time and a.m./p.m., then it could be as low as 52 bytes:
disp(sprintf('It''s%s\b.m.',lower(datestr(now,16))))

It's 5:39 p.m.

I think the output must be 05:38p.m.

According to OP's comment, the leading zero doesn't matter.

You're right. Here, have my upvote!

Nice! Didn't know I could use \b like that... You need an extra space btw.

Perl 5.10+, 58 62 bytes
localtime=~/(..)(:..)/;say"It's ",$1%12||12,$2,$1>11?p:a,".m."

Must be run with the -M5.010 command line flag to get say.
I didn't account for a couple of edge cases in my original solution (namely, 00:** and 12:**); fixed at a cost of 4 additional bytes.
How it works
In scalar context, localtime returns a string like this:
Sat Sep 12 03:13:22 2015

The minutes field is already zero-padded, which saves some bytes (in list context, localtime returns numbers instead of strings, so you have to pad them yourself).
Here it is ungolfed:
localtime=~/(..)(:..)/;  # Store hour in $1 and minutes in $2
say"It's ",              # Print "It's " followed by...
   $1%12||12,            # hour in 12-hour format
   $2,                   # minutes
   $1>11?p:a,            # "p" if hour > 11, otherwise "a"
   ".m."'                # ".m."

Perl 5.14+, 57 bytes
(Just for fun, since it stretches the rules a bit.)
say"It's ",(strftime"%l:%M%P",localtime)=~s/m/.m./r

51 bytes + 6 bytes for -MPOSIX. Must also be run with the -M5.010 command line flag to get say.
This solution is dependent on your locale, so will not work on all systems. It also uses the POSIX module, which might be stretching the definition of a "built-in", even though it is a core module.
Perl 5.14+ is required for the non-destructive r modifier to the substitution operator. An equivalent solution that works on 5.10+ is:
$_=strftime"%l:%M%P",localtime;chop;say"It's $_.m."

This is also 57 bytes (51 bytes + 6 bytes for -MPOSIX).

Pyth, 38 36 bytes
s["It's "|%J.d6K12K\:.d7?gJK\p\a".m.

Saved 2 bytes thanks to @Jakube!

@Sp3000 On the online interpreter or locally?

@Sp3000 I think I know the issue. It's giving the time of the location of the Pyth server, and I'm not handling midnight correctly. Hold on...

@Sp3000 Fixed!!!

You're almost beating my PHP answer and Doorknob's Bash answer!

Mathematica 49 90 92 90 84 bytes
-6 bytes thanks to user202729
The solution is straightforward, but a bit wordy, in Mathematica.
(d=DateString)@{"It's ","Hour12",":","Minute"}<>(d@"AMPM"/."AM"->"a.m."/."PM"->"p.m .")

(Although this post is quite old) StringReplace can be eliminated, save 6 bytes. (d=DateString)@{"It's ","Hour12",":","Minute"}<>d@"AMPM"/."AM"->"a.m."/."PM"->"p.m."

Haskell, 135 bytes
import Data.Time.Format
import Data.Time.LocalTime
main=getZonedTime>>=putStr.(++".m.").init.formatTime defaultTimeLocale"It's %I:%M%P"

I found a much more amusing main that's five bytes longer:
getZonedTime>>=putStr.formatTime(TimeLocale[][]("a","p")""""""""[])"It's %I:%M%P.m."

Or 66 bytes on Unix:
import System.Cmd;main=system"date \"+It's %I:%M%P.\"|sed s/m/.m/"

Perl 5, 74 bytes
A small showcase of how the variables are evaluated from right to left.
($s,$m,$h)=localtime;printf"It's %d:%02d%s.m.",$h<13?$h:$h%12,$m,$h<12?a:p

Using POSIX: 80 bytes
use POSIX;$_=strftime"It's %I:%Mx.m.",@_=localtime;$x=$_[1]<13?a:p;s/x/$x/;print

Using POSIX with time locale dependence & switches :  54 bytes (48 + 6)
$_=strftime"It's %I:%M%P",localtime;s/m/.m./;say

Test
$ export LC_TIME="en_DK.UTF-8"
$ perl -MPOSIX -M5.01 whatsthetimechap.pl
It's 3:09p.m.

You can save some bytes on your POSIX solutions by using -MPOSIX instead of use POSIX;, dropping the parens in your call to strftime, and replacing print with say (-M5.010 is free). Which brings your last solution down to 54 bytes!

Thanks. I used your advice for the shortest POSIX solution.

You still have to count -MPOSIX (6 bytes), but you can save 2 bytes by dropping the parentheses: $_=strftime"It's %I:%M%P",localtime;. That gives 54 bytes total, which is still better than my 57-byte POSIX solution. Well done!

Heh, thanks again for rescuing a few bytes.

CJam, 40 bytes
"It's "et3=CmdCe|\'p'a?':et4=s2Ue[@".m."

Try it online in the CJam interpreter.
How it works
"It's " e# Push that string.
et3=    e# Select the fourth element of the date/time array (hours).
Cmd     e# Push quotient and remainder of the hour divided by 12.
Ce|     e# Logical OR with 12 to map 0 to 12.
\'p'a?  e# Select 'p' if the quotient is 1 and 'a' if it is 0.
':      e# Push that character.
et4=    e# Select the fifth element of the date/time array (minutes).
s2Ue[   e# Cast to string and left-pad with zeroes to a length of 2.
@".m."  e# Rotate 'a' or 'p' on top of the stack and push ".m.".

Locale-dependent
For browser environments that have the locale set to en-CA or any locale that outputs a 12-hour time by default:
CoffeeScript, 81 bytes
alert "It's #{(x=(new Date).toLocaleTimeString().toLowerCase())[..4]} #{x[9]}.m."

JavaScript (ES5), 90 bytes
alert("It's "+(x=(new Date).toLocaleTimeString().toLowerCase()).slice(0,5)+' '+x[9]+".m.")

Locale-independent
CoffeeScript, 113 96 bytes
alert "It's #{(h=(d=new Date).getHours())%12}:#{('0'+d.getMinutes())[-2..]} #{'ap'[+(h>11)]}.m."

Previous:
This one works in all browser environments regardless of locale. Requires Chrome 24+, Firefox 29+, IE 11+, Opera 15+ or any derivatives of such. Does not work in Safari. See Intl.DateTimeFormat.
alert "It's #{new Intl.DateTimeFormat('en',{hour:f='2-digit',minute:f}).format(new Date).toLowerCase()[..-2]}.m."

The javascript answer gave me: It's 2:59: m.m.

@Mwr247 Which locale is your browser in?

@rinkattendant6 My locale is en-US

Swift - 124 102 bytes
import Cocoa
var f=NSDateFormatter()
f.dateFormat="hh:mma"
print("It's \(f.stringFromDate(NSDate()))")

T-SQL (2012+), 67 65 bytes
SQL Server 2012 finally gave us a reasonable formatting function for dates.  I still had to muck around with the AM/PM to get the format right though.
PRINT 'It''s '+LOWER(STUFF(FORMAT(GETDATE(),'hh:mmtt.'),7,0,'.'))

In previous versions it would have needed something like this (93 bytes)
PRINT'It''s'+LOWER(STUFF(STUFF(RIGHT(CONVERT(VARCHAR,GETDATE(),109),15),6,7,''),8,0,'.'))+'.'

PHP, 49 bytes
If only it were am/pm instead of a.m./p.m....
It's <?=@preg_replace(~Ð¤ž’¢Ð,~ÛÏÑ,date(~˜Å–ž));

I used a lot of nasty bytes to save a bit of length so here's the hex:
00000000: 49 74 27 73 20 3C 3F 3D - 40 70 72 65 67 5F 72 65 |It's <?=@preg_re|
00000010: 70 6C 61 63 65 28 7E D0 - A4 9E 92 8F A2 D0 2C 7E |place(~       ,~|
00000020: DB CF D1 2C 64 61 74 65 - 28 7E 98 C5 96 9E 29 29 |   ,date(~    ))|
00000030: 3B                      -                         |;|
00000031;

Readable version:
It's <?=preg_replace("/[amp]/", "$0.", date("g:ia"));

SQL (PostgreSQL), 42 41 bytes
Another SQL variant, however this one is in a query.
select to_char(now(),'"It''s" HH:MIa.m.')

As a note either p.m. or a.m. works to get the am/pm part.  The formatting options in PostgreSQL are really quite flexible.
Thanks to @manatwork for the tip to move the it's into the format string.
SQLFiddle

So you need to adjust am/pm it manually?

@DavidArenburg, no it gets it right with either ... but I had to check it out, because it didn't seem right.  If you add + time '12:00' after the now() in SQLFiddle it should change the am/pm.

1 character shorter: select to_char(now(),'"It''s" HH:MIa.m.')

@manatwork, very nice thanks.  I wouldn't have thought of trying that.

Javascript, 103 bytes
Javascript executed from the console.
d="It's "+new Date().toLocaleTimeString();l=d.length;d.slice(0,l-6)+d.slice(-2,l-1).toLowerCase()+'.m.'

C#, 63 bytes
C# executed from the immediate window.
?"It's "+System.DateTime.Now.ToString("h:MMt").ToLower()+".m.";

Also runs as F# ;)

You don't need to calculate d.length, you could just write -n and it will calculate from the end, just an FYI. d="It's "+new Date().toLocaleTimeString();d.slice(0,-6)+d.slice(-2,-1).toLowerCase()+'.m.' 90 bytes. And you can save one byte by moving the "It's " string. And a few bytes from a little string shortcut in there. d=new Date().toLocaleTimeString();"It's "+d.slice(0,5)+d[9].toLowerCase()+'.m.' 79 bytes.

And if the answer needs to be locale-independent (as some have posted), just use toLocaleTimeString("en-US") 86 bytes.

C, 103 94 bytes
int main(){time_t r;char b[80];time(&r);strftime(b,80,"It's %I:%M %p",localtime(&r));puts(b);}

Ungolfed
int main()
{
  time_t r;
  char b[80];
  time(&r);
  strftime(b,80,"It's %I:%M %p",localtime(&r));
  puts(b);
}

PHP, 41 bytes
It's <?=strtr(date('g:ia'),['m'=>'.m.']);
First time I've played this.  Not sure if I'm supposed to update/edit the previous PHP answer (49 bytes) or just add my own...

You should always add your own. You only comment on someone's answer if you see something that can save them a few bytes. But other than that, nice answer!

By the way, you can write [m=>'.m.'], which saves 2 bytes. (Warnings can be ignored, so, don't worry about them.)

C, 154 bytes
#include <time.h>
#define l localtime(&r)
main(){time_t r=time(0);printf("It's %02i:%02i%c.m.",(l->tm_hour+11)%12+1,l->tm_min,(l->tm_hour>=12)?'p':'a');}

In contrast to the other C answer, this one uses the correct "a.m."/"p.m." format.  The other poster omitted #include <time.h> – if your compiler allows this, we get down to 136 bytes.  Which one should we count?

You're right, in fact all I got was a warning – I got it confused with an error from trying to do without time.h. Editing.

Bash, 44 characters
Pure Bash, just shell builtins, no ***utils.
printf -vt "It's %(%I:%M%P)T"
echo ${t%m}.m.

Sample run:
bash-4.3$ printf -vt "It's %(%I:%M%P)T";echo ${t%m}.m.
It's 01:04p.m.

Powershell, 49 bytes
"It's {0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d

(date).hour/23 seems to work as an index for "ap" because it rounds to 0 for hours less than 12 and 1 for 12 and above.

Should be able to golf off a few characters by instead treating the "p"/"a" as string turned into an implicit char-array -- 51 bytes -- "It's $(date -f hh:mm)$("pa"[(date).hour-lt12]).m."

Your latest "{0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d misses the It's  at the beginning. If you tack that onto the front, it's the same 49 bytes as "It's $((date -f hh:mm)+"ap"[(date).hour/23]).m."

My bad. I've fixed it. Anyway, this version is more "correct", as it only makes a single call to date

For what it's worth, I stumbled across the following while researching something else. Apparently [datetime] casts are always en-US. That means something like this "It's $(("{0:h:mmt}"-f[datetime](date)).ToLower()).m." is possible ... which, granted, is 54 bytes and longer than your current solution, but still an interesting quirk of the language.

@TimmyD Interesting, but it seems it's only casting to DateTime that's en-US, not formatting.

AutoIt, 73 bytes
Even though AutoIt is generally a verbose language, this is quite short (converts time from 24h format):
$h=@HOUR>12
ConsoleWrite("It's "&@HOUR-12*$h&":"&@MIN&($h?"p":"a")&".m.")

ß, 56 bytes
H=@HOUR>12µ€"It's "&@HOUR-12*H&":"&@MIN&H?"p.m.":"a.m.")

Python 3, 117 87 79 bytes
from datetime import*
print(datetime.now().strftime("It's %I:%M%P")[:-1]+".m.")

This gets the hours and minutes from a 12-hour clock using the format %I:%M, plus am or pm using %P. We then select everything but the last m and append .m..
Saved a few bytes thanks to Ruth Franklin!

As you're only using datetime once, it's 6 bytes shorter to use from datetime import*; h=datetime.now() ...

@RuthFranklin Thanks for the suggestion! I also found a few other ways to shorten it.

Moonscript - 56 bytes
print "It's "..(os.date'%I:%M%p'\gsub 'M','.M.')\lower!

Unfortunately the Lua standard library only implements %p for uppercase AM/PM, so I have to call the method lower.

SpecBAS - 64 bytes
PRINT "It's ";LOW$(REPLACE$(TIME$(TIME,"h:mm p$"),"M",".M."))

The built-in p$ of the time function returns AM or PM, so this then has to be formatted with REPLACE$ to change it so it has a full stop before/after that letter.
Then the time output had to be converted to lowercase.

Python 2, 75 67 66 bytes
import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower()

old version, 75 bytes
import time
t=time.strftime("%I:%M%p")
print"It's",t[:5]+t[5].lower()+".m."

old version, 75 bytes
import time
print"It's",time.strftime("%I:%M%p").lower().replace("m",".m.")

@AlexA. Not working in Python 2 time.strftime at least under windows gives "ValueError: Invalid format string"

@AlexA Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower()
It's 01:30p.m.`

MATLAB, 66 bytes
['It''s' lower(datestr(now,'HH:MMam'))];disp([ans(1:end-1),'.m.'])

Displays:
It's 2:48p.m.

Excel VBA, 33 bytes
?"It's "format(now,"h:ma/p")".m."

Related to toothbrush's VBA6 solution, but written before I saw it, so I'm allowing myself to post it here.
Most of the code is perfectly explicit: now returns a system timestamp, format forces the timestamp to the desired format, whilst It's and .m. are just text strings.
I abused/took advantage of a few things here:

Implicit concatenation : VBA assumes that when something is put next to a string that a concatenation operation is desired.
Immediate window printing : This is why I don't claim this is a complete VBA solution, as it relies on being executed from inside an immediate window. The ? replaces debug.print for Excel VBA in an immediate window. This is an obvious gain for VBA where most of the byte cost comes from descriptive/user-friendly function and method names. Toothbrush's solution for example calls Msgbox which is 5 bytes more expensive.
Format abuse : based on Dopapp's comments in this puzzle, we don't need to have double-digit hours. I'm also not forcing double-digit minutes, which might be slightly against the rules of the game, but can easily be corrected by adding an extra m between : and m, but costs 1 byte more.

I might have missed some other tricks, but I think this is about as low as Excel VBA can go. From what I can see so far, I'm pretty surprised that it's scoring so well, but a lot of the very concise languages haven't been used yet...

x86-16 machine code, IBM PC DOS, 64 62 bytes
Binary:
00000000: bf34 01b4 2ccd 218a c5d4 0c75 02b0 0ce8  .4..,.!....u....
00000010: 1400 478a c1e8 0e00 b870 0980 fd0c 7c01  ..G......p....|.
00000020: aaba 2f01 cd21 d40a 86c4 0530 30ab c349  ../..!.....00..I
00000030: 7427 7320 3030 3a30 3061 2e6d 2e24       t's 00:00a.m.$

Build and test using xxd -r with above.
Listing:
BF 0134     MOV  DI, OFFSET HH      ; DI point to hours in output string
B4 2C       MOV  AH, 2CH            ; DOS get time function
CD 21       INT  21H                ; CH = hour, CL = minute
8A C5       MOV  AL, CH             ; put hour into AL
D4 0C       AAM  12                 ; AL = AL mod 12, ZF = (AL == 0)
75 02       JNZ  NOT_12             ; is hour 0?
B0 0C       MOV  AL, 12             ; if so, make it 12
        NOT_12:
E8 0126     CALL ACONV              ; ASCII convert AL to [DI]
47          INC  DI                 ; skip ':' in output string
8A C1       MOV  AL, CL             ; put minutes into AL
E8 0126     CALL ACONV              ; ASCII convert AL to [DI]
B8 0970     MOV  AX, 0970H          ; AL = 'p', AH = 9 (DOS write string)
80 FD 0C    CMP  CH, 12             ; set up compare for 12
7C 01       JL   OUTPUT             ; is hours > 11?
AA          STOSB                   ; if so, write 'p' to output string
        OUTPUT:
BA 012F     MOV  DX, OFFSET IT      ; beginning of output string
CD 21       INT  21H                ; display output
        ACONV:
D4 0A       AAM                     ; BCD base 10 convert
86 C4       XCHG AL, AH             ; endian convert
05 3030     ADD  AX, '00'           ; ASCII convert
AB          STOSW                   ; write to output string buffer
C3          RET                     ; return to caller/DOS

        IT  DB  'It',27H,'s '
        HH  DB  '00:'
        MM  DB  '00'
        AP  DB  'a.m.$'

I had imagined this being shorter in my head when I started it, but alas.  No date "built-ins" at least!
Standalone PC DOS executable TIMECHAP.COM file.  Output to STDOUT.

05AB1E, 39 37 bytes
"It's "ža<12%>žb‚T‰J':ý„apža13@è….m.J

-2 bytes thanks to @ovs.
Try it online.
Explanation:
"It's "     # Push string "It's "
ža          # Push the current hours (24 format)
  <         # Decrease it by 1
   12%      # Modulo-12: (hours-1)%12
      >     # Increase it by 1: (hours-1)%12+1
            # (so if the hours was 0, it's now 12; the [1,11] remained the same)
žb‚         # Pair this with the current minutes
   T‰       # Get the divmod-10 of each
     J      # And join the two digits together to a single string
            # (`T‰J` is used to format the hours/minutes with a potential leading 0)
      ':ý  '# Join them together with ":" delimiter
„ap         # Push string "ap"
   ža       # Push the current hours again (24 format)
     13@    # Check if it's >= 13 (1 if truthy; 0 if falsey)
        è   # (0-based) index that into the "ap"
….m.        # Push string ".m."
J           # Join all strings on the stack together
            # (after which the result is output implicitly)

I'd never noticed before but TIO seems to cache the output in the link too, since when I clicked on your link the time was wrong until I re-ran. Guess that makes sense because for most cases the output only changes with a code change. Learn something new everyday.

@640KB Yep. It's actually pretty useful for programs that run let's say 40 seconds. When someone else visits the same link, they don't have to wait 40 seconds to see the result if someone else has already run it prior. :)

37 bytes by using (hours-1)%12+1 for calculating 12-hour hours.

APL (Dyalog Extended), 58 bytes
-6 thanks to @ovs
⎕←∊'It is '(⍕h-12×12<h)':'(⍕5⌷⎕ts),'ap'[1+12<h←4⌷⎕ts]'.m.'

Try it online!
Original:
∊'It is '((':',⍕5⌷⎕ts){⍵>12:∊(⍕(⍵-12))⍺'p'⋄∊(⍕⍵)⍺'a'}4⌷⎕ts)'.m.'

Try it online!

58 bytes as a full program without any dfns

Windows Batch, 113 bytes
@set h=%time:~0,2%&@set z=a&@if %h% gtr 11 set z=p&if %h% gtr 12 set /a h-=12
echo It's %h: =0%:%time:~3,2%%z%.m.

JavaScript (ES6), 88
Edit Missing "It's"
Edit 2 Fixed 0 instead of 12
Edit 3 Added an output statement. I was trying to be in line with other JavaScript answers that I felt ugly, but rules are rules
Test in any EcmaScript 6 compliant browser console (works in Chrome and Firefox).
alert(`It's ${1+((h=(d=new Date).getHours())+11)%12}:${d.getMinutes()+'ap'[h>11|0]}.m.`)

// With no ES6 features : 92

alert("It's "+(1+((h=(d=new Date).getHours())+11)%12)+':'+d.getMinutes()+'ap'[h>11|0]+'.m.')

This doesn't output leading 0:s if any number is below 10. F.e It's 0:9a.m.

@Jan indeed. That's not requested: see answer to @StewieGriffin's question: You must use p.m or a.m. For your second comment: it doesn't matter. Whichever you want

Talking about hours, yes. Regarding minutes, looking at another reply It should be like 11:00p.m. not 23p.m. I'd very much suspect it's required, but you could ask. Also noted another thing: It's 12:32p.m., so not 0:32p.m.

My first comment was from the console output of running your script.

@Jan Right. It's broken. Fixing it

Neat little trick with the a/p selector by the way. Nice.

I believe you need an alert (or similar output) in JavaScript for it to be considered valid by code golf conventions.

@Mwr247 right, thanks for pointing it out

BASH, 50 bytes
date +"It's %I:%M%p"|sed s/AM/a.m./|sed s/PM/p.m./

Just date and two easy seds.

Perl, 88 75 bytes
use POSIX;$d=lc strftime"%R%p",localtime;$d=~s/m/.m./;printf("It's %s",$d);

POSIX automatically exports everything, so you can shave off 13 bytes by dropping the qw(strftime).

@ThisSuitIsBlackNot Thank you! :D

Java, 182 bytes
These solutions are horrendously long. =(
Note: These print in local time, and suppresses leading zeros for the hour. java.util.Date has deprecated API.
// 183 bytes when linebreaks and indentation are removed
import java.util.Date;
class T{
  public static void main(String[]a){
    Date d=new Date();
    int h=d.getHours();
    System.out.printf("It's %d:%02d%c.m.%n",
      (h+11)%12+1,d.getMinutes(),97+h/12*15);
  }
}

Alternate solution:
// 182 bytes when linebreaks and indentation are removed
class T{
  public static void main(String[]a){
    System.out.println("It's "+new java.text.SimpleDateFormat("h:mma").format(
      new java.util.Date()).toLowerCase().replaceAll("[apm]","$0."));
  }
}

PowerShell, 61 bytes
"It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m."

My very first PowerShell experiecne // because my linux machine is in the other room.
EDITED to be culture-settings robust. Thanks to all commenters below, credit goes to @NeilD

This also depense on system setting. I don't get am or pm. (24:00 format)

Ouch. Ok I will fix it.

@TimmyD Format string t is culture-dependent and may return other characters than a or p, or an empty string for cultures that do not use am/pm designators.

@DankoDurbić Indeed you're correct. Mea culpa.

"It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m." works for me (62 bytes)

That's 61 bytes. @NeilD

Octave, 75 bytes
disp(["It's " strrep(lower(strftime("%R%p",localtime(time()))),"m",".m.")])

This shoiws: ans = .... A lot of MATLAB / Octave answers could be a lot shorter if that was legal.

@StewieGriffin Yes, that's true...

@AlexA. Of course. Thanks! :)

C# - 160 bytes
using System;class C{static void Main(string[] a){var n=DateTime.Now;int h=n.Hour,m=n.Minute;Console.Write("It's "+(h<13?h:h-12)+":"+m+(h<12?"a":"p")+".m.");}}

Hassium, 125 Bytes
func main(){print("It's "+date().hour%12+":"+date().minute);if(date().hour%12!=date().hour)print("p.m.");else print("a.m.");}

Run it (and for expanded) here

CJam, 60 58 bytes
"It's "3et=Cmd\'p'a?".m."+\_0>{}{;C}?\":"\4et=_A<{0\@}{\}?

Explanation
"It's "                                                         e# Print the string "It's ".
        et                                                      e# Push the local time to the stack.
       3  =                                                     e# Select the third item. (hours)
           C                                                    e# Push 12 to the stack.
            md                                                  e# Push the top stack item modulo the second stack item.
              \                                                 e# Swap the top two stack items.
               'p'a?                                            e# Push "p" or "a" to the stack.
                    ".m."+                                      e# Tack on ".m." to the above.
                          \                                     e# Swap the top two stack items.
                           _                                    e# Duplicate the top stack item.
                            0>                                  e# Determine if the top item is > 0.
                              {}{  }                            e# An if-then statement.
                                    ?                           e# If the top stack item is true.
                                 ;                              e# Remove the top stack item.
                                  C                             e# Push 12 to the stack.
                                     \                          e# Swap the top two stack items.
                                      ":"                       e# Push ":" to the stack.
                                         4  =                   e# Select the fourth item. (minutes)
                                          et                    e# Push the local time to the stack.
                                             _                  e# Duplicate the top stack item.
                                              A<                e# Determine if the top item is < 10.
                                                {   }{ }        e# An if-then statement.
                                                        ?       e# If the top stack item is true.
                                                 0              e# Push 0 to the stack.
                                                  \             e# Swap the top two stack items.
                                                   @            e# Rotate the top three stack items.
                                                      \         e# Swap the top two stack items.

You can test it online, here.

TI-BASIC, 58 bytes
getTimeStr(12
"It's "+sub(Ans,1,length(Ans)-2)+sub("ap",2-not(inString(Ans,"P")),1)+".m.

An ugly hack to build the correct output from the built-in getTimeStr(, which gives something like "8:59 PM". (By the way, the 12 means "12-hour format".)

JavaScript (ES6), 95 bytes
x=(new Date+"").substr(16,5).split(':')
alert(`It's ${x[0]%12||12}:`+x[1]+(x[0]<12?'a':'p')+'.m.')

Octave 54 bytes
5 bytes shorter than the shortest MATLAB submission and 21 bytes shorter than the shortest Octave submission. Uses Octave's "index everywhere" functionality.
disp(['It''s ',lower(datestr(now,16))([1:5,7]),'.m.'])
It's 12:34p.m.

Bash, 32 bytes
printf "%(It's %H:%M:%S%P^H.m.)T"

Where ^H is a literal backspace character. Here's a hex dump (use xxd -r to reverse it):
0000000: 7072 696e 7466 2022 2528 4974 2773 2025  printf "%(It's %
0000010: 483a 254d 3a25 5325 5008 2e6d 2e29 5422  H:%M:%S%P..m.)T"

Thunno 2 j, 36 bytes
ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's

Try it online!
Explanation
ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's    # Full program

                              "It's   "# Step 1 (get the prefix string):
                              "It's   "#  Push the string "It's "

             kKkL⁻12%⁺,TȷḋẸ':s        '# Step 2 (get the time):
               kL                      #  Push the current hours (24-hour format)
                 ⁻                     #  Decrement it
                  12%                  #  Modulo by 12
                     ⁺                 #  Increment it
             kK       ,                #  Pair with the current minutes
                        ȷ              #  And to each one:
                       T ḋ             #   Divmod it by 10
                          Ẹ            #  Dump both onto the stack
                           ':s        '#  Push a ":" between the two pairs

ʋ.m.`apkL12®i                          # Step 3 (get the suffix string):
       kL                              #  Push the current hours again
         12®                           #  Check if it's >= 12
    `ap     i                          #  Index this into the string "ap"
ʋ.m.                                   #  Push the string ".m."

                                       # Join the stack into a string, joining
                                       # lists on the stack implicitly as well

                                       # Implicit output

Pascal, 83 B (subject to implementation characteristics)
Extended Pascal, ISO standard 10206, furnishes Pascal with some time-related routines and a data type timeStamp.
However, the specific behavior of getTimeStamp, whether it populates a timeStamp with the ”local time“, UTC, wall time or else, is implementation-defined.
Similarly the format time returns is implementation-defined, too.
For instance, it could depend on the value of the LC_TIME environment variable if the implementation says so.
It is therefore not guaranteed that the following implementation meets all task specification requirements in all ISO-compliant Pascal implementations.
program t(output);var t:timeStamp;begin getTimeStamp(t);write('It''s ',time(t))end.

Note, it is not checked that t.timeValid is true but in a real-life application it is advisable.


text:
Evaluating expressions with numerical shorthands
You work for a company that wants to make a user-friendly calculator, and thus you have been tasked with adding the ability for users to use "numerical shorthands," that is, letters that represent numerical values, such as k for 1000. Because your company wants to save money on storage in said calculators, you must minimize your code as much as possible to reduce the cost of storage.

Your Task
You are to create a function that either reads an expression as input from STDIN or takes it as a parameter and returns its evaluation or prints it to STDOUT.
Some Clarification
Let me do some definitions. First off, we have the input, which I call an expression. This can be something like the following:
x + y / z

Within this expression we have three numbers: x, y, and z, separated by operators (+ and /). These numbers are not necessarily positive integers (or even integers). What complicates things is when we have to evaluate shorthands contained within numbers. For example, with
2k15

for purposes of evaluation, we split this up into three numbers: 2, 1000 (which is k), and 15. Then, according to the rules, we combine them to obtain
2*1000 + 15 = 2015

Hopefully this makes it a bit easier to understand the following rules.
Rules
N.B. Unless specified otherwise, you can interpret the word "numbers" or its synonyms to include shorthands.

The following constitutes the numerical shorthands your function must be able to process: k, m, b, t, and e. k, m, b, and t correspond to the values 1000, 1000000, 1000000000, and 1000000000000 respectively (one thousand, one million, one billion, and one trillion). The e shorthand will always be followed by another number, n, and represents 10^n. You must allow for numerical shorthands to be present in n and present before e. For example, kek evaluates to 1000*10^1000.
For simplicity's sake, if a number has the shorthand e in it, it will only be used once.
Any number (shorthands included) before a shorthand is multiplied by it. e.g. 120kk would be evaluated as 120 * 1000 * 1000. If there is no number before it, you must assume that the number is 1 (like how you might, in mathematics, treat a variable x implicitly as 1x). e.g. e10 evaluates to 10^10. Another example: 2m2k evaluates to 2*1000000*2*1000 (nothing is added to it).
Any number (shorthands do not apply) following the last shorthand in a number containing a shorthand is added to it. e.g. 2k12 would be evaluated as 2*1000 + 12. The exception to this is if the shorthand e is used, in which case the number (shorthands included) following e will be treated as n and evaluated as 10^n (see the first rule).
Your function must be able to process the operators +, -, *, and / which are addition, subtraction, multiplication, and division respectively. It may process more, if you so desire.
Operations are evaluated according to the order of operations.
Numbers in shorthands are not only integers. 3.5b1.2 is valid and is to be evaluated as 3.5*1000000000 + 1.2 = 3500000001.2
Built-ins are not allowed, if they exist for this sort of thing. The exception that I'll add would be if your language automatically converts large numbers to scientific notation, in which case that is admissible for your output.
Shortest code in bytes wins, standard loopholes applying.

Input
The input will be an expression with each number and operator separated by spaces. Numbers may or may not contain a shorthand. A sample is shown below:
10 + 1b - 2k

Output
Your function must output the evaluation of the expression as a number. It is admissible to use scientific notation if the output would be too large to display. You must have at least three decimal places if the number is not an integer. It is admissible if you retain these decimal places if the number is an integer.
Test Cases
Input
t

Output
1000000000000

Input
1 + 4b / 10k11

Output
399561.483

Input
e2 + k2ke-1 - b12

Output
-999799912

or
-999799912.000

Input
142ek12

Output
142e1012

or
142.000e1012

Input:
1.2m5.25

Output:
1200005.25

Final Notes
This is my first challenge posted (with some help from users on the sandbox). If anything is unclear, make it known to me and I will do my best to clarify.

Good first challenge

@DigitalTrauma Thanks a lot! I look forward to seeing the answers.

I don't understand the second example. I thought the middle term was interpreted as 1000 + 2000 * 10 ^ -1, but that gave a final answer of -999998712. (Also, my interpretation doesn't seem to jive with rule 4's "last shorthand," but I'm not sure how else to understand the sequence k2k.) Can you please explain the steps in evaluating it?

@trichoplax yes, it should only be a number; good catch.

@DLosc Of course, for that term the way you'd evaluate it would be as 1000 * 2 * 1000 * 10^-1 (see rule 3). Basically, anything that isn't after the last shorthand is multiplied together. That whole input evaluates to 100 + 1000*2*1000*10^-1 - 1000000012.

Okay. That's not clear to me from the wording of rule 3: "Any number before a shorthand"--the first k there isn't before a shorthand, it's before the number 2. (And it isn't a number either, unless "shorthand" is a subset of "number.") Maybe rewording rule 3 to read more like your comment above would help.

Or, disallowing cases like k2k, since that's equivalent to 2kk anyway.

How should 2e3k be interpreted? Is that 2e3000 or is it 2e3 * 1000?

@Timwi 2e3000, judging from the last example.  e appears to have lowest precedence within each (compound) number.

@Timwi it would be the former (2e3000), see rule 1 for clarification. @DLosc you're right, I've reworded it to hopefully reduce further confusion and tried to specify that "number" includes "shorthand" where applicable.

After looking at the comments on the sandbox post, I think an example like 2m2k should be added to the discussion of rule 3. Also, it might be best to use a different term--maybe "integer"--for the literal numbers  like 123 that are not shorthands. The word "number" has about 3 different definitions here, as it stands now.

Doesn't the second test case e2 + k2ke-1 - b12 break rule 2?

@meandmycat when I say "number," (which appears to be the source of most of the confusion here -- I'll try and think of a way to make things a bit clearer), I mean each individual term that is part of the expression as a whole. a + b, for example, contains two numbers a and b. What complicates things is when you have shorthands within a number, since we then have to split said number up: 2k, for example, we evaluate as if it contained two numbers being multiplied by each other (2*1000).

Python 2, 553 bytes
import sys
a=lambda i:lambda j:j*10**i
d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)}
e='e'
o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j}
r=[e,'*','/','+','-']
x=0
y=k=b=''
z=[]
q=lambda i,j:float(i or j)
for l in ''.join(sys.argv[1:]):
 if l in d:x,y=d[l](q(x,1)*q(y,1)),b
 elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=0,b
 elif k==e:y+=l
 elif l in o:z.extend([x+q(y,0),l]);x,y=0,b
 else:y+=l
 k=l
z.append(x+q(y,0))
for m in r:
 while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])]
print repr(z[0])

This question looked a little unloved and seemed fun, so I gave it a shot. I've never done code golf before, so there's probably a lot that can be improved, but I gave it my best based on my knowledge of the language. An equivalent solution is possible in Python 3 at the cost of one extra byte: print repr(z[0]) -> print(repr(z[0])).
Usage is something along the lines of
python2 ShorthandMath.py <equation>

i.e.
python2 ShorthandMath.py e2 + k2ke-1 - b12

outputs
-999799912.0

Input for how to improve this would be much appreciated. If there is sufficient interest, I can ungolf and comment the program, but most of it pretty legible already (a concerning fact in code golf).
It should be noted that the program breaks with the example 142ek12 because that value is ludicrously large and the program overflows.
To compensate, the following is slightly longer, but can theoretically handle anything thrown at it due to use of the built in arbitrary precision library. Syntax is identical.
Python 2, 589 588 bytes (arbitrary precision)
import sys
from decimal import*
a=lambda i:lambda j:j*10**i
d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)}
e='e'
o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j}
r=[e,'*','/','+','-']
x=c=Decimal(0)
y=k=b=''
z=[]
q=lambda i,j:Decimal(float(i or j))
for l in ''.join(sys.argv[1:]):
 if l in d:x,y=d[l](q(x,1)*q(y,1)),b
 elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=c,b
 elif k==e:y+=l
 elif l in o:z.extend([x+q(y,0),l]);x,y=c,b
 else:y+=l
 k=l
z.append(x+q(y,0))
for m in r:
 while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])]
print z[0]

I'm going to say the first version should be fine and I'll get back to you if try there's anything wrong (I can't look/think too carefully right now).

@Cole Awesome, thanks. I tried it out on every example given, and it gets all of those right at least.

source: Stack Exchange

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

sort: votes


text:
Interrupt handler call serializator
The question uses C to formulate the problem, but solutions in any language can be accepted. At the end of the question you can find a pythonic version.
As part of a bigger software, we have a C function:
void wrapper(void* p);

Which is a wrapper function around the C function:
void handler(void* p);

wrapper() is triggered by an external effect (hardware interrupt, unix signal, it doesn't matter), which also provides a p as its argument. The triggering can happen after the execution of any CPU instruction, even if wrapper() or handler() is being executed. The triggering happens similarly to the interrupt requests in a cpu, or to the signal handlers in unix: after wrapper() returns, the execution continues from exactly the same CPU state as the triggering found it.
We don't know what does handler(), but we know that it doesn't interact with the triggering mechanism.
As a help, we have
void swap(void **a, void **b);

which swaps the contents of two void* pointers in a single cpu instruction.
The solution of the problem is a wrapper() function, which "serializes" handler(): it makes sure, that handler() never is called in multiple times: every new handler() will be called only after the previous returned.
Trigger can't be lost: for every wrapper(), exactly one handler() must be called. It shouldn't be called from the same wrapper() which was actually triggered, but p can't be lost.
Similar solutions in practical situations often block the triggering for a short period, here it is impossible.
If needed, malloc(), free() and NULL (==(void*)0) can be used, but out of it, no library calls. These functions are considered reentrant (if triggering happens in them, they will work correctly). Especially any direct or indirect usage of any multithreading isn't allowed.
There is no speed criteria for wrapper(), but it must be ready in a finite time. We know, that the triggering won't happen so fast to cause some hardware/stack/etc. overflow. wrapper() must handle any deep of reentrancy.
Any language can be used for the task (incl. asm or interpreted languages), but no language construction or api calls which would make the task essentially easier, as in C.
The handler() calls don't need to happen in the same order as their corresponding wrapper() was triggered.
The solution is an implementation of wrapper().
Analogous problem in Python:
Look for the signal handlers module in python (here). This what this problem is about. Essentially, we have a
def wrapper(p):
  ..the solution...

What is a wrapper around
def handler(p):
  ...we don't know what is here...

The execution of wrapper is triggered by an external event. It means, that it can happen any time, even while we are in wrapper or in handler. If the triggering event happens, wrapper will be called. After it returns, the normal program execution will continue. The task is to implement  wrapper in a such way, that handler won't run multiple times in the same moment. I.e. the next handler will be called only after the previous returned, even if the triggering happens while the wrapper(s) of  previous trigger(s) run.
No python API call or external module can be used, with the single exeception of a
def swap(a, b):

...which exchanges the values of a and b in a single instruction (equivalent of a tmp = a; a = b; b = tmp, but it does in a single moment, without a triggering would be happened).
Bonus Python problem: the internal Python functions which handles the lists, dicts, etc, they all aren't reentrant. This means, if you call mylist.append(), it is possible that the trigger will happen during the execution of the append() method. If another wrapper() or handler() try to do anything with a such list, your program will segfault and solution won't be accepted. The case is the same for every higher-level language. In short: if you use _any_ higher level language construct, i.e. list/dict/object/etc, you need to make sure that it won't be used by any other wrapper which is triggered meanwhile.
The objective win criterion:
Afaik, this is a hard problem. If anybody can find a solution, is already a big success (to me was it around a week to find one), and on my opinion, there won't be a big difference between the different results. But it is required here to have an "objective winning" criterion, and so, lets say "the shortest solution in bytes" is the winner.

Despite the tagging, I replay: any language can be used. I used only C to make the problem the possible most clearly formulated.

Welcome to Programming Puzzles and Code Golf. Challenges on this site require an objective winning criterion so that a winning submission can be unambiguously chosen.

@AlexA. Ok, I extend the question ASAP!

@AlexA. Would it be enough objective: "The winner is the solution which uses the fewest '{', '}', "? Or: "The winner is the shortest"?

Shortest code in bytes is a common scoring criterion, which would make this a code golf challenge.

After thinking a lot, I am not sure if the question passes the site criteria. To me, it was the most interesting problem I've meet in the latest years, but if it doesn't pass your topic, I am ready to remove it.

@AlexA. I extended the question with the needed objective winning criterion.

I've initiated a discussion about the possibilities of the reopening this question on the meta.

I don't know C and I have no idea what this is asking. Is there a more language agnostic way to describe the challenge?

Basically wrapper() can be called many many times (sometimes at the same time as it is already running) and wrapper() is responsible for making sure handler() is called exactly once for every time it is invoked itself - but handler() must never run concurrently and you aren't allowed to use any multithreading features.  You are allowed to dynamic memory allocation and deallocation without worrying about reentrancy issues.

@JerryJeremiah I don't get that either. Must my language have some concurrency and memory allocation features to participate?

@xnor you don't need it to design the algorithm but testing your algorithm requires being able to call wrapper multiple times simultaneously to make sure handler does not get executed simultaneously.

@xnor I am thinking on it. Jerry Jeremiah described the problem correctly.

@xnor Although the problem is formulated in C, its essence is language-independent.

I would still vote to close as "unclear what you're asking". The win condition is not specific enough for our ruleset, and the objective of the challenge is confusing as well.

@ETHproductions How about now?

The win condition is better now, but I still don't understand the goal of this challenge. Perhaps it's just me.

@ETHproductions And the problem, do you understand the problem? If yes, you can help me to construct a win criteria. If not, you can help to reformulate it to a more understable direction.

I think it's my lack of knowledge of C and CPU instructions that's holding me back here. What if you organized your explanation into a specific, numbered list of rules that a solution must follow?

Would using synchronization and a blocking queue count as a "multi-threading feature"? IMO I think this fits appropriately under code-challenge, but its winning criterion at a glance would be very subjective.

@Luminous I am thinking on to make the question easier to understand without low-level hardware-near knowledge. Usage of blocking locks isn't allowed, because the solution is a single-threaded, reentrant routine and not a multithreaded solution (usage of blocking is sensible only if there are other threads whose execution can be waited, but now there aren't). But the swap() can be used essentially as a (non-blocking) spinlock.

@ETHproductions I extended the problem description with a python syntax (and reference), how about now?

Yes, now that it has been explained entirely in terms of plain functions, I understand much better. :)

As I mentioned in meta, I don't think this question is answerable without more details on what we can assume about the CPU and memory architecture.

@PeterTaylor No, knowing that the malloc/free are reentrant and the swap() is atomic, it is enough, although it is hard. I have a solution, but it took a week of puzzling to me to find one.

Honestly, the close reason made me laugh... "unclear"? Well, it is quite subjective and say more from the close voters as from the the question.

C, 149 bytes
Note:
This seems to be a pretty controversial challenge, so I might be treading on thin ice here :)
To make things clear, as far as I understand, the OP meant for the problem to be strictly single-threaded, which simplifies matters, since invocations of wrapper() can only interleave in an all-or-nothing fashion; if that's not the case, then this solution is wrong.
The so called "interrupts" that trigger wrapper() are assumed to have the same semantics as C signals, as defined by the C standard, except that, as part of the hypothesis of the challenge, malloc() and free() can be called, and swap() can be used to access objects of type void* volatile with static storage duration, during the execution of their handler.
(notwithstanding, the golfed version invokes all kinds of UB that aren't directly relevant to this challenge.)
P B;wrapper(p){P c=malloc(8);P b=c,n=c;*c=0;c[1]=p;while(c=n){S;if(b)return*b=c;handler(c[1]);S;n=*c;free(c);}}

Compile with: gcc -c -w -m32 "-DV=volatile" "-DP=int*V*V" "-DS=swap(&b,&B)" wrapper.c.
Look below for a test program to link against.
(The calculated code size is the size of the snippet, and of the three -D... arguments, not including the quotes.)
Ungolfed
We use a queue to store pending handler() invocations.
Several queues may exist simultaneously, but at most one may be active at any given time.
When wrapper() is invoked, if a queue is already active, we add an item at the back of the queue and return immediately.
Otherwise, we start a new queue, and handle all of its items, until it empties;
during the handling of a queue item (i.e., during an invocation of handler()), we make the queue active, so that nested invocations of wrapper() don't call handler() themselves;
however, while fetching the next item, we deactivate the queue, so that nested invocations of wrapper() start their own queue, instead of modifying the one we're currently inspecting.
#include <stddef.h> /* NULL */
#include <stdlib.h> /* malloc(), free() */

void swap(void* volatile*, void* volatile*);
void handler(void* p);

/* Each queue item contains an argument, `p`, for the invocation of `handler()`,
 * and a pointer to the next item. The last item in the queue has a NULL `next`
 * pointer.
 */
struct queue_item {
    struct queue_item* volatile next;
    void* p;
};

/* Points to the last item in the currently active queue, or NULL if there is no
 * active queue.
 */
static void* volatile active_queue_back;

void wrapper(void* p) {
    struct queue_item* current;
    void* back;

    /* We allocate a new queue item for the current invocation of `handler()`.
     */
    current = malloc(sizeof(struct queue_item));
    current->next = NULL;
    current->p = p;

    /* We make the new item the back of the active queue, by assigning it to
     * `active_queue_back`, while at the same time fetching the previous value
     * of `active_queue_back`.
     */
    back = current;
    swap(&back, &active_queue_back);

    /* `back` now holds the previous value of `active_queue_back`. Since the
     * swap is atomic, no two interleaving invocations of `wrapper()` see the
     * same previous value, and no item is lost.
     */

    /* We check if there was an active queue prior to the current invocation of
     * `wrapper()`, that is, if the previous value of `active_queue_back` is not
     * NULL.
     */
    if (back != NULL) {
        /* If there was an active queue, we pass ownership over the new item
         * to the previously active queue (essentially making it active again,)
         * by linking it after the previous back of the queue. The owner of the
         * active queue is now responsible for handling, and disposing of, the
         * item, or, alternatively, for handing it over to someone further down
         * the line.
         */
        ((struct queue_item*) back)->next = current;

        /* Note that any reinvocation of `wrapper()`, following the preceeding
         * swap, will have added a queue item at the back of our newly allocated
         * one, directly or indirectly. Ownership over these items is
         * transitively passed to the owner of the active queue as well.
         */
    } else {
        /* If there was no active queue prior to this invocation, we take over
         * the queue, processing its items until it empties.
         */

        while (1) {
            struct queue_item* next;

            /* At the beginning of each iteration of the loop, we own the active
             * queue, `current` points to the current queue item (which is
             * initially the item created at the beginning of the function), and
             * `back` is NULL.
             */

            /* We can now call `handler()` for the value of `p` associated with
             * the current item. Note that any reinvocation of `wrapper()`,
             * from this point until the following swap, sees an active queue,
             * and therefore will not call `handler()` itself, but will rather
             * add an item at, ultimately, the back of our queue.
             */
            handler(current->p);

            /* In order to safely fetch the next item of the queue, we need to
             * make sure that no one else modifies the queue while we're at it.
             * To do that, we assign NULL to `active_queue_back` (recall that
             * `back` holds NULL at this point,) while fetching its current
             * value into `back`.
             *
             * Any reinvocation of `wrapper()`, from this point until the
             * following swap, will see no active queue, and hence will start
             * its own independent queue, process it until it empties, and leave
             * `active_queue_back` NULL again, before control returns to the
             * current invocation.
             */
            swap(&back, &active_queue_back);

            /* We free the current item and move on to the next one. If the next
             * item is NULL, we terminate the loop.
             */
            next = current->next;
            free(current);
            if (next == NULL) break;
            else current = next;

            /* We restore the previous value of `active_queue_back`, so that our
             * queue is active again. Recall that `active_queue_back` is NULL at
             * this point, so `back` becomes NULL after the swap.
             */
            swap(&back, &active_queue_back);
        }
    }
}

This program can be compiled with gcc -c -m32 wrapper.c, instead of the golfed version.
(Since this version doesn't rely on any shenanigans, unlike the golfed one, it can be compiled without -m32; in this case, don't use -m32 for the test program either.)
Test Program
The following program is a very rudimentary test for wrapper().
It's not meant to be thorough, nor does it rely on completely defined behavior;
rather, its main purpose to show wrapper() in action.
Compile with: gcc -m32 -otest wrapper.o test.c, in a POSIX environment.
Run with: ./test.
The program triggers wrapper() upon receipt of SIGINT (usually, Ctrl + C), and has handler() print a message, and sleep for one second (during which SIGINT may be sent again).
You can terminate the program by sending it SIGQUIT (usually, Ctrl + \).
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>

void wrapper(void* p);

void swap(void* volatile* a, void* volatile* b) {
    void* t = *a; *a = *b; *b = t;
}

void handler(void* p) {
    struct timespec tp;

    printf("handler(p = %tu) entered. Sleeping for 1 second...", (uintptr_t) p);
    fflush(stdout);

    tp.tv_sec = 1; tp.tv_nsec = 0;
    while (nanosleep(&tp, &tp));

    printf(" handler(p = %tu) returned.\n", (uintptr_t) p);
    fflush(stdout);
}

static void signal_handler(int signum) {
    static volatile sig_atomic_t n = 0;
    wrapper((void*) ++n);
}

int main() {
    struct sigaction sa = {};
    sa.sa_handler = signal_handler;
    sa.sa_flags = SA_NODEFER;
    sigaction(SIGINT, &sa, NULL);

    while (pause());
}

Congrat, wonderful solution! :-) I've found a very similar.

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


text:
Write a panic script to remote secure a Mac Pro from an untrustworthy local user
The Situation
Suppose I allow "Shady Sam" admin access on my workstation to perform an important administrative task on my Mac Pro for me by giving them a temporary root login password. (Assume they were trustworthy, perhaps a systems admin for my company.)
From a remote location (e.g. home), I use my MacBook Pro laptop to observe Sam's activities and learn how to do the task myself via Remote Desktop (VNC).
Without warning, Shady Sam does something dastardly! Perhaps I see him trying to delete data from my hard drive or prying into restricted folders, etc. Whatever the dastardly deed, I want to lock Shady Sam out immediately, and secure the computer as best as possible from my remote location.
Since we share the mouse and keyboard, I couldn't reliably perform an action from within Remote Desktop (besides, they could close the connection). I'd have to write a script and run it remotely.
The Challenge
What's the best script (e.g. panicScript.sh or panicScript.py) I could run remotely to stop Shady Sam from performing his dastardly deed and prevent him from attempting it again?
I envision myself running it in the following way:
scp panicScript.sh remoteMachine:~/panicScript.sh
ssh remoteMachine . ~/panicScript.sh

Possible Features:
Other ideas are expressly encouraged!

Change passwords of any/all accounts on remoteMachine
Disable the keyboard or mouse
Disable the monitor
Reboot the machine

Assumptions
Shady Sam will not damage the Mac Pro in any way or remove any of its components (e.g. physically remove a hard drive or wired network connection), but he will attempt to re-login and continue his dastardly deed as quickly as possible. Sam has (otherwise) unrestricted physical access to the computer and a root login password.
Assume the Mac Pro has a monitor, keyboard, mouse, external hard drive, and an ethernet connection for internet. Let's suppose it can print to a network printer in a common area. For fun, let's suppose I have a standard user account on several coworker's workstations, which are identical to mine (so I can connect to their machines via ssh).
Assume there are a dozen open-air cubicles clustered together so that coworkers can stand up and talk to each other. My coworkers, however, will generally not suspect that Shady Sam is doing something dastardly if they see him at my computer because he has helped several of them in the past and didn't do dastardly things to their computers.
Constraints
The panic script is initially on my laptop at home. You can scp it to my machine and run it there, or run it directly from my laptop at home. (Specify in your response!)
All actions taken by the script must be non-damaging and/or reversible from my remote location so that I can regain access at a later point from my remote location, and must be standard features/commands on a Mac Pro.
The script may call other scripts/programs as long as they come standard with the machine. Command-line scripting tools (e.g. awk) are okay as long as their commands is contained in the main script (e.g. history | awk '{print $2}'). This admittedly limits the scripting languages that could be used.
Calling a custom script or program you wrote (e.g. . ~/myOtherScriptOfKungFoo.sh) isn't okay, unless you generate it from within your script and the generated script is under 32 characters:
echo -e "#"'!'"/bin/bash\necho \"Hello, World\"" >> test.sh
chmod +x test.sh
. test.sh

I shouldn't have to interact with the script more than once (e.g. to type a password).
Criteria
The script should be short (cap of 30 lines), yet readable. Primary criteria is thoroughness, creative features and style, which is better than simplicity.
Ultimately, the most votes wins!

Pro-tip: Don't hire anyone named Shady Sam.

The panic script should be sent to remote machine (Mac Pro) using scp, and then run (no sudo or any input required):
Here is the script: (this assumes that you are John Smith)
#!/bin/bash -m
f() {
 while true
 do
  pmset displaysleepnow
  sleep 0.1
 done
}
f&
while true
do
 osascript -e "set Volume 10"
 say -v Ralph "Stop Shady Sam now. He is trying to do something he is not allowed to."
 for n in {1..10};
 do
  afplay /System/Library/PrivateFrameworks/ScreenReader.framework/Versions/A/Resources/Sounds/Hit.aiff
  sleep 0.05
 done
 sleep 0.1
 say -v Ralph "This is John Smith speaking."
done

For maximum effiency, you should run this on every single machine in room to ensure that everybody will notice the problem and stop him.


text:
Find the digit occurring the most in a range of prime numbers
Find the digit which occurs the most in a range of prime numbers.
Input:
Two numbers, p and q, specifying the range; the range includes both p and q.
Output:
The digit that occurs most frequently in that range of prime numbers. If two or more digits are tied, all of them should be outputted.
Winning Criteria:
Fastest code to complete (insert 1+ specific test cases here) wins.
Example
Input: 21 40
Output: 3
Explanation
The prime numbers in the range 21 40 are 23, 29, 31, and 37. Within these numbers, 2 occurs 2 times, 3 occurs 3 times, and 1, 7 and 9 occur 1 time each. Thus, as 3 appears the most, the correct output is 3.

I've added the tag corresponding to your chosen winning criterion. Please have a look at the tag wiki and consider clarifying especially the second and third question there.

"Two numbers p and q specifying the range" how? Inclusive, exclusive, one of each? What should the output be if there's a tie? What should it be if the tie is because there are no primes in the range? And are you really sure you want to do a [tag:fastest-algorithm] which involves primality testing, bearing in mind that the running time of the best known algorithm depends on the correctness or otherwise of a long-open problem (the generalised Riemann hypothesis)?

I think this could be an OK question if the winning criterion is least number of bytes, and all of Peter's questions are answered.

@PeterTaylor First of all Primality testing has a poly time algorithm (Agarwal,2002) . Second by fast algorithm I never said it has to be poly time, I just wanted an algorithm better than just bruteforce. Third I have specified range as inclusive.

I know that PRIMES is in P: the developments of AKS techniques are precisely what's behind my comment about the GRH. The best AKS variant is in Õ(n^6) if the GRH is false, and Õ(n^4) if the GRH is true. Moreover, the previous [tag:fastest-algorithm] question about primes has a few answers, not a single one of which has a stated score. I don't think [tag:fastest-algorithm] and primes are a good fit for each other.

@alienCoder Could you define more precisely what should happen in the case of finding two (or more) digits which occur the most, like if there are 4 threes and fives? Also, what do you mean by input and output? Function parameters and return value? STDIN and STDOUT?

39 is divisible by 3. It's not prime.

@alienCoder What do you mean as least time complexity? Big O notation ? Note that two algorithms with the same time complexity given in terms of big O notation may differ in the time of execution by an arbitrarily big constant factor. Maybe consider [tag:fastest-code] instead? This could make this question more "popular".

Python 3
import collections
p=lambda n:n>1 and all(n%i for i in range(int(n**0.5),1,-1))
print(collections.Counter(''.join(map(str,filter(p,range(*map(int,raw_input().split(' '))))))).most_common(1)[0][0])

Probably not the best way it can be done, but a start. (196 bytes)
Time Specs
Using Python's builtin code timer module, timeit, I got these times for each listed range.
(1,       11):      0.000084381103520
(1,      101):      0.000338881015778
(1,     1001):      0.003911740779880
(1,    10001):      0.071979818344100
(1,   100001):      1.785329985620000
(1,  1000001):     54.977741956700000
(1, 10000001):   1700.231099130000000

It can go over a range of a million numbers in under a minute.
Usage
$ python test.py
21 41
3
$ python test.py
51 89
7
$ python test.py
201 501
3

Ungolfed
import collections

def is_it_prime(n):
    if n > 1:
        if all(n % i for i in range(int(n ** 0.5), 1, -1)):
            return True
    return False

start, stop = raw_input.split(' ', 1)

primes = ""
for p in range(int(start), int(stop)):
    if is_it_prime(p):
        primes += str(p)

counter = collections.Counter(primes).most_common(1)
print(counter[0][0])

Just so you know, winning criteria is time complexity, not byte count :)

I saw; that's why I added the "Time Specs" section. :P @Shebang

Just making sure you know if you want to update you could un-golf to make updating much easier. Nice work though! :)

Added an ungolfed version. @Shebang

Mathematica
 Print[""<>IntegerString[MaximalBy[Tally[Join@@IntegerDigits[Prime[Range[PrimePi[#1]+1,PrimePi[#2]]]]],Last][[;;,1]]&@@FromDigits/@StringSplit@InputString[]]]

Time Specs
Using Mathematica's builtin timer, AbsoluteTiming, I got these times for each listed range.
f=MaximalBy[Tally[Join@@IntegerDigits[Prime[Range[PrimePi[#1]+1,PrimePi[#2]]]]],Last][[;;,1]]&
Grid[Table[{1,10^x+1,AbsoluteTiming[f[1,10^x+1]][[1]]},{x,1,7}]]

Returns:
1        11   0.0003388
1       101   0.0003645
1      1001   0.0016222
1     10001   0.0040902
1    100001   0.0267737
1   1000001   0.211297
1  10000001   4.55387
1 100000001  43.9889

It can go over a range of a hundred million numbers in under a minute.
Usage
wolframscript -f primedigitcount.wls
? 21 41
3
wolframscript -f primedigitcount.wls
? 51 89
7
wolframscript -f primedigitcount.wls
? 201 501
3

Ungolfed
Takes the space-seperated input and converts it to two integers
a = FromDigits/@StringSplit@InputString[]

PrimePi is the inverse function of Prime, so this gets all the primes between the two a's. The +1 is that if the operand is not prime, it gets the first prime below it, but we want a prime above the smaller number.
b = Prime[Range[PrimePi[#1]+1,PrimePi[#2]]&@@a

Turns every number in the list into a list of it's digits, and then concatenates all the lists into one list of all the digits
c = Join@@IntegerDigits[b]

Mathematica has a nice built-in for turning a list into unique items and their counts.
d = Tally[c]

Takes a list of the item (or items) who has the largest count, and strips off the tally.
e = MaximalBy[d,Last][[;;,1]]

Converts every number in the list to a string, concatenates them, and prints it.
Print[""<>IntegerString[e]]

Conjecture:
In hope that somebody more mathematically inclined could find this to be an O(n) problem, I leave you this conjecture:
If the first number is kept as 1, and the 2nd number tends to be large (n>100), the result will be no more than two of 1, 3, or 7.

I don't know Mathematica so I can't prove it, but the timings definitely do point towards this being $O(n)$ (as you multiply the upper limit by 10, the timings also increase by a factor of 10).

Yep, re-read and remembered that my variable is 10^x, not just x, I should state it as O(log(n)). If the pattern is logarithmically cyclical, then it could be ~O(1).

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


text:
The Great British Cake Off
I hear somebody was very selfish on their birthday, demanding cake from everyone and there were no plans to share! 🎂
It's bound to be somebody's birthday today, so why not bake them a cake. Use your favourite programming language to make a delicious cake, with a nice "Happy Birthday" message as the output. (Might I suggest Chef!)
Your cake should

Mimic a real world recipe (if you can link to it, brilliant!)

a list of newline separated ingredients suitable for making a cake
a newline separated list of steps for the method
how many people it serves

Stay as close to correct ingredient ratios as possible.
Output minimally "Happy Birthday" when served.

The best cakes will be:

Delicious  - since this is a popularity-contest, the community will decide what is delicious
Personalised - try baking a custom happy birthday message to somebody specific. (If you can't find a PPGC user, why not a celebrity?)
Balanced - Try to use a suitable number of ingredients for the amount of servings the recipe prepares. 1000 eggs, serves 1 for one serving is probably just a teensy bit big, huge, absolutely colossal!
Outlandish - You can bake more than just a basic sponge, for example, include some icing, a drizzle, serve with sauce, decorations, etc.
Visually appealing - images are good either in the source code as ascii or in the output. The first "byte" is with the eyes after all.

And don't forget, good bakers don't cut corners and do things properly. (Don't just use no-op code to make it look like a recipe then print, make sure your code means something)  I encourage voters to view these recipes negatively.
Happy Baking!

Hey, in my defence, I thought you were all going to get me some!

Is it any consolation that I was concerned that you'd be upset?

Nah it's fine, I'm just kidding ;)

Maybe it should have been also [tag:underhanded]?

@close voter: I list 3 criteria which all programs should meet and 6 criteria which "judges" can use to vote for cakes. What am I missing?

I’m voting to close this question because it lacks an "objective validity criterion" as required by the [tag:popularity-contest] tag wiki.

@TheFifthMarshal I don't think anybody wants 7 year old cakes now anyway ;) Let the question rot :D

But ...  "the entire premise of the Stack Exchange network is that old content is still relevant, and doesn't collapse into a mass of goo". Not even content about perishable foods ...

@TheFifthMarshal I agree. I'm saying let it rot :)

ECMAScript 2015, serves 10
Don  =([_])=> alert(_.replace(/^.*(?=, )/,'Happy Birthday'))

ReadMoreAbout  =classic=  victoria  =sandwich=  on  =bbcgoodfood=      ~`

⚠  Remember that OCR technologies aren't perfect, and that scanning old,
⚠  smudgy recipes does not always go as smoothly as we'd expect or hope.
⚠  This recipe is not wonderful, but please, thoroughly enjoy making it.

`

try/* to do this properly! */{
  // Link to recipe:
  bbcgoodfood.com/recipes/1997/classic-victoria-sandwich
  'Makes 10 slices'

  Ingredients:
    ForThecake:
      - 200 | grammes | castorSugar
      - 200 | grammes | softenedButter
      -   4 | whole   | eggs
      - 200 | grammes | self-raising_flour
      -   1 | tsp     | bakingPowder
      -   2 | tbsp    | milk

    For_theFilling:
      -  100 | grammes | butter, softened
      -  140 | grammes | icing.sugar, sifted
      -    a | drop    | vanilla- extract (optional)
      -  240 | grammes | jar.good-quality_strawberryJam
      -                  icingSugar, to.decorate

  Method:
    1. ^`Heat oven to 190C/fan 170C/gas 5. Butter two 20cm sandwich tins
         and line with non-stick baking paper. In a large bowl,
         beat all the cake ingredients together until you have a smooth, soft batter.`
    2. ^`Divide the mixture between the tins, smooth the surface with a spatula
         or the back of a spoon, then bake for about 20 mins until golden
         and the cake springs back when pressed. Turn onto a cooling rack
         and leave to cool completely.`
    3. ^`To make the filling, beat the butter until smooth and creamy,
         then gradually beat in icing sugar. Beat in vanilla extract if you’re
         using it. Spread the butter cream over the bottom of one of the sponges,
         top it with jam and sandwich the second sponge on top.
         Dust with a little icing sugar before serving.
         Keep in an airtight container and eat within 2 days.`

  * HappyBirthdayǃ
} catch (cake) {
  Don`t drop that! It's your cake, Uncle Chris! This cake is one day late – sorry about that.
`}

Valid ES6 code; no corners cut!
It works in Firefox Developer Edition.

 It is all valid code; the try only serves to catch the ReferenceError caused by the variables not being defined.

This is a good answer. This is what I was looking for.

Clearly ⚠ should become a valid comment character in ECMAScript 7.

@immibis Yeah, definitely :-)

BF
Inspired by mbomb007s answer, I've made them a cake.
I'm afraid I lost the recipe (it's around here somewhere, but I'd probably have to break my own rules on cutting corners to post it); here is the finished product.
                                    +
                                    [
                       (
               )                    )             (
                       )           (o)    )
               (      (o)    )     ,|,            )
              (o)     ,|,          |~\    (      (o)
              ,|,     |~\    (     \ |   (o)     ,|,
              \~|     \ |----(o)->++|+\<]>,|,     |+.
              |`\-----|`\@@@-|-@@@@\.-@@@\~|[++>-\ |-
             -\-|-o@@@\ |@@@<]>@@@@|.\@@@|.\@@@o+|+\++
            ++|+\@@@@@|+\@@@|+\@@@@\.|@@@\-[@@@@@\-|o--
           ->@\+|@@@@@\<|@@@]>|@@@@@@@@@@|+\@@@@@|+\@@o.
          [->+|+\+@@@@@@@@@@|<]@@@@@@@@@@\>|@@@@@\+|+@@@.
          +@@@@@@@@@@@@@@@@@\+|@@@@@@@@@@|+\@@@@@@@@++++.
          @@++@@@@@@@@@@@@@@|+\@@@@@@@@@@@@@@@@@@@@+++++
          +.@@@++@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@o@@.-@
          --@@--@@-@@@@@@@@@@@@@@@@@@@@@@@@@@@@-@@-@@--@
          --@@.-@@@@---.@@@@--@@@@@-.+[@@@@@o---@@@>+<:]
          >::::::+::::::++@@.::@@@:::::@@@@:::::@@:::::%
          %%::::::::::::@@::::::@:::::::@@::::::::::::%%
          ::%%%::::::::::@::::::::::::::@::::::::::%%%::
       º# ::%::%%%%%%:::::::::::::::::::::::::%%%%%::%::##º
     º### ::::::%%:::%:%%%%%%%%%%%%%%%%%%%%%:%:::%%::::: ###º
   º##### ::::::%:::::%%::::::%%%%:::::%%::::%:::::::::: #####º
  º###### `:::::::::::%:::::::%:::::::::%::::%:::::::::' ######º
 º########  ``::::::::::::::::::::::::::::::::::::''  #########º
  º##########   ```::::::::::::::::::::::::::'''   ###########º'
    `º#########-[---->+<]>++.[-->+++<]>..+++++++. ###########º'
      ` º#################################################º '
          ` º#######################################º '
             ` º#################################º '
                   ` º######################º '

Outputs:
happy birthday 007

So conveniently it works for James Bond, but not until 11th November.

Woah........... nice!

Is it clean Brainfuck? It doesn't seem to work for me...

Python 2, serves 0
First of all, sorry, this isn't a REAL world cake.
However, it is in one of the best games of all time,  Portal.
This recipe is based on what the Intelligence Core says are the ingredients.
""" Happy Birthday, Chell!
* * * * * * * * * * * """
# Here are all the ingrediants for portal cake
candles = 1 # There is most certainly only one candle for her.
fish_shaped_dirt = 32 # There isn't an official amount of dirt to add, 32 seems like a nice number.

#Full of lies
lie = float('inf')

serves = None

# Show the tester the documentation on how to use this
print __doc__,

# Now, we are going to repeat these steps until chell stops lying.
while lie:
    # She did it again, so now we need to do the whole thing once more.
    print "\r",
    # Check how many candles her cake will have
    if candles:
        # We had better take them away from her. Maybe it will stop her lying so much
        candles = 0
    else:
        # Maybe if we give her a candle, she will listen
        candles = 1
    # See, her chances of lying go down when we give her candles!
    lie -= candles
    # Add the fish shaped dirt. But ONLY if we're giving her a candle.
    print chr(fish_shaped_dirt)*candles,
    # Add all the other rubbish
    print __doc__[25:],
    #Flush it into the relaxation vault
    import sys
    sys.stdout.flush()
    # Wait and ask her if she liked it.
    import time
    time.sleep(1)

Output
 Happy Birthday, Chell!
 * * * * * * * * * * *

Followed by
 Happy Birthday, Chell!
  * * * * * * * * * * *

Then repeats indefinitely

The cake is a lie.

I want to up vote because I love Portal, but by my own criteria I can't! Even if I could eat a cake that wasn't a lie, it would taste awful. Dirt doesn't make for good eating!

This is a triumph.

You didn't even use the best ingredients. 1 rhuBARB on fire, fish-shaped crackers,  a book on how to kill someone with your bare hands, etc.

It serves 0. You can never make enough of it to make a serving. Therefore, you will have to listen to me when I say this it tastes great

Where's the fish shaped ethylbenzene?

Brainf***
I like ice cream cake, which doesn't require baking. Also, it's my birthday, so don't tell me what kind of cake I can have.
Buy an ice cream cake:
    +   +   +    +   +   +
    |   |   |    |   |   |
[-]-[------->+<]>-.[--->++++<]
|><>+.-[++>-----<]>..+++++++++
|><.-[---->+<]>++.+[->++<]>.-[
|><--->+<]>--.+++++++++.++.---
|><---------.----.---.+[--->+<
|><]>+++.-[---->+<]>+++---+++|
then serve it.

I like to pretend that the >+<]>'s are fish-shaped crackers.

I think this is worthy of a +1 for matching 4/5 "best cake" criteria. I'll give you the vote, but definitely cut corners by just buying the cake.

I also could've personalized it, but that would make the cake twice as big. It also just didn't look as great.

I'm currently having a go at making the cake look more extravagant :P

I made you a cake.

@mikeTheLiar I guess you haven't played Portal or read the recipe recently? Read it again: http://theportalwiki.com/wiki/Core_voice_lines#Cake_core

Don't I feel dumb now. : /

@mikeTheLiar It's a long recipe to remember. I like rhuBARB.

Pip, serves 2
For those of us whose birthday tastes are a little more global...
Our dessert tonight: " Birthday " Dosa!
(adapted from vegrecipesofindia.com/masala-dosa-recipe-how-to-make-masala-dosa-recipe)

1 cup rice: ("mmm, rice")
1 cup ukda chawal: [don't know what that is but it sounds good]
1/2 cup urad dal: ["dal" means lentils in Hindi]
1/4 cup poha: ["poha" is another kind of rice]
1/4 tsp methi seeds: ("!")
salt to taste: ["Happy" time]
water as needed: [you'll need some water]

Are you ready to cook? Yes? OK then:

1. rinse the rice and urad dal separately first.:
2. soak the ukda chawal, rice and poha.
3. in another bowl soak the urad dal-methi in enough water.
4. grind the urad dal with methi to a fine and fluffy batter.
5. grind the rice and poha to a smooth batter.
6. mix both the rice and urad dal batter with salt.
7. cover and let the batter ferment for 8-9 hours.

is it Ready? Y(es) or N(o)

Answer should be: y.
    take batter out and:

1. heat a flat cast-iron griddle and smear some oil on it.
3. spread the dosa batter in a circular way on the griddle; add some oil on top.
4. flip and cook the other side.
5. serve dosa hot with coconut chutney and sambar. (yum)

Recipe serves ___:
           `(?<=2) ?`
Actually, it serves exactly 2--half feR "ME" and half feR:_" YOU"!
Yeah! Happy birthday  !

Output
Happy Birthday 2 YOU!

or, if you cook it:

Now I'm hungry.

Dosa in a cooking-related challenge? That sounds familiar... ;-)

+1 for "Now I'm hungry." Thanks a lot, I'm hungry now too.

For the record I also have no idea what ukda chawal is.

Chef, serves 16.
Based off of this. I couldn't find an interpreter online, so I closely followed the specs found here.
"Golfed" version
"Happy" Birthday Cake.

This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.

Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space

Cooking time: 25 minutes.

Pre-heat oven to 162 degrees Celsius.

Method.
Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put space into mixing bowl. Put happiness into the mixing bowl. Remove water from the mixing bowl. Combine vanilla extract into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add butter to the mixing bowl. Add happiness to the mixing bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove water from mixing bowl. Add happiness to the bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove semisweet chocolate from mixing bowl. Add happiness to the bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put eggs in mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Put happiness into the mixing bowl. Put happiness into the mixing bowl. Remove sugar from the bowl. Remove baking soda from the bowl. Put space into mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add salt to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Add butter to the mixing bowl. Add water to the mixing bowl. Put space into the mixing bowl. Add baking soda to the mixing bowl. Liquefy contents of the mixing bowl. Serves 16.

Output: Happy Birthday, me!.
Here is the explanation for each step:
"Happy" Birthday Cake.

This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.

Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space

Cooking time: 25 minutes.

Pre-heat oven to 162 degrees Celsius.

Method.

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72 (H)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24= 97 (a)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add corn starch to the mixing bowl.             +8 =112 (p)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add corn starch to the mixing bowl.             +8 =112 (p)

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72
Add happiness to the mixing bowl.                +24= 96
Add happiness to the mixing bowl.                +24=120
Add sugar to the mixing bowl.                   +1 =121 (y)

Put space into mixing bowl.                     32      ( )

Put happiness into the mixing bowl.              24
Remove water from the mixing bowl.              -3 = 21
Combine vanilla extract into the mixing bowl.   *2 = 42
Add happiness to the mixing bowl.                +24= 66 (B)
Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add butter to the mixing bowl.                  +1 = 81
Add happiness to the mixing bowl.                +24= 95 (i)

Put space into the mixing bowl.                 32
Combine water into the mixing bowl.             *3 = 96
Remove water from mixing bowl.                  -3 = 93
Remove water from mixing bowl.                  -3 = 90
Add happiness to the bowl.                      +24=114 (r)

Put space into the mixing bowl.                 32
Combine water into the mixing bowl.             *3 = 96
Remove water from mixing bowl.                  -3 = 93
Remove semisweet chocolate from mixing bowl.    -1 = 92
Add happiness to the bowl.                      +24=116 (t)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the bowl.                       +24=104 (h)

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72
Add happiness to the mixing bowl.                +24= 96
Add sugar to the mixing bowl.                   +1 = 97 (d)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24= 97 (a)

Put eggs in mixing bowl.                        73
Add happiness to the mixing bowl.                +24 = 97
Add happiness to the mixing bowl.                +24 =121(y)

Put happiness into the mixing bowl.              24
Put happiness into the mixing bowl.              +24= 48
Remove sugar from the bowl.                     -3 = 45
Remove baking soda from the bowl.               -1 = 44 (,)

Put space into mixing bowl.                     32      ( )

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add salt to the mixing bowl.                    +5 =109 (m)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24=97
Add butter to the mixing bowl.                  +1 =98
Add water to the mixing bowl.                   +3 =101 (e)

Put space into the mixing bowl.                 32
Add baking soda to the mixing bowl.             +1 = 33 (!)

Liquefy contents of the mixing bowl.            Converts the mixing bowl to characters

Serves 16.                                      Outputs the contents of the first
                                                16 bowls.

Isn't it spelled "happiness," or do names need to be a specific way?

Sorry, wrote in my code-pad. I forgot I had turned off auto-correct.

I also haven't run this yet, but I think you've got everything in 1 mixing bowl, then attempt to output 16.

@JamesWebster The spec says that the Serves N statement outputs all the ingredients in each bowl from 1 to N.

Yeah, but you have only used one bowl. Bowls 2-15 are empty / don't exist.

@JamesWebster I took a little interpretation on my part: If the bowl doesn't exist, nothing happens (silent error handling, like in JavaScript or TI-BASIC)