text:
Write a Metaquine
A metaquine is a program which is not a quine, but whose output, when run as a program in the same language, is a quine.
The goal of this challenge is to write a metaquine. This is code-golf, so shortest code wins, with earliest answer used as a tiebreaker. Note that only full programs are acceptable, due to the definition of a quine.
Rules for Quines
Only true quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, without:

reading your source code, directly or indirectly.
relying on a REPL environment which just simply evaluates and prints every expression you feed it.
relying on language features which just print out the source in certain cases.
using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)
the source code consisting purely of literals (whether they be string literals, numeric literals, etc.) and/or NOPs.

Any non-suppressible output (such as copyright notices, startup/shutdown messages, or a trailing line feed) may be ignored in the output for the sake of the validity of the quine.
Example
Ignoring the rule which forbids literal-only programs and built-in quining, this would be a metaquine in Seriously:
"Q"

The program consists of the single string literal "Q", which is implicitly printed at output. When the output (Q) is run, it is a quine (Q is the built-in quine function).

Does the literals/comments/NOPs rule apply to the output (i.e. the real quine) of the metaquote as well? Otherwise ex. T is an easy 1-byte Pyth answer.

@Doorknob Yes, I'll clarify.

I don't really see where's the difficult point of this challenge. Isn't the strategy "print the string which contains the shortest known quine" pretty much guaranteed to win for each language?

@Fatalize Well I guess the interesting question is, can that be done in the same amount or fewer bytes than the quine itself.

@Fatalize Isn't it also possible that you could write a short metaquine that prints a long but valid quine?

You should add a rule to prevent the empty quine.  E.g. any C program which produces no output technically could be a meta-quine, because a blank source code will compile (and print nothing, which happens to be its source code).

@DarrelHoffman Empty programs are already a standard loophole

What kind of a quine gives shutdown messages? o_O

@CᴏɴᴏʀO'Bʀɪᴇɴ I'd imagine some interpreter out there always prints "Goodbye!" or something similarly ridiculous on exit.

Oh, program shutdown messages. I thought you meant computer shutdown messages ^^"

@CᴏɴᴏʀO'Bʀɪᴇɴ Well it really depends on your definition of interpreter. It could be a literal OS shutdown message with C/assembly, where the "interpreter" is the processor.

So... is SMBF allowed, since the source code and execution happen on the same tape? Example quine (not metaquine): <[<]>[.>], which does use its own code that was on the tape (and can be read/modified) during execution. I guess I'll post an answer, and people can downvote if they don't like it.

CJam, 6 bytes
"_p"_p

Prints
"_p"
_p

which is the shortest proper quine in CJam.
Test it here.
Explanation
Both programs work exactly the same, since the linefeed inside the proper quine is a no-op and only included because it's more expensive to remove it from the output. How the programs work:
"_p"  e# Push this string.
_     e# Duplicate it.
p     e# Print a string representation of the top of the stack (i.e. the string with
      e# quotes) followed by a linefeed.
      e# The other copy is then printed automatically at the end of the program, without
      e# stringifying it.

Side Note
The same works in GolfScript as
".p".p

which prints
".p"
.p

with a trailing linefeed, which in turn is one of the shortest known quines.

Pyth, 12 11 10 9 bytes
Knocked off one more byte thanks to @Pietu1998.
jN B".[9N

This prints
.[9N".[9N

which is a quine in Pyth. You can try it out here.

Is the output a new record for the shortest Pyth quine? I don't believe I've ever seen it before.

I couldn't find it anywhere else. I came up with it trying to get a metaquine.

Perhaps you should post it as an answer to the original quine challenge :)

You can get this down to 9 by using jN B".[9N or .[9N"jN B. (jN B"jN B is another true quine at 9: bifurcate identity function and join by ".)

@Pietu1998 Thanks! I knew there must be a way to get it to 9. Are there any quines in Pyth that are shorter than 9 bytes?

@Rhyzomatic None that I know of, mainly due to the fact that Pyth has no short way of eval'ing Pyth code.

Fission, 6 bytes
!+OR"'

Prints
'!+OR"

Which is the shortest Fission quine. This works because cyclic shifts of the program leave its output completely unaffected.
Try it online!

Javascript ES6, 21 bytes
$=_=>`$=${$};$()`
$()

Trivial.

Happy 3k!!!!!!!

@ConorO'Brien Wow, much rep. 3k factorial is already more than Jon Skeet...

Python 2, 29 bytes
_="_=%r;print _%%_";print _%_

Turns out the well-known short python quine is easily turned into a metaquine :)
And, since we don't have to worry about matching the trailing newline, the metaquine is actually shorter!

beat me to it, again :( I thought of a wrapper, but yours is better

Japt, 15 13 bytes
Q+"+Q ³s7J" ²

Test it online!
This program outputs
"+Q ³s7J"+Q ³s7J

which is the shortest known quine in Japt.
How it works
Q+"..." // Take a quotation mark plus this string.  "+Q ³s7J
²       // Repeat it twice.                         "+Q ³s7J"+Q ³s7J
        // Implicit output

11 bytes
Q+"+Q ²é" ²

I've just added é, a "rotate" command. So
"+Q ²é"+Q ²é

is now a valid quine.

Ruby, 25 23
puts"puts <<2*2,2
"*2,2

Generates the classic Ruby HEREdoc quine
puts <<2*2,2
puts <<2*2,2
2

Old solution
_='_=%p;$><<_%%_';$><<_%_

Generates itself except with the single quotes replaced with double quotes.

JavaScript, 50 bytes
a="a=%s;console.log(a,uneval(a))";eval(a.slice(5))

Based on the shortest non-source-reading JS quine known to man, but a good 8 bytes shorter. Prints
a="a=%s;console.log(a,uneval(a))";console.log(a,uneval(a))

which is a quine.

Fish (><>), 17 bytes
This works using the classic fish quine "r00g!;oooooooo| but adds a { which shifts the entire stack to the left so that the original program isn't a quine, but it's output, when run, is.
"{r00g!;oooooooo|

Outputs:
"r00g!;oooooooo|

which is a fish quine!

Jelly, 3 bytes (non-competing)
Unfortunately, the required atoms are roughly 2 weeks younger than the challenge.
Metaquine
”Ṙv

Try it online!
How it works
”Ṙv  Main link. No arguments.

”Ṙ   Set the left argument and the return value to the character 'Ṙ'.
  v  Dyadic eval; evaluate the return value with the left argument as argument.
     Executing the atom Ṙ on the argument 'Ṙ' prints a string representation of
     the character, i.e., the string "”Ṙ".
     Finally, v returns its unaltered argument, which is printed implicitly.

Quine
”ṘṘ

Try it online!
How it works
”ṘṘ  Main link. No arguments.

”Ṙ   Set the left argument and the return value to the character 'Ṙ'.
  Ṙ  Print a string representation of the character, i.e., the string "”Ṙ".
     (implicit) Print the unaltered return value.

Since the second Ṙ prints the first two characters (”Ṙ), this is a proper quine by our definition.

Octopen-Baru, 22 bytes
** Non competing answer
愛[35211].pack歩U')

Ruby output
puts [35211].pack(' U')

Which outputs 見. Which is a quine in Octopen-Baru!

7, 2 bytes, language postdates challenge
The program is two bytes long, and can be interpreted in several ways; as a hex dump:
00000000: 4ff4                                     O.

as codepage 437:
O⌠

or, most readably, in octal (which 7 natively uses):
237723

Try it online!
The workings of this are very simple: it's the standard 7 quine with a no-op stack element inserted between the two halves, to make it different (in this context, 7 separates stack elements). (I could also have inserted it at the start, 723723. I couldn't have interpreted it at the end because trailing 7s are like trailing whitespace, and ignored in the packed encoding, thus it wouldn't be any different from the output program.)
Incidentally, this program is a palindrome in hexadecimal, but that's mostly just coincidence.

Underload, 11 bytes
(:aSS)::aSS

Pretty simple. It prints out (:aSS):aSS, which is the standard Underload quine.

Brachylog, 12 bytes
"~k;?w₁"gjw₃

Try it online!
One of 132 same-length metaquine variations on the quine I translated from Fatalize's Brachylog v1 (non-cheating) quine. I actually wrote a (non-golfed, and overall silly) program to print all of them out:
{[[";?","gj","jḍ"],"₁₃₅₇"]j∋ᵐ{ḍ≠&};"\"~~k~ww~w\"~ww~w~n"}ᶠ{lw" metaquines generated:
"ẉ&}w₁ᵐ

Try it online!
There are two parts of the original quine which could be replaced inconsequentially: ;? can be changed to gj or jḍ, and ₁ can be changed to ₃, ₅, or ₇. If we keep or change them outside the string literal in one way and inside the string literal in a different way, then the output won't match the source, because whichever variants were present within the string literal will be printed both inside and outside it, resulting in a quine which was not the initial program run.
;?, gj, and jḍ are interchangeable because all three pair the string literal with itself: due to the layout of the program, the input variable ? is unified with the string, so ;? pairs the string with itself; regardless of the layout, gj wraps the string in a list which is then concatenated to itself; likewise jḍ concatenates the string to itself then splits it in half.
The odd-numbered w subscripts are interchangeable because, although originally w could only take 0 or 1, with 0 printing the input to w and 1 printing the first element formatted with the second, the subscript inventory for w has grown into something that externally functions as a bitfield: the low bit of the subscript encodes whether it's direct or formatted, the middle bit encodes whether the output variable from w is unconstrained or set to the input, and the high bit encodes whether the printing is done immediately or if it's delayed until the end of the program so it can be subject to backtracking. (Those subscripts were my first and so far largest contribution to Brachylog.) Since the quine and metaquine don't use the output variable and don't backtrack, all four odd subscripts are equivalent.

Vyxal, 3 bytes
\II

Try it Online!
which prints :
`I`I

Try it Online!
which is a quine
Explanation :
  I  # quote and prepend
\I   # the char `I`
     # Implicit output => `I`I

   I # quote and prepend
`I`  # a string containing `I`
     # implicit output => `I`I

Befunge-93, 22 bytes
"+1_@#`+39:,g0:">:#,_@

I just took the standard quine, put it in quotes, reversed it (so it is loaded on the stack correctly), and then added a stack-print at the end.
It's 8 characters added to the normal quine, so it's very possible there's a better solution.

Couldn't you just take the standard quine and add a newline? The newline will disappear at the parsing stage, leaving you with just the standard quine (which will print itself).

Turtlèd, 52 bytes (noncompeting)
1 less than original quine
@##'@r,r,r-{ +.r_}r{ +.r_}"#'@r,r,r-{ +.r_}r{ +.r_}"

Works in the same way, except that it does not have a character at the end, when run, it will have a character at the end, that does not effect output, because it writes # on to a #. Note the output is slightly different to the quine I have made for the quine challenge, but works the same: " writes #, which is its own last character, like the quine I made. Check out the explanation there.

Lua, 45 bytes
Quine code not mine.
s="s=%qprint(s:format(s))"print(s:format(s));

will result in
s="s=%qprint(s:format(s))"print(s:format(s))

which is a quine. Glad the ; is optional in Lua.

Pushy, 7 bytes
Non-competing as the language postdates the challenge.
This is the standard quine, but with newlines removed. Newlines mean nothing in Pushy, but are the print operator's standard separator, and therefore needed for a true quine.
95 34_"

Try it online! This outputs:

95 34
_"

Which is the shortest Pushy quine - an explanation on how it works can be found here.
Alternatively, H5-34_" works for the same byte count.

Foam, 14 bytes
[. .'|: ~|]: ~

This prints the second Foam quine that can be found here. This is actually shorter because . will always put a space between each element, but the bar in the third token allows me to omit the space before it.

I've removed the non-competing bit because newer languages are not automatically non-competing as per site policy.

Husk, 6 bytes
D"S+s¨

Try it online!
Prints the standard Husk quine S+s"S+s".
 "S+s¨    The string S+s"
D         concatenated with itself.

The quine explained:
   "S+s"    The string S+s
 +          concatenated with
S           itself passed through
  s         the function which returns its string representation.


text:
Remove leading and trailing zeroes
Given a non-empty list/array containing only non-negative integers like this:
[0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0]

Output the list with trailing and leading zeroes removed.
The output for this would be:
[8, 1, 4, 3, 5, 6, 4, 1, 2]

Some other test cases:
[0, 4, 1, 2, 0, 1, 2, 4, 0] > [4, 1, 2, 0, 1, 2, 4]
[0, 0, 0, 0, 0, 0] > nothing
[3, 4, 5, 0, 0] > [3, 4, 5]
[6] > [6]

Shortest code wins

Are the numbers non-negative integers only? I suggest you clarify that or add test cases with other numbers

Can we assume that there will be at least one leading and one trailing 0?

@LuisMendo Yes, only non-negative integers.

@DJMcGoathem No, it is possible that there is no leading or trailing 0

What constitutes nothing? I can think of several different things that are variations on nothing in Perl 6. Nil ()/[] slip()/Empty Any {} some of them are undefined, some defined but singular, some that slip into other lists such that they don't increase the number of elements. ( There are as many different variations on Any as there are classes/types and roles )

Is it a coincidence that there are no integers over 10 or can we assume that all the numbers are going to be single-digit?

Huh. I was thinking about posting this the other day, actually. +1

Can we input/output the list as a delimited string? For example: "0,4,1,2,0,1,2,4,0" => "4,1,2,0,1,2,4" EDIT: Just noticed many languages do this already.

Jelly, 2 bytes
Code:
t0

Explanation:
t   # Trim off...
 0  #  zero at both sides

Try it online!

This works? Jeez. I thought the MATL answers were insane.

wut y no don do dis jelly

Of course Jelly beats every other guy out there almost every time...

Is Jelly used in actual businesses?

Man, I hope not

JavaScript (ES6) 43
a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

Less golfed
a=>{
  f=a=>a.reverse().filter(x=>a|=x) // reverse and remove leading 0
  // leverage js cast rules: operator | cast operands to integer
  // an array casted to integer is 0 unless the array is made of
  // a single integer value (that is ok for me in this case)
  return f(f(a)) // apply 2 times
}

Test

F=a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

function test(){
  var l=(I.value.match(/\d+/g)||[]).map(x=>+x)
  O.textContent=F(l)
}

test()
#I { width:90%}
<input id=I oninput='test()' value='0 0 1 3 7 11 0 8 23 0 0 0'>

Nice. f=(a,r=f(a,a))=>r.reverse().filter(x=>a|=x) is also 43 bytes.

Retina, 12 bytes
^0 ?

)` 0$

The trailing linefeed is significant.
Thanks to @Martin Büttner and @FryAmTheEggman for saving a few bytes.
Try it online

CJam, 13 bytes
l~{_{}#>W%}2*

With the array inputted.
Longer version:
l~             Puts input on the stack and parse as array
  {       }    Code block
   _           Duplicate the first thing on the stack
    {}#        Finds the index of the first non-0 value in the array, puts it on the stack
       >       Slices the array from that index
        W%     Reverses the array
           2*  Does the code block twice in total

I wish I could use the fact that converting to and from a base would remove leading zeros, but it looks like it's too long.

Haskell, 29 bytes
t=f.f;f=reverse.dropWhile(<1)

Pyth, 4 bytes
.sQ0

Demo:
llama@llama:~$ pyth -c .sQ0
[0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 5, 0, 0, 0, 0]
[1, 2, 0, 3, 4, 0, 0, 5]

From Pyth's rev-doc.txt:
.s <seq> <any>
    Strip from A maximal prefix and suffix of A consisting of copies of B.

05AB1E, 4 bytes
Code:
0Û0Ü

Try it online!
Explanation:
0Û    # Trim off leading zeroes
  0Ü  # Trim off trailing zeroes

Uses CP-1252 encoding.

Jelly, 10 bytes
Uo\U,o\PTị

This doesn't use the builtin.
Uo\U            Backward running logical OR
    ,           paired with
     o\         Forward running logical OR
       P        Product
        T       All indices of truthy elements
         ị      Index the input at those values.

Try it here.

R, 43 bytes
function(x)x[cummax(x)&rev(cummax(rev(x)))]

or as read/write STDIN/STDOUT
x=scan();cat(x[cummax(x)&rev(cummax(rev(x)))])

This finds the cumulative maximum from the beginning and the end (reversed) string. The & operator converts these two vectors to logical one of the same size as x, (zeroes will always converted to FALSE and everything else to TRUE), this way it makes it possible to subset from x according to the met conditions.

Mathematica 34  27 bytes
#//.{0,a___}|{a___,0}:>{a}&

This repeatedly applies replacement rules until such action fails to provide a new output.  7 bytes saved thanks to Alephalpha.
The first rule deletes a zero at the beginning; the second rule deletes a zero at the end of the array.

#//.{0,a___}|{a___,0}:>{a}&

05AB1E, 4 bytes
0Û0Ü

Basically trimming leading then trailing zeroes of the input, given as an array.
Try it online !

Ruby, 49 44 bytes
->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}

Thanks to manatwork for chopping off 5 bytes with a completely different method!
This just drops the first element of the array while it's 0, reverses the array, repeats, and finally reverses the array to return it to the proper order.

Ouch. Now even a .drop_while() based solution would be shorter (if using 2 functions): f=->a{a.drop_while{|i|i<1}.reverse};->a{f[f[a]]}

Doh. No need for 2 functions, just some eval ugliness: ->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}.

@manatwork Not sure why I didn't think of <1, anyway. Thanks!

Perl, 19 + 1 = 20 bytes
s/^(0 ?)+|( 0)+$//g

Requires -p flag:
$ perl -pE's/^(0 )+|( 0)+$//g' <<< '0 0 0 1 2 3 4 5 6 0 0 0'
1 2 3 4 5 6

@MartinBüttner I though about the same just after hitting [Add Comment], now I just need to figure out now to let markdown save my newline in a code block

Via evil HTML hacks. ;)

17+1 bytes: s/^0 | 0$//&&redo

@Kenney That is beautiful :-) You should post that as an answer!

Thanks! My original was also 19+1 bytes but then I saw your answer which gave me an idea to shave off 2 more, so it's yours if you want it. Btw, your answer is actually 18+1 if you drop the ? as in the example - but that won't reduce "0"..

MATL, 9 bytes
2:"PtYsg)

Try it online!
Explanation
2:"     % For loop (do the following twice)
  P     %   Flip array. Implicitly asks for input the first time
  t     %   Duplicate
  Ys    %   Cumulative sum
  g     %   Convert to logical index
  )     %   Apply index
        % Implicitly end for
        % Implicitly display stack contents

Perl, 38 bytes
$\.=$_}{$\=~s/^(0\n)*|(0\n)*\n$//gs

Run with perl -p, (3 bytes added for -p).
Accepts numbers on STDIN, one per line; emits numbers on STDOUT, one per line, as a well-behaved unix utility should.
Only treats numbers represented exactly by '0' as zeroes; it would be possible to support other representations with a few more bytes in the regex.
Longer version, still to be run with -p:
    # append entire line to output record separator
    $\.=$_
}{
    # replace leading and trailng zeroes in output record separator
    $\ =~ s/^(0\n)*|(0\n)*\n$//gs
    # output record separator will be implicitly printed

Expanded version, showing interactions with -p flag:
# implicit while loop added by -p
while (<>) {
    # append line to output record separator
    $\.=$_
}{ # escape the implicit while loop
    # replace leading and traling
    $\=~s/^(0\n)*|(0\n)*\n$//gs
    # print by default prints $_ followed by
    # the output record separator $\ which contains our answer
    ;print # implicit print added by -p
} # implicit closing brace added by -p

Assuming you're running with perl -E, the -p flag usually is only counted as one byte, since there's only one extra byte different between that and perl -pE.

JavaScript (ES6), 47 bytes
a=>a.join(a="").replace(/(^0+|0+$)/g,a).split(a)

Where a is the array.

I think you need to make an anonymous function to take input: a=>a.join(a="")....

This only handles integers properly when they're a single digit

@dev-null Done.

Still returning wrong for multi-digit integers. [14] will return [1, 4].

Actually, I was (and am) still awaiting a reply to this comment. Anyway, I unfortunately don't see a way to do handle multi-digit integers using the same technique I've used for my answer and I don't think I'll be able to beat this answer anyway. I may try when I have the time, though.

Elixir, 77 bytes
import Enum
z=fn x->x==0 end
reverse(drop_while(reverse(drop_while(l,z)),z))

l is the array.
Edit:wah! copy/pasta fail. of course one has to import Enum, which raises the byte count by 12 (or use Enum.function_name, which will make it even longer).

Vitsy, 13 bytes
Vitsy is slowly getting better... (I'm coming for you Jelly. ಠ_ಠ)
1mr1m
D)[X1m]
This exits with the array on the stack. For readability, the TryItOnline! link that I have provided below the explanation will output a formatted list.
Explanation:
1mr1m
1m      Do the second line of code.
  r     Reverse the stack.
   1m   I'ma let you figure this one out. ;)

D)[X1m]
D       Duplicate the top item of the stack.
 )[   ] If the top item of the stack is zero, do the stuff in brackets.
   X    Remove the top item of the stack.
    1m  Execute the second line of code.
Note that this will throw a StackOverflowException for unreasonably large inputs.
TryItOnline!

Vitsy will get Jelly some day.

Add auto-bracket matching on EOL/EOF

JavaScript (ES6), 34 bytes
a=>a.replace(/^(0 ?)*|( 0)*$/g,'')

Input and output are in the form of a space-delimited list, such as "0 4 1 2 0 1 2 4 0".

R, 39 bytes
function(x)x[min(i<-which(x>0)):max(i)]

Four bytes shorter than David Arenburg's R answer. This implementation finds the first and last index in the array which is greater than zero, and returns everything in the array between those two indices.

Python 3, 48 bytes
lambda a:map(int,''.join(map(str,a)).strip('0'))

While it works for the given test cases, it fails if the input array contains number 10 or higher.

Brachylog, 12 bytes
{↔a₁.h>0∧}ⁱ²

Try it online!
The predicate fails in the case of "nothing".
  a₁.           Take the longest suffix of
 ↔              the input reversed
     h          the first element of which
      >0        is greater than 0
        ∧       (which is not the output).
{        }ⁱ²    Do it again.

If "nothing" has to be some actual value, like an empty list, it's only one more byte:
Brachylog, 13 bytes
{↔a₁.h>0∨Ė}ⁱ²

Try it online!
If the input can be assumed to contain only single digits, it's quite a bit shorter:
Brachylog, 6 bytes
c↔↔ℕ₁ẹ

Try it online!

Dyalog APL, 15 bytes
{⌽⍵↓⍨+/0=+\⍵}⍣2

               ⍣2     Apply this function twice:
{             }       Monadic function:
           +\⍵        Calculate the running sum.
       +/0=           Compare to zero and sum. Number of leading zeroes.
   ⍵↓⍨               Drop the first that many elements from the array.
 ⌽                   Reverse the result.

Try it here.

How about {⌽⍵/⍨×+\⍵}⍣2?

Vim 16 Keystrokes
i<input><esc>?[1-9]<enter>lD0d/<up><enter>

The input is to be typed by the user between i and esc, and does not count as a keystroke. This assumes that there will be at least one leading and one trailing zero. If that is not a valid assumption, we can use this slightly longer version: (18 Keystrokes)
i <input> <esc>?[1-9]<enter>lD0d/<up><enter>

I don't think you need to include code to allow the user to input the numbers (i and <esc>). In vim golf the golfer starts with the input already in a file loaded the buffer and the cursor in the top left corner, but the user also has to save and exit (ZZ is usually the fastest way). Then you could do something like d[1-9]<enter>$NlDZZ (13 keystrokes). Note N/n instead of /<up><enter>

ES6, 51 bytes
f=a=>a.map(x=>x?t=++i:f<i++||++f,f=i=0)&&a.slice(f,t)

t is set to the index after the last non-zero value, while f is incremented as long as only zeros have been seen so far.

Perl 6, 23 bytes
{.[.grep(?*):k.minmax]}
{.[minmax .grep(?*):k]}

Usage:
# replace the built-in trim subroutine
# with this one in the current lexical scope
my &trim = {.[.grep(?*):k.minmax]}

say trim [0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0];
# (8 1 4 3 5 6 4 1 2)
say trim [0, 4, 1, 2, 0, 1, 2, 4, 0];
# (4 1 2 0 1 2 4)
say trim [0, 0, 0, 0, 0, 0];
# ()
say trim [3, 4, 5, 0, 0];
# (3 4 5)
say trim [6];
# (6)

Retina, 11 bytes
+`^0 ?| 0$
<empty>

Quite simple. Recursively replaces zeroes at beginning and end of line.
Try it online!

PHP, 56 54 52 bytes
Uses Windows-1252 encoding
String based solution
<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));

Run like this:
echo '<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

If your terminal is set to UTF-8, this is the same:
echo '<?=preg_replace("#-( 0)+|( 0)+$#","",join($argv," "));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

Tweaks

Saved 2 bytes by negating strings and dropping string delimiters
Saved 2 bytes by using short print tag

Can you please provide an ASCII solution. Nobody can read this!

@Titus Sure. However, plenty of unreadable esolangs out there.... it's not like my answer doesn't feel right at home.

An array as first parameter of join?

@JörgHülsermann Yup. It's documented the other way around but it accepts both.

You are right I have not realize it

Wanted to point you at this: http://codegolf.stackexchange.com/questions/15715/goodbye-world-complete-obfuscation. Can you create a score 0 answer in PHP?

@Titus I have a solution, but can't post it... I voted to reopen

@Titus: it probably won't be re-opened. Here you go (Windows 1252 encoding): echo '<?="Äììçáúæ£Ôìñïç¢"^"ƒƒƒƒƒƒƒƒƒƒƒƒƒƒ";' | php;echo

Python, 84 characters
def t(A):
 if set(A)<={0}:return[]
 for i in(0,-1):
  while A[i]==0:del A[i]
 return A

You can do for i in-1,0:

I count 86 bytes.

Python 2, 69 67 bytes
def f(a):
 for i in(0,-1):
  while a and a[i]==0:a.pop(i)
 return a

You can remove the space before your tuple in the second line.

You can do for i in-1,0:

Also, you might want to recount your bytes. I count 67 as is. You can also replace [space][space]while with [tab]while. And ==0 can be <1. https://mothereff.in/byte-counter#def%20f%28a%29%3A%0A%20for%20i%20in-1%2C0%3A%0A%09while%20a%20and%20a%5Bi%5D%3C1%3Aa.pop%28i%29%0A%20return%20a

I count 67 bytes.

Javascript (ES6) 40 bytes
a=>/^(0,)*(.*?)(,0)*$/.exec(a.join())[2]

///, 20 bytes
/[0 /[// 0]/]//[0]//

Try it online!
Input as list of integers separated by spaces and surrounded by square brackets ([0 1 2 3 4 5 0]).

Pari/GP, 27 bytes
p->Vecrev(polrecip(Pol(p)))

When a list is converted to a polynomial, the leading zeros are removed. Then we can take the reciprocal polynomial, and convert it back to a list, and the trailing zeros are removed.
Try it online!

MATLAB, 38 32 bytes
@(x)x((cummax(x))&cummax(x,'r'))

Anonymous function, saved to default output variable Ans.
Tried different ideas but the simplest stayed the shortest. Also I should note that instead of cummmax you can use cumsum as well.
Unfortunately, doesn't work with Octave, because its implementation of cummax and cumsum doesn't allow for reversing the direction. For Octave alternative solution below.
How does it work?

cummax(x) takes cumulative maximal value, so everything besides leading zeros is greater than 0.
cummax(x,'reverse') does the same but in reversed direction - everything besides trailing zeros is greater than 0.
& is logical conjunction (AND) on arrays. Both numeric arrays (results of cummax functions) are transformed into logical arrays in a way that 0 is false and anything else is true.
cummax(x))&cummax(x,'reverse') gives thus logical array with true for values we need to include and false for trailing/leading zeros.
x(cummax(x))&cummax(x,'reverse')) performs logical indexing - only values where corresponding logical value is true are selected.
'reverse' can be replaced simply with 'r'

Octave, 40 bytes
@(x)x((cummax(x))&flip(cummax(flip(x))))

Try it online!
Basically the same as MATLAB solution, only cummax(x,'reverse') is replaced with flip(cummax(flip(x))) - the x is flipped, then cummax and then result is flipped.

Factor, 16 bytes
[ [ 0 = ] trim ]

Try it online!
Factor has a combinator for this. You just have to supply it with a quotation that returns t for the element(s) you want to trim.

Trilangle, 78 bytes
<>?@.#<...#)!j.(,2#_|...><.L/(,\@^_\L\.\.#\S.?S>S(.<)).7),..\._v..._|..._>#('0

Try it on the online interpreter! Output is separated by newlines.
This is some of the control flow of all time.
           <
          > ?
         @ . #
        < . . .
       # ) ! j .
      ( , 2 # _ |
     . . . > < . L
    / ( , \ @ ^ _ \
   L \ . \ . # \ S .
  ? S > S ( . < ) ) .
 7 ) , . . \ . _ v . .
. _ | . . . _ > # ( ' 0

This is definitely the most colors I've had to use in this size of grid. Let's break this down:
The first loop -- red, blue, and yellow -- ignores input until it sees something other than 0. If it reaches EOF before finding a positive value, the green path terminates the program with no output.
The next loop -- orange and yellow-green -- counts how much input there is after the first positive number.
The third loop -- cyan and brown -- removes zeroes from the end of the array and decreases the counter as it goes.
The final loop -- gray and red-violet -- prints out what's left. The purple branch terminates the program once it's exhausted the list.

PowerShell, 49 bytes
($args[0]-join',').trim(',0').trim('0,')-split','

Takes input $args[0] and -joins them together with commas to form a string. We then use the .Trim() function called twice to remove first the trailing and then the leading zeros and commas. We then -split the string on commas back into an array.

Alternate version, without using conversion
PowerShell, 81 bytes
function f{param($a)$a=$a|%{if($_-or$b){$b=1;$_}};$a[$a.Count..0]}
f(f($args[0]))

Since PowerShell doesn't have a function to trim arrays, we define a new function f that will do half of this for us. The function takes $a as input, then loops through each item with a foreach loop |%{...}. Each iteration, we check a conditional for $_ -or $b. Since non-zero integers are truthy, but $null is falsey (and $b, being not previously defined, starts as $null), this will only evaluate to $true once we hit our first non-zero element in the array. We then set $b=1 and add the current value $_ onto the pipeline. That will then continue through to the end of the input array, with zeros in the middle and the end getting added onto the output, since we've set $b truthy.
We encapsulate and store the results of the loop all back into $a. Then, we index $a in reverse order (i.e., reversing the array), which is left on the pipeline and thus is the function's return value.
We call the function twice on the $args[0] input to the program in order to "trim" from the front, then the front again (which is the back, since we reversed). The order is preserved since we're reversing twice.
This version plays a little loose with the rules for an input array of all zeros, but since ignoring STDERR is accepted practice, the program will spit out two (verbose) Cannot index into a null array errors to (PowerShell's equivalent of) STDERR and then output nothing.

Mathematica, 33 bytes
#/.{Longest[0...],x__,0...}->{x}&

jq, 48 characters
. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]

Sample run:
(Command line option -c only used in this sample for readability to avoid pretty printing the result.)
bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 4, 1, 2, 0, 1, 2, 4, 0]'
[4,1,2,0,1,2,4]

bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 0, 0, 0, 0, 0]'
[]

On-line test:

[0, 4, 1, 2, 0, 1, 2, 4, 0]
[0, 0, 0, 0, 0, 0]

Groovy, 43 characters
{x={it.dropWhile{it<1}.reverse()};x(x(it))}

Sample run:
groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 4, 1, 2, 0, 1, 2, 4, 0])
===> [4, 1, 2, 0, 1, 2, 4]

groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 0, 0, 0, 0, 0])
===> []

sed, 24 bytes
#!/bin/sed -f
:
s/ 0$//
s/^0\b \?//
t

Input as space-separated words on stdin.
It cost me five bytes (\b \?) to deal with the special case of all zeros.
Test results
$ ./71877.sed <<EOF
0 0 0 8 1 4 3 5 6 4 1 2 0 0 0 0
0 4 1 2 0 1 2 4 0
0 0 0 0 0 0
3 4 5 0 0
6
EOF
8 1 4 3 5 6 4 1 2
4 1 2 0 1 2 4

3 4 5
6

PHP, 30 bytes
<?=trim(join(' ',$argv),' 0');

Needs to be saved in a file called '0' (or any number of 0s). Works with all test cases (which are <10 at time of submission) but if a test case with a final non 0 integer of 10 (or any other integer with a 0 units digit) gets added then it will no longer be valid.
use like:
php 0 0 4 1 2 0 1 2 4 0

Where the first 0 is the file name and the rest is the input
A bunch of answers got added between me loading the challenge and submitting this. I'd delete it but I never finished the account sign up, would a mod do so please?

C#, 134 bytes
using System.Linq;n=>string.Join(" ",n).Trim('0',' ').Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(s=>int.Parse(s));

If I can return a comma separated string of the return values:
C#, 36 bytes
n=>string.Join(",",n).Trim('0',',');

PHP, 61 bytes
<?=preg_replace("^[^_]*_(0_)*(.*)(_0)*$","$2",join(_,$argv));

regexp using the underscore as delimiter.

<?=preg_replace("#^[^_]*_(0_)*(.*?)(_0)*$#","$2",join(_,$argv)); works better for $argv=["t.php",0, 4, 1, 2, 0, 1, 2, 4, 0]; or you should take <?=preg_replace("^[^_]*_(0_)*(.*?)(_0)*$","$2",join(_,$argv)); instead

PHP, 41 Bytes
<?="[".trim(join(",",$_GET[a]),",0")."]";

If the input as array could be write as ?a=0&b=0 and so on it can be reduce to 38 Bytes
<?="[".trim(join(",",$_GET),",0")."]";

The longer way working with Regex 65 Bytes
<?="[".preg_replace("#^(0,)*|(,0)*$#","",join(",",$_GET[a]))."]";

Invalid, consider input: 0 10, output [1]

@aross in the question is to read non-negative integers like this: followed with no integer greater then 9. let me remenber you to your own opinion at http://codegolf.stackexchange.com/questions/94832/yes-of-course-im-an-adult/94842#94842 You are right if there could been an integer greater then 10 my answer is not valid

The other challenge explicitly specified a range of input. Though I only just realized that this challenge doesn't clarify that (someone asked about it on OP). Usually it's safe to assume that there's no limit if none is posted though...

Normally this would be considered optimizing for the specified test-cases which is a loophole.

05AB1E, 2 bytes
Built-in version. :)
0Ú

Try it online!

Jellyfish, 22 bytes
p
\A2
~R
(#
~*
\
/
+
i

Try it online!
Explanation
p   print the result of:
\A2 repeat the following twice:
~R  compose reverse with the below
(#  filter the elements of the input by the following function:
~*  compose sign with:
\   map each prefix to:
/    fold by:
+    addition
i   evaluated input

AWK, 24 bytes
gsub(/^(0 )*|( *0)*$/,e)

Try it online!
Using a convenient input to awk's default field separator (space). No easy way to define an array here.
This substitutes every match to the regex /^(0 )*|( *0)*$/ for a null string (variable e, not defined). Even if there are no trailing zeros, null matches are found before and after the input, so gsub() always returns a positive number, and the input (modified or not) is printed.

Python 2/3, 48 bytes
lambda x:map(int,''.join(map(str,x)).strip('0'))

Try it online!

Realized after posting that Adam Abahot posted an identical answer (excluding the name)

Japt -h, 6 bytes
ã fÎfÌ

Try it
2Æ=Ôf|

Try it

TypeScript's Type System, 69 bytes
type T<R>=R extends[...infer K,0]?T<K>:R extends[0,...infer K]?T<K>:R

TypeScript Playground
Explanation
By using infer, we can take out portions of the array that don't start or end in 0 recursively:
type T<R> =
    R extends [...infer K, 0] ? T<K> : // take out trailing zeros
    R extends [0, ...infer K] ? T<K> : // and leading zeros
    R; // if none are left, return the final array.

Since we use extends, we don't need to bind the input parameters to a type (e.g. using T<"input"> simply returns "input")

JavaScript (Node.js), 58 bytes
Not the best JS answer, but a different approach not using regexp, replace, nor filter.
(Like other answers, we assume that the array input can only contain integers <= 9)
t=>(r=(g=a=>[...""+a.reverse().join``*1])(g(t)))[0]*1?r:[]

Try it online!

Converts the array into a number to get rid of the leading zeros.

Then we do this a second time on the reversed array to get rid of the leading (previously trailing) zeros, and reverse back again to get the answer array in the correct order.

The case were the array contains only zeros had to be specifically handled (or else it would have resulted in a [0] output), and this part has a cost of 14 bytes :(

Python 3, 48 55 29 26 bytes
print(input().strip('0 '))

Input and output is taken as space-separated numbers, eg:
0 0 0 1 3 1 4 0 1 3 6 4 5 19 3 1 4 0

Alternatively, a 29-byte Python 2 solution:
print raw_input().strip('0 ')

This chops off trailing 0s from numbers divisible with 10: python3 -c "print(input().strip('0 '))" <<< '0 2000 0'.

Racket 73 bytes
(λ(l)(define(g k)(if(= 0(car k))(g(cdr k))k))(reverse(g(reverse(g l)))))

Ungolfed:
(define f
  (λ(l)
    (define (g k)                     ; fn to remove leading zeros;
        (if(= 0 (first k))
           (g (rest k))
           k))
    (reverse (g (reverse (g l))))))

Last line removes leading 0s in original and reversed list. List is re-reversed to get original order.
Testing with different combinations:
(f '(0 0   2 5 0 6 8 9   0 0))
(f '(0 0 0 2 5 0 6 8 9   0 0 0))

(f '(0 0 0 2 5 0 6 8 9   0 0))
(f '(0 0   2 5 0 6 8 9   0 0 0))

(f '(0 0   2 5 0 6 8 9))
(f '(0 0 0 2 5 0 6 8 9))

(f '(2 5 0 6 8 9   0 0))
(f '(2 5 0 6 8 9   0 0 0))

(f '(2 5 0 6 8 9))

Output:
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)

PHP, 144 126 chars

-18 chars thanks to @manatwork

It's a bit longer than the other PHP answers because it's array-based.
function e($a){foreach($a as$i=>$v){if($v)break;unset($a[$i]);}return array_reverse($a);}print_r(e(e(explode(",",$argv[1]))));

Call like this: php remove0.php 0,4,2,1,0,1,2,4,0
Example return:
Array
(
    [0] => 4
    [1] => 2
    [2] => 1
    [3] => 0
    [4] => 1
    [5] => 2
    [6] => 4
)

Rearranged it a bit to reduce it to 126 characters, without changing the logic: http://pastebin.com/HMSGfftE

@manatwork thanks, changed it.

According to discussion in Running PHP with -r instead of code tags and Is the PHP opening tag mandatory in byte count?, running code with php -r is acceptable, so no need the <?.

@manatwork Thanks, changed it ^^

JavaScript (V8), 54 bytes
s=>(g=a=>a.filter(e=>e^k?k=1:k,k=0).reverse(),g(g(s)))

Try it online!
JavaScript (V8), 52 bytes
f=(s,q=f(s,s))=>q.filter(e=>e^k?k=1:k,k=0).reverse()

Try it online!

Vyxal, 2 bytes
0P

Try it Online!
What it says on the box. StriPs 0s.

AKA "cyclops sticking its tongue out"

C (gcc), 80 78 bytes
-2 bytes thanks to ceilingcat by using strlen() and indexing into the string
p;f(char*s){for(;*s&&*s<49;s++);for(p=strlen(s);p&&s[p]<49;s[p--]=0);puts(s);}

Try it online!

Julia 1.0, 15 bytes
~x=strip(x,'0')

Try it online!
Accepts a String input.

BQN, 10 bytes
⌈`∘×⊸/∘⌽⍟2

Anonymous tacit function; takes a list, returns a list. Try it at BQN online!
Explanation
⌈`∘×⊸/∘⌽⍟2
      ∘⌽    Reverse the list; then,
    ⊸/      select the elements matching the 1s in the following list:
   ×         Get the sign of each number in the list (0 or 1)
⌈`∘          Scan by maximum: preserves leading 0s, but turns all others into 1s
            All but the leading run of zeros is therefore kept
        ⍟2  Do this twice

Python 3, 101 bytes
def f(l,n,a=0):
 while l[a]==0:
  del l[a];a+=1;n-=1
 a=n-1
 while l[a]==0:
  del l[a];a-=1
 return l

Try it online!

ReRegex, 21 bytes
\[0,?/[/,?0]/]/#input

A very simple solution consisting of two regexes, each stripping 0's from the start and end respectively.
Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Fill the holes in letters
Sometimes when I'm bored, I take some text and fill the "holes" in the letters. But isn't filling the holes the most boring thing you can do? I think we should automate it, so we could use our time better.
Standard code-golf rules apply.
Input
A string containing sequence of alphanumeric characters (a-z, A-Z, 0-9) and spaces.
Output
Image containing string rendered and holes on it filled. You can use any human readable font as long as it still requires filling the holes. You can either save image to file i.png (in png format) or just display the image.
Image properties:

Black text
White or transparent background
Padding:

The dimensions of the image can be maximum two times the dimensions of the text
Padding should be same color as background, either white or transparent

Example
Input: Example text
Output:

Related. (same challenge, different scoring.)

Is there a minimum font size for the letters (in pixels)?

Yes, lets say it is 12px

Bash, 135 bytes
convert +antialias -pointsize 99 label:$1 -fill red -draw 'color 0,0 floodfill' -fill black -opaque white -fill white -opaque red i.png

Uses ImageMagick (convert).
Sample output:

convert
  +antialias                              # disable antialiasing
  -pointsize 99                           # annoyingly necessary (see below)
  label:$1                                # draw input text
  -fill red -draw 'color 0,0 floodfill'   # flood fill from (0,0) with red
  -fill black -opaque white               # replace all white with black
  -fill white -opaque red                 # replace all red with white
  i.png

Disabling antialiasing is required because otherwise antialiased interior parts of the letters wouldn't flood fill. Setting the font to a large size is also required because some fonts have "gaps" in letters that should have "holes" in them at small font sizes (in my tests, the a wasn't filled at the default small font size).

Mathematica, 83 bytes
ImageSubtract[s=Binarize@Rasterize@Style[#,FontSize->99],DeleteBorderComponents@s]&

An unnamed function that takes a string as input and returns an image object. The idea is to use DeleteBorderComponents to keep only the holes and then subtract those from the original image.

The funny thing is that Mathematica wins often even with long builtin names like ImageSubtract and DeleteBorderComponents.

That's because Mathematica has builtin names for many things - you don't need to create your own functions often.

SmileBASIC, 38 bytes
??INPUT S$GPUTCHR.,2,S$,2,2,8GPAINT.,0

Draws black* text on the black background, then uses the built in "paint bucket" function to fill everything outside the text with white.
*(actually I used 00000008, which looks identical to transparent, but is treated as a different color)

Eats away at the text a bit, but there's also a canvas-based solution:
JS, 610 bytes
function o(a,b){return a[b]+a[b+1]+a[b+2]}x=prompt();l=x.length;c=document.createElement("canvas");document.body.appendChild(c);h=33;w=18*l;c.height=h;c.width=w;n=255;m=764;t=c.getContext("2d");t.fillStyle="white";t.fillRect(0,0,w,h);t.fillStyle="red";t.fillRect(0,2,w,h);t.font="900 30px Courier";t.fillStyle="black";t.fillText(x,0,25);d=t.getImageData(0,0,w,h);f=0;q=d.data.length;for(i=0;i<20;i++){for(j=0;j<q;j+=4){f=d.data;if(o(f,j)>0&&(o(f,j-w*4)>m||o(f,j+w*4)>m||o(f,j-4)>m||o(f,j+4)>m)){f[j]=n;f[j+1]=n;f[j+2]=n}}}for(k=0;k<q;k+=4){f=d.data;if(f[k+1]<1){f[k]=0;f[k+1]=0;f[k+2]=0}}t.putImageData(d,0,0)

Postscript 273
[was originally posted to the related challenge, but I never implemented the counting.]
Renders each character normally, to get the correct spacing to advance, then takes all the curves which describe the glyph and fills each one. Normally the interior and exterior curves are described with different orientations, so a fill will leave the interior empty, regardless of whether it's using the non-zero winding rule or even-odd rule. Filling separately, it all gets filled.
/Courier 9 selectfont
9 9 moveto{( ) dup 0 4 3 roll put currentpoint 3 2 roll
dup show currentpoint 3 2 roll 5 3 roll moveto
true charpath[[{/moveto
cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[}pathforall
pop]]{exec currentpoint fill moveto}forall pop moveto}forall

Indented:
/Courier 9 selectfont
9 9 moveto
{
    ( ) dup 0 4 3 roll put
    currentpoint 3 2 roll
    dup show
    currentpoint 3 2 roll
    5 3 roll moveto
    true charpath
    [ [{/moveto cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[}
       pathforall pop] ]
    { exec currentpoint fill moveto } forall
    pop moveto
} forall

Usage. String object is expected to be on the stack when the program starts. Extra scaling just to make it visible.
$ gs -c '7 7 scale(Example Text)' -f courier.ps

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


text:
ADFGX Cipher Encryption
ADFGX cipher encryption
The ADFGX cipher was used by the German army in WWI. Write a program to encipher with it!
It works as follows:

Create a 5x5 Polybius square with a mixed alphabet. The polybias square is labled A D F G X along the top and left.
Generate the pairs, so A in its non-mixed position is AA, B is AD and so on.
Perform columnar transposition using the columnar key.
Output the ciphertext.

Rules

Your program should either define a function that accepts the arguments of the mixed alphabet and the columnar transposition key, in that order, or accept the alphabet/key as command-line arguments. You can also get input from STDIN.
Standard loopholes apply.
You can't use a pre-written columnar transposition library (or, for that matter, ADFGX) - i.e. no running something like import cipherpack.

Scoring
This is code-golf, so shortest code (in bytes) wins!
Test cases
My example runs used a failed source. I'll do some more later.
Leaderboard
Run the Stack Snippet to generate a leaderboard.

/* Configuration */

var QUESTION_ID = 71997; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 50171; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

Note:
It is not necessary to split the output into groups of five.

Wouldn't B in its non-mixed position be AD, not AB?

Also, does it need to be case insensitive or can we assume all input is in uppercase? Could we have some test cases?

Also, you never specified where the actual message to encipher comes in the input. Does it come first (before the alphabet and the key) or last (after them)?

Do we need to separate the ciphertext into groups of five?

@Doorknob Yes, I've updated the question. I'll do some test cases when I'm on my PC.

@ThomasKwa No, I've added a note.

Pyth, 26 bytes
seMhDC,Q.TcsXwz^"ADFGX"2lQ

For this, the second line (columnar key) needs to be in quotes, which is acceptable by default.
Try it here.

Pyth, 36 34 33 32 31 bytes
JwseMhDC,J.Tcsm@^"ADFGX"2xzdwlJ

Jw                                assign (z, J) to 2 lines of input
              m             w     map over each char of a 3rd input line...
                ^"ADFGX"2         generate ['AA', 'AD', 'AF', ...]
                         xzd      find the index of this char in z
               @                  index into ^^ with ^
             s                    join groups of 2 ch. into one string
            c                lJ   split ^ into groups of len(J) chars
          .T                      transpose
       C,J                        pair elems up with chars of J
     hD                           sort by chars of J (the key)
   eM                             get rid of the chars of J now
  s                               join

Thanks to Thomas Kwa for a byte!
Sample run, using the example from Wikipedia:
llama@llama:~$ pyth -c 'JwjdeMhDC,J.Tcsm@^"ADFGX"2xzdwlJ'
BTALPDHOZKQFVSNGJCUXMREWY
CARGO
ATTACKATONCE
FAXDF ADDDG DGFFF AFAX AFAFX

Sorry for posting a similar solution, and thanks for linking to the test case.


text:
Read a retro display
Art stolen from What size is the digit?

7-segment digits can be represented in ASCII using _| characters. Here are the digits 0-9:
 _     _  _       _   _  _   _   _
| | |  _| _| |_| |_  |_   | |_| |_|
|_| | |_  _|   |  _| |_|  | |_|  _|

Your job is to parse the art into normal numbers.
Notes on numbers

Each digit has a different width.

1 has a width of 1
3 and 7 are 2 wide
245689 and 0 are all 3 wide

Also between each digit is one char of padding. Here is the full char set:

 // <-- should be one space, but SE formatting messed it up
|
|
-------------
 _
 _|
|_
-------------
_
_|
_|
-------------

|_|
  |
-------------
 _
|_
 _|
-------------
 _
|_
|_|
-------------
_
 |
 |
-------------
 _
|_|
|_|
-------------
 _
|_|
 _|
-------------
 _
| |
|_|

Input
Input can be either from the console or as a string arg to a function.
Output
Output is either put to the console or is returned from the function.
Examples:
  _  _   _
|  |  | |_
|  |  | |_|
1776

 _   _     _
 _| | | | |_
|_  |_| | |_|
2016

   _       _
| |_| |_| |_
|  _|   |  _|
1945

   _   _   _   _   _   _
| | | | | | | | | | | | |
| |_| |_| |_| |_| |_| |_|
1000000

 _     _  _       _   _  _   _   _
| | |  _| _| |_| |_  |_   | |_| |_|
|_| | |_  _|   |  _| |_|  | |_|  _|
0123456789

This is code-golf so shortest byte count wins!

Related

I am interested in learning about the best algorithms to solve this kind of problem, and I'm having difficulty learning from the answers here (they're good, just very concise).  Is there a place you can refer me to see more lengthy explanations, preferably with pictures?

Well, The way mine works is fairly simple. It transposes the list and loops over it. It then splits on empty lines. Each number is checked against a fingerprint table for each number. The others work a bit like mine, except instead of a fingerprint table they basically have a hash table they use.

Is there a more general name for this type of problem in computer science?

I have no idea ;)

Pyth, 33 30 bytes
sm@."/9Àøw"%%Csd409hTcC.z*3d

Here's the idea: Once we transpose the input, and split into digits, we can sort of hash the individual digit strings and assign them to their values.
sm@."/9Àøw"%%Csd409hTcC.z*3d     Implicit: z=input
                      C.z        Transpose input.
                     c   *3d     Split that on "   ", a space between digits.
 m@."/9Àøw"%%Csd409hT            Map the following lambda d over that. d is a digit string.
             Csd                   Flatten the digit string, and convert from base 256.
            %   409                Modulo that by 409
           %       hT              and then by 11. All digits go to a distinct num mod 11.
   ."/9Àøw"                        The compressed string "03924785/61".
  @                                Index into that string.
s                                Flatten and implicitly output.

Try it here.

Cool, basically looks like my approach but far shorter!

@Lynn Sorry about that; there's basically one shortest way to do this in Pyth.

Ruby, 184 bytes
a=0
l=$<.map{|x|x.bytes.map{|y|y==32?0:1}+[0]*2}
(0..l[0].count-1).map{|i|l[0][i]+2*l[1][i]+4*l[2][i]}.each{|x|
x>0?(a=x+2*a):(p Hash[[40,6,32,20,18,26,42,8,44,64].zip(0..9)][a];a=0)}

Explanation

takes the input from stdin
converts the strings to binary sequences, 1/0 for segment on/off
encodes columns to 3bit binary number
encodes sequences of 3 bit numbers to 9 bit numbers, use '0' columns as stop symbols
use a lookup table to convert the 9 bit numbers to digits

This is my first code-golf. Thanks for the fun!

Welcome to PPCG! Very nice job on your first post!

Japt, 119 bytes
Ur"[|_]"1 z r" +
"R x1 qR² £"11
1 1
1151151
111
 15111
115 1
 1
115 1
111
1511
111
15  1
11511
111
115 1
111
11"q5 bXÃq

Try it here!
Oh geez, this one's really long. I don't think I have finished golfing.
Explanation
Preparation
We take the input and convert any |_ to 1. Then we transpose, strip out ending spaces, and split along double-newlines.
Translation
We map over the resulting array and find the index where the form appears in a reference array. Here's a diagram to help:
MAPITEM
  11
  1 1 --> This same form appears at index 0 in the reference array
  11                            |
                                |
                                V
                        change the mapitem to 0!

After that, we join the array of numbers and output!
NOTE: You may be wondering why we have to change each art character to a series of 1's. This is because there seems to be a bug (or something like that) which doesn't let me store the characters as is with |_.

I noticed the _ bug, but I don't know what caused it.

OK, "\n\n" can be replaced with R², and "\\||_" with "%||_". I think you could also save some bytes by encoding the long string in base 4 (changing each of the 4 disinctive chars to 0, 1, 2, or 3, padding to a length of a multiple of 4, then running r"...."_n4 d} over it), but for some reason, I haven't gotten this to work yet.

Python2, 299 261 244 bytes
s=lambda a,i=0:[a]if i==len(a[0])else[[j[:i]for j in a]]+s([j[i+1:]for j in a])if all(j[i]==' 'for j in a)else s(a,i=i+1)
p=lambda l:['95572431508448853268'.find(`sum(ord(c)**i for i,c in enumerate("".join(n)))%108`)/2for n in s(l.split('\n'))]

I really liked this challenge, good job !
Explanation
The function s takes the three lines as input, it tries to find a digit separation (all characters are spaces). When such a separation is found it calls s with the rest of the three lines and add the value returned by the call to the three lines that compose the digit. If there is no separation it means there is only one digit.
The function p is the entry point so it takes a string that represent the digits. The digits are stored as a "hash" computed with sum(ord(c)**i for i,c in enumerate("".join(n)))%108 to save space (thanks to other answers !).
Exemple
digits="""
 _     _
| | |  _|
|_| | |_ """[1:]  # remove the '\n' at the beginning

p(digits)  # [0, 1, 2]

Other versions
261 bytes (py3):
s=lambda a,i=0:[a]if i==len(a[0])else[[j[:i]for j in a]]+s([j[i+1:]for j in a])if all(j[i]==' 'for j in a)else s(a,i=i+1)
def p(l):[print([91,21,84,31,58,76,88,41,80,68].index(sum(ord(c)**i%20 for i,c in enumerate("".join(n)))),end="")for n in s(l.split('\n'))]

249 bytes, this one transpose the lines (py2):
f="".join
s=lambda a,i=0:[a]if i==len(a)else[a[:i]]+s(a[i+1:])if all(c==' 'for c in a[i])else s(a,i=i+1)
h=lambda s:ord(s[0])**len(s)+h(s[1:])if s else 0
p=lambda l:["10220907112527153129".index(`h(f(map(f,n)))%34`)/2for n in s(zip(*l.split('\n')))]

Pyth, 39 bytes
sm@"413-928-506--7"%%Crd6C\524cjbC.z*3d

This seems to work? Try it online.

JavaScript (ES6), 169 bytes
a=>[...(a=a.split`
`)[0]].map((b,c)=>(d={' ':0,'|':1,'_':2})[b]+d[a[1][c]]*2+d[a[2][c]]).join``.split(0).map(b=>[343,3,182,83,243,281,381,23,383,283].indexOf(+b)).join``

Starts by splitting into three lines, remapping each column into a value, and then building a unique identity for each column from those values. It then splits by 0 (the identity for the space between columns), and finally maps each identity to it's number values, which it concatenates and outputs.

Very nice! I wish python had a list split function...

@JAtkin I joined into a string so that I could split it. I believe you could do that in Python as well?

Python 3, 281 254 bytes
Edit
I just looked at the code for the other python answer and noticed that much of the code is similar. This was arrived at independently.
(newlines added for "readability")
def p(i):
 n=[[]]
 for l in zip(*i.split('\n')):
  if all(i==" "for i in l):n+=[[]]
  else:n[-1]+=l
 return''.join(map(lambda l:str([''.join(l[2:])==x for x in
             "|_ _ ||,|,|___ | ,_ ||,  _  ||, ___  |,|___  |,  ||,|___ ||, ___ ||"
                     .split(',')].index(1)),n))

Ungolfed:
def parse(input):
    lines = list(input.split('\n'))
    numbers = [[]]
    for lst in zip(*lines):
        if all(i==" " for i in lst):
            numbers += [[]]
        else:
            numbers[-1] += lst
    return ''.join(map(digit, numbers))

def digit(num):
    fingerprint =
        "|_ _ ||,|,|___ | ,_ ||,  _  ||, ___  |,|___  |,  ||,|___ ||, ___ ||".split(',')
    return str([''.join(num[2:]) == y for y in fingerprint].index(True))

Tests:
assert (parse("   _   _   _   _   _   _ \n| | | | | | | | | | | | |\n| |_| |_| |_| |_| |_| |_|") == '1000000')
assert (parse("   _       _ \n| |_| |_| |_ \n|  _|   |  _|") == '1945')
assert (parse(" _   _     _ \n _| | | | |_ \n|_  |_| | |_|") == '2016')
assert (parse(" _     _  _       _   _  _   _   _ \n| | |  _| _| |_| |_  |_   | |_| |_|\n|_| | |_  _|   |  _| |_|  | |_|  _|") == '0123456789')
assert (parse("  _  _   _ \n|  |  | |_ \n|  |  | |_|") == '1776')

How it works
(Note: I am explaining the ungolfed program here since it is more readable and it has the exact same code, with the exception that the digit function is in-lined into a lambda)
def parse(input):
    lines = list(input.split('\n'))
    numbers = [[]]

The main function is parse. It first splits the input into lines and creates the numbers array.
    for lst in zip(*lines):
        if all(i==" " for i in lst):
            numbers += [[]]
        else:
            numbers[-1] += lst

This is my favorite part (since it took so long to figure out). Here we zip the lines so we can basically vertically traverse the input. When the line has chars on it we add it to the last number in the numbers array. If it does not have any chars on it we add a new number to the array.
    return ''.join(map(digit, numbers))

Really simple, numbers is mapped with the digit function and is converted to a string.
def digit(num):
    fingerprint =
        "|_ _ ||,|,|___ | ,_ ||,  _  ||, ___  |,|___  |,  ||,|___ ||, ___ ||".split(',')
    return str([''.join(x[2:]) == y for x, y in zip([num]*10, fingerprint)].index(True))

This is (fairly) simple. fingerprint is the string representation of the digits created above minus the first 2 chars (this was the smallest fingerprint I could find). We return the index of the first match.

Haskell, 270 207 bytes
Don't be too hard, this is my first ever haskell program ;) I'm almost certain this can be golfed further, but I don't know how given my limited knowledge of the language.
import Data.Lists
b n=map c$splitOn["   "]$transpose$lines n
c n|e<-drop 2$concat n,Just r<-elemIndex True[e==f|f<-splitOn",""|_ _ ||,|,|___ | ,_ ||,  _  ||, ___  |,|___  |,  ||,|___ ||, ___ ||"]=(show r)!!0

Ungolfed:
module Main where
import Data.Lists

main :: IO ()
main = print $ parse " _     _  _       _   _  _   _   _ \n| | |  _| _| |_| |_  |_   | |_| |_|\n|_| | |_  _|   |  _| |_|  | |_|  _|"

parse :: String -> String
parse n = let lst = transpose $ lines n
              numbers = splitOn ["   "] lst --"   " lst
              number = map digit numbers
          in number

digit :: [String] -> Char
digit n | e <- drop 2 $ intercalate "" n
        , fingerprint <- ["|_ _ ||","|","|___ | ","_ ||","  _  ||"," ___  |","|___  |","  ||","|___ ||"," ___ ||"]
        , Just res <- elemIndex True [e == finger | finger <- fingerprint]
        = head $ show res

Big thanks to @nimi for the tips!

bad news first: I'm afraid you have to include the import Data.List in your byte count. Good news: a) if you have Data.Lists installed you can import it instead and replace a with splitOn: ...map c$splitOn["   "]$transpose... and ...f<-splitOn",""|_.... b) intercalate "" n is concat n or id=<<n. c) replace res with a single letter name.  d) use pattern guards instead of let ... in: c n|e<-drop 2$id=<<n,Just r<-elemIndex ... ]=(show r)!!0.

Hehehe, Whoops! The import was lost in the copy/paste ;) Thanks for all the tips!

@nimi Sorry to bother you about it, but do you mind explaining what =<< does? Neither the hoogle docs or the type signature are very helpful to me.

=<< in list context is concatMap, i.e. it maps the given function over the list and combines the results into a single list. >>= does the same but with the arguments flipped. id =<< n (or n >>= id) maps the identity function over the list (of lists), i.e. does nothing with the sublists and the concatenates them. So it's the same as concat.


text:
Quotient in base 31 numeral system
You're given two numbers a and b in base 31 numeral system and number k with no more than 10000 decimal digits. It is known that b is divisor of a. The task is to find last k 31-based-digits of quotient a/b.
The solution with fastest proved asymptotics in length of max(a,b) wins. I'll put a bound of 10^5 on length of a and b.
Test example:
INPUT: a = IBCJ, b = OG, k = 5
OUTPUT:  000N7

Welcome to Programming Puzzles & Code Golf! This site is for programming contests and challenges, not general programming questions. Yours might be on-topic on [programmers.se] or [cs.se], but be sure to read their help centers to make sure your question is high in quality and on-topic there. Thanks!

@Doorknob I've changed the statement so that it should satsify the rules.

"There isn't just one input so one may be O(n) in a but O(n^2) in k, and another solution may be the other way around. Which one wins?" - @trichoplax. As it stands, I don't think that the winning criteria is clear enough. Take a look at the tag wiki too for info on the fastest-algorithm tag.


text:
How many words of power did I shout?
In Skyrim, the player character can use powerful magic shouts (Thu'ums) to achieve their goals. Every shout consists of three words, however, the player can use the first one or two words to achieve the same effect with less power but at a shorter cooldown.
Given a lowercase ASCII Thu'um phrase without punctuation or spaces, return how many words of power it contains.
Example:
fusrodah   -> 3
dur        -> 1
kaandrem   -> 2
odah       -> 2
vengaarnos -> 3

The input will always be a lowercase ASCII string formed by taking one of the shouts below, choosing the first 1, 2, or 3 words from that shout, and concatenating the words in order.
dur neh viir
faas ru maar
feim zii gron
fo krah diin
fus ro dah
gaan lah haas
gol hah dov
hun kaal zoor
iiz slen nus
joor zah frul
kaan drem ov
krii lun aus
laas yah nir
lok vah koor
mid vur shaan
mul qah diiv
od ah viing
raan mir tah
rii vaaz zol
strun bah qo
su grah dun
tiid klo ul
ven gaar nos
wuld nah kest
yol toor shul
zul mey gut
zun haal viik

So fus, fusro, and fusrodah are all valid inputs, but fusroviir isn't because it uses words from mixed shouts, and rodah isn't because it's not a prefix of a shout. You also don't have to handle the empty string input.

Shortest code in bytes wins.

I will give a cookie for the first person to run this algorithm on each line of the Song of the Dragonborn (known as the "skyrim theme" by plebs)

Retina, 78 42 15 14 bytes
ul
xo
[aeiou]+

Try it online
tiidkloul is the only word that doesn't have the same amount of vowel sequences as the number supposed to be printed. Therefore we need to match the word to give it an extra vowel sequence. ou will only match tiidkloul and we can then replace ou with oxo which creates the extra sequence.
My initial approach wasn't this simple, but was build around removing all consonants, then removing a few vowel sequences (ai|ii|aa|...) and then finally counting the numbers of letters. But thanks to @Martin Büttner for thinking of [aeiou]+ instead.

Returns 3 for fusroviir, which was explicitly listed as invalid input.

@atk I asked OP if their would be invalid input. The answer was no.

Retina, 313 bytes
ah|aus|bah|d(ah|ii[nv]|ov|rem|u[nr])|[fhl]aas|f(eim|o|rul|us)|g(aa[nr]|ol|rah|ron|ut)|haal|hah|hun|iiz|joor|k(aa[ln]|est|lo|oor|rah|rii)|lah|lok|lun|m(aar|ey|i[dr]|ul)|n[ae]h|nir|n[ou]s|od|ov|qah|qo|r(aan|ii|o|u)|s(haan|hul|len|trun|u)|tah|tiid|toor|ul|v(aaz|ah|en|iin?[gkr]|ur)|wuld|yah|yol|z(ah|ii|[ou][ln]|oor)

Try it online!
Based on a few simple observations:

All words are unique, regardless of their position.
No word is a prefix of another word.
The input is guaranteed to be valid.

That means we can simply count how many of words appear in the string without overlap. That's exactly what a regex does. I've tried compressing the regex a little beyond just concatenating all the words with | (which would be 351 bytes), but I'm sure this is far from optimal. For a start, I've definitely not exploited all common parts optimally. But more importantly, it's possible to compress the string even further by making it match more strings than valid words, as long as those can't accidentally match part of a valid word (because then they'll just never be matched). I'm pretty sure one would have to automate the compressing to really be sure it's optimal.

Martin Büttner got outgolfed? Everyone get in your bunkers, the end is nigh!

@Cyoce it's okay, I golfed two thirds off that other answer. ;)

Perl 5, 28 bytes
Byte count includes one for -p.
s/ou/oxo/;$_=()=/[aeiou]+/g

Stolen straight from dev-null. (Thanks, dev-null!)


text:
How drunk am I and when can I drive again?
It's weekend and what are the cool guys doing on weekends? Drinking of course! But you know what's not so cool? Drinking and driving. So you decide to write a program that tells you how loaded you are and when you are gonna be able to drive again without getting pulled over by the cops and loosing your license.
The Challenge
Given a list of beverages you enjoyed this evening, calculate your blood alcohol level and the time you have to wait till you can hop into your car and get home.
Input
Input will be a list of drinks you had this night. This will look like this:

4 shots booze
1 glasses wine
2 bottles beer
3 glasses water

Containers will always be plural.
As you can see each entry consists of:

The type of drink (booze, wine, beer, water)
The container for the drink (shots, glasses, bottles)
The amount x of the drinks you had of that type as integer with x > 0,

Each drink type adds a certain amount of alcohol to your blood:

booze ->  0.5 ‰ / 100 ml
beer  ->  0.1 ‰ / 100 ml
wine  ->  0.2 ‰ / 100 ml
water -> -0.1 ‰ / 100 ml

Water is the exception here, since it thins your blood out and lowers your alcohol level (would be so nice if that actually worked...).
Each container has a certain volume:

shots   -> 20 ml
glasses -> 200 ml
bottles -> 500 ml

Output
You have to output two numbers:

The alcohol level in ‰
The time in hours you have to wait until you reached 0.5 ‰ or less, so you can drive again. You loose 0.1 ‰ per hour.

Notes

The alcohol level can never fall below zero.
Same goes for the waiting time. If you have 0.5 ‰ or less, output zero.
The order of drinks does not matter, so drinking water may lower the alcohol level below zero in the process of the calculation. If it remains there, you need to replace it with zero.

The alcohol level for the the example above would be calculated like this:

4 shots booze   -> 0.4 ‰
1 glasses wine  -> 0.4 ‰
2 bottles beer  -> 1.0 ‰
3 glasses water -> -0.6 ‰

=> 0.4 + 0.4 + 1 - 0.6 = 1.2 ‰

To reach 0.5 ‰ you need to loose 0.7 ‰. You loose 0.1 ‰ per hour, so you need to wait 7 hours to drive again.
Rules

You can take the input in any format you want, but you have to use the exact strings as given above. You may take the numbers as integers.
You can output the two numbers in any order, just make in clear which one you use in your answer.
You may assume that the input will always have at least one entry.
Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
Input as list of strings. Outputs alcohol level first, values seperated by a comma.

["4 shots booze","1 glasses wine","2 bottles beer","3 glasses water"] -> 1.2, 7
["10 shots booze", "1 bottle water"] -> 0.5, 0
["3 glasses wine", "2 bottles booze"] -> 6.2, 57
["6 shots beer", "3 glasses water"] -> 0, 0
["10 glasses beer"] -> 2.0, 15

Happy Coding!

"The alcohol level can never fall below zero." - Is the array in order of concession, or just in total? So if I have 1 shot of beer, and then 2 shots of water, and then 1 shot of beer, should it output 0% or .5%?

@KuilinLi It's not, order does not matter. I will clarify, thanks for the comment!

So it should output 0, and alcohol level can technically fall below zero in the middle of the drinking? Cuz otherwise, we have no way of knowing when the water was drunk if the array has water in it... We could even assume that, if the array contains water, we will drink the water first, and it will have zero effect on anything.

@KuilinLi I made it clear in the challenge now. Alcohol level may fall below zero in the process of the calculation, you just have to round it to zero if it stays there.

I don't drink, so my entry is function drive(a) { if (a.every(v=>/water/.test(v))) return [0, 0]; throw new TeetotalException; }

Is this a valid input format?

Javascript (ES6), 111
Takes input as arrays of arrays of strings/integers e.g.
[[4, "shots", "booze"],
[1, "glasses", "wine"],
[2, "bottles", "beer"],
[3, "glasses", "water"]]

Outputs to simple array e.g. [1.2, 7]
a=>(b=0,c={s:2,g:20,b:50,o:2,e:10,i:5,a:-10},a.map(([d,e,f])=>b+=d*c[e[0]]/c[f[1]]),g=b>0?b:0,[g/10,g>5?g-5:0])

#Explained
a => (
b = 0,                                           // Counter For Alcohol Level
c = {s:2, g:20, b:50, o:2, e:10, i:5, a:-10},    // Look up for values
a.map(                                           // Loops over array
  ([d, e, f]) =>                                 // Sets d,e,f to respective array indexes
     b += d * c[e[0]] / c[f[1]]                  // Increases Level by values from lookup
  ),
g = b > 0 ? b : 0,                               // If Level is lower than 0 make it = 0
[g / 10, g > 5 ? g - 5 : 0])                     // Output: Level / 10 and Level - 5 bound to 0

Well played but not always valid: try [[3,"shots", "booze"]]

@edc65 Good Catch!

It just need a little adjustment and still a lot better than mine

TSQL, 301, 299, 219, 206 Bytes
Input goes into temp table #I (you said any format :)
SELECT * INTO #I FROM (
  VALUES
    (4,'shots','booze')
   ,(1,'glasses','wine')
   ,(2,'bottles','beer')
   ,(3, 'glasses','water')
) A (Q, V, N)

Code:
SELECT IIF(L<0,0,L),IIF(10*L-.5<0,0,10*L-.5)FROM(SELECT SUM(Q*S*P)L FROM(VALUES('bo%',.5),('be%',.1),('wi%',.2),('wa%',-.1))A(W,S),(VALUES('s%',.2),('g%',2),('b%',5))B(X,P),#I WHERE N LIKE W AND V LIKE X)A;

Thanks for the ideas to improve it, Micky T :)

For 2012+ you could use the IIF function rather than CASE statements for some bytes

You could also change your column names in the subqueries to avoid having to qualify then in the join clauses eg JOIN(SELECT .. )A(Y,S)ON Y=N and (L+ABS(L))/2,10*((L-.5+ABS(L-.5))/2) is shorter than the previously mentioned IIF function.  You may also save a bit if you look at doing a cross join on the values for size and strength. eg SELECT V,N,Q*S FROM(VALUES(...))A(N,S),(VALUES(...)B(V,Q)

JavaScript (ES6), 131
a=>a.map(s=>([a,b,c]=s.split` `,t+=a*[50,20,2]['bgs'.search(b[0])]*~-'0236'['aeio'.search(c[1])]),t=0)&&[t>0?t/100:0,t>50?t/10-5:0]

Less golfed
a=>(
  t=0,
  a.map(s=>(
    [a,b,c] = s.split` `,
    t += a * [50,20,2]['bgs'.search(b[0])] // char 0 is unique
           * [-1,1,2,5]['aeio'.search(c[1])] // char 1 is unique
           // golfed: add 1 to get a string of dingle digits, the sub 1 using ~-
    )
  ),
  [ t>0 ? t/100 : 0, t>50 ? t/10-5 : 0]
)

Perl, 133 119 + 3 = 136 122 bytes
%u=(o,.5,e,.1,i,.2,a,-.1,g,2,b,5,s=>.2);/(\d+) (.).* .(.)/;$x+=$1*$u{$2}*$u{$3}}{$_=($x>0?$x:0).$".($x-.5>0?$x-.5:0)*10

To be run with perl -p. Takes line-oriented input on STDIN, produces output on STDOUT.
Less-golfed version:
# char->number conversion table
# declared using barewords except for 's', which can't be a bareword
# because it's a keyword
%u=(o,.5, e,.1, i,.2, a,-.1, g,2, b,5, s=>.2);

# extract the number, first letter of first word, second letter of
# second word
/(\d+) (.).* .(.)/;

# do unit conversion and multiply up all factors
$x += $1 * $u{$2} * $u{$3}

# hack for -p to produce an END { ... print } block
}{

# format output
$_ = ($x > 0 ? $x : 0) . $" . ($x-.5 > 0 ? $x-.5 : 0)*10

Thanks to dev-null for suggestions saving 11 bytes.

@dev-null thanks! I think the function made sense for an intermediate shortening, and I forgot to check whether it was still helping.

If you always get valid input then you can change \d to .

Would you please add an example run of the program, so its clear which input and output format you use?

C (GCC), 176 166 bytes
-10 bytes thanks to @ceilingcat
float x;main(a){for(char b[9],c[9];~scanf("%d%s%s\n",&a,b,c);)x+=a*(*b-98?*b-103?.02:.2:.5)*(*c-98?c[1]-97?2:-1:c[1]-111?1:5);printf("%f %f",x>0?x:0,fmax(0,x*10-5));}

Attempt This Online!


text:
Get the closest value to number
In this code golf, you need to get the closest number from another one in a list.
The output may be the closest number to the input.
Example:
value: (Input) 5 --- [1,2,3] --- 3

And, the program may work with negative numbers.
Example:
value: (Input) 0 --- [-1,3,5] --- -1

value: (Input) 2 --- [1, 5, 3] --- 1 (Because it gives priority to lower numbers)

RULES:
As mentioned before, it has to work with negative numbers.
If there are two answers (Example: 0 -- [5,-5]), the program gives priority to the lowest number. (-5)
This is code golf so the shortest code wins!

it gives priority to lower numbers That should be mentioned in the rules.

If the target number is present in the list, should the output be that number or the closest other number from the list?

I know, the accepted answer is temporal.

But whatever, I'll remove the accept.

@Alex82 Sure, you know that you'll change the accepted answer if a better one comes in, but some people are put off by challenges that already have an accepted answer, because unfortunately not every challenge author is that attentive to late answers. So it's less about whether accepting early is actually bad but whether people will get the wrong impression.

Are the input numbers integers?

@randomra: Yes.

Pyth, 6 bytes
haDQSE

Test suite
Input in the following form on STDIN:
num
array

Explanation:
haDQSE
          Implicit: Q = eval(input()) (num)
     E    Evaluate input (array)
    S     Sort (smaller values to the front)
 aDQ      Sort by absolute difference with Q.
h         Take the first element of the sorted list, the min.
          Print implicitly.

Ruby, 34 bytes
->n,a{a.sort.min_by{|x|(n-x).abs}}

a.sort       min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x|  select the element which returns the smallest val for predicate...
(n-x).abs}   (absolute) difference between input num and element

I think you don't need #sort, since min_by will already sort it from min to max. So, it can be even shorter: ->n,a{a.min_by{|x|(n-x).abs}}

Mathematica, 12 bytes
Min@*Nearest

Built-ins FTW! Buettner's explanation: "Mathematica has a built-in Nearest for this, but it returns a list of all tied numbers. Hence, we need to compose it with Min to break the tie."

That's what I get for writing an explanation...

Could you add a "Try it online"?

@Alex82 Seems unlikely for Mathematica (which is proprietary).

@Alex82 Test it here: https://lab.open.wolframcloud.com/app/view/newNotebook?ext=nb

Pyth, 8 bytes
hS.mabQE

Explanation
         - autoassign Q = eval(input())
  .m   E -   min_values([V for b in eval(input())])
    abQ  -    abs(b-Q)
 S       -  sorted(^)
h        - ^[0]

Try it online!

Jelly, 7 6 bytes
ạżṛỤḢị

Try it online!
How it works
ạżṛỤḢị Main link. Left input: n (number). Right input: A (list)

ạ      Take the asbolute difference of n and the items of A.
  ṛ    Yield the right argument, A.
 ż     Zip the left result with the right one.
       This pairing causes ties in absolute value to be broken by initial value.
   Ụ   Grade up; sort the indices of the resulting list by their associated values.
    Ḣ  Retrieve the first index, which corresponds to the smallest value.
     ị Retrieve the item of A at that index.

JavaScript ES6, 64 56 54 bytes
(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]

Try it online
Thanks to @Niel for saving two bytes
Test Snippet:

f=(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0];

[
  [5, [1, 2, 3]],
  [2, [3, 5, 1]],
  [2, [1, 3, 5]],
  [0, [-1, 2, 3]],
  [5, [1, 2, 3]]
].map(v=>O.textContent+=JSON.stringify(v)+": "+f.apply(null,v)+"\n")

Save 2 bytes by combining the sorts: (i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]

You can save a byte by currying your function: i=>a=>... then f(i)(a) is how you call it.

@PatrickRoberts In this case I would say no, because OP is asking for a function (or simulere) that takes to values: input and a list/array/... as integers

Jelly, 4 bytes
ạÐṂṂ

Try it online!
This takes A on the left and n on the right
I'm guessing the ÐṂ builtin didn't exist when Dennis wrote his answer.
How it works
ạÐṂṂ - Main link. Takes A on the left and n on the right
 ÐṂ  - Keep elements of A with a minimal:
ạ    -   Absolute difference with n
   Ṃ - Take the minimum

@ovs Good catch, I missed that

APL (Dyalog Unicode), 17 16 bytes
⊢{⌊/⍺/⍨⍵=⌊/⍵}∘|-

Try it online!
This is a function which takes a single number as a left argument and a list of numbers as a right argument.
The general structure of this is a fork consisting of:

the constant right function ⊢ returns the list of numbers
|- calculates the absolute value of each difference between a number from the list and the left argument
and the dfn {⌊/⍺/⍨⍵=⌊/⍵} which is called with the results of the other two functions:

            ⍝ ⍵: absolute differences (|-)
            ⍝ ⍺: the original list (⊢)
       ⌊/⍵  ⍝ the minimum of the absolute differences
     ⍵=     ⍝ element-wise equal to the absolute differences
  ⍺/⍨       ⍝ select all values from the original list where this is 1
⌊/          ⍝ take the minimum

A fully tacit function came out at 17 bytes: ⌊/∘∊((⊢=⌊/)∘|-)⊆⊢.

With some help from Adám, here is a shorter function in the extended variant:
APL (Dyalog Extended), 12 bytes
(⊃⍋⍤|⍤-⊇⊢)∘∧

Try it online!
Same arguments as before, ∧ sorts the list ascending and ⊃⍋⍤|⍤-⊇⊢ is applied with the left number and the sorted list as a right argument.
     -   ⍝ the difference between the left argument and each list entry of the sorted list
   |     ⍝ take the absolute values
 ⍋       ⍝ the indices that would sort this list (stable)
      ⊇  ⍝ index with these indices into ...
       ⊢ ⍝ ... the sorted list. This resorts the list on the absolute difference
⊃        ⍝ pick the first value

(⍋⊃¨⊂) sorts ascending as well, if that'd be of help in the tacit version.

@Razetime that's an interesting alternative, but in this case, where we have to ignore the left argument, the best I could do with it is 17 bytes.

Doesn't ⌊/⊢⊃⍨∘⊃∘⍋∘|- do the trick? Or ⊃⍋⍤|⍤-⊇∧⍤⊢ in Extended?

@Adám the non-extended version seems to fail for the last testcase on TIO. I guess ⌊/ should do the tiebreak? But doesn't ⊃∘⍋∘|- always result in a single value?

The extended works for my testcases, but I'm struggling to understand why. The way I read this is: with the indices that woud sort |⍺-⍵ (⍋⍤|⍤-) index (⊇) into the sorted list (∧⍤⊢). Then take the first element (⊃). But why does this work if we are indexing into the sorted with indices that are not based on the sorted list? Am I missing something?

I see now that my second solution had the same problem: TIO. Sorry for the confusion.

{(∧⍵)⌷⍨⊃⍋|⍺-∧⍵} does work in Extended and can probably be shortened.

That explains it, as I didn't look at the problem spec, only at your second solution. Shortened: ⊃⍤⍋⍤|⍤-∘∧⌷∧⍤⊢ or (⊃⍤⍋⍤|⍤-⌷⊢)∘∧

R, 37 bytes
(x=scan())[order(abs(x-scan()),x)][1]

Try it online!
After 4 years, 5 bytes shorter than the previous R answer.
Uses the order() function with two arguments, to order first by the closeness to the target value, and then to break ties by the array value.  Finally outputs the first element after re-ordering.

Python 2, 56 bytes
a=input()
print sorted(input(),key=lambda x:abs(a-x))[0]

Gets the target number first a=input() - this has to be stored in a variable.
It then sorts the input with the function lambda x:abs(a-x) applied (think map(lambda x:abs(a-x), input()))
It then takes the minimum value in case of any duplicate values

MATL, 10 bytes
Sti-|4#X<)

Try it online!
S       % implicitly input array, and sort. This ensures smaller numbers have priority
t       % duplicate
i       % input number
-|      % compute array of absolute differences
4#X<    % arg min. If there are several minimizers, the position of the first is returned
)       % index into original array. Implicitly display

Japt -g, 4 bytes
ÍñaV

Try it
ÍñaV     :Implicit input of array U and integer V
Í        :Sort U
 ñ       :Sort by
  aV     :  Absolute difference with V
         :Implicit output of first element

Python 3, 41 bytes
lambda n,a:min((abs(n-i),i)for i in a)[1]

Try it online!
No need to sort, because min captures the lowest difference and the lowest value.
Also works in Python 2.

Husk, 6 4 bytes
◄≠⁰O

Try it online!
◄           # element that minimizes
 ≠⁰         # difference to arg 1
   O        # applied to sorted elements
            # (implicitly) of arg 2

05AB1E, 4 bytes
{I.x

Try it online or verify all test cases.
Explanation:
{     # Sort the first (implicit) input-list from lowest to highest
  .x  # Pop the list, and push the value closest
 I    # to the second input-integer
      # (after which it is output implicitly as result)

This could have been 2 bytes (.x) if we were allowed to output the first instead of the lowest value in the list, if more than one is closest: try it online or verify all test cases.

Haskell, 38 bytes
e#l=snd$minimum$(zip=<<map(abs.(e-)))l

Usage example: 2 # [1,5,3]-> 1.
For each element in the input list l make a pair of the absolute difference of the element with the input number e and the element itself, e.g. e=2, l=[1,5,3] -> [(1,1),(3,5),(1,3)]. Find the minimum and discard the difference.

Perl 6, 31 bytes
{@^b.sort.sort((*-$^a).abs)[0]}

Usage:
my &code = {@^b.sort.sort((*-$^a).abs)[0]}

say code 5, [1,2,3];   # 3
say code 0, [-1,3,5];  # -1
say code 2, [1, 5, 3]; # 1
say code 0, [5,-5];    # -5

zsh, 75 73 71 70 67 bytes
for n in ${@:2};{echo "$[$1-n]    $n"}|tr -d -|sort -n|head -1|cut -f2

Expects input as command line arguments.
Note that the four spaces in the echo is actually supposed to be a tab, but Stack Exchange converts tabs to spaces in all posts.
Not Bash-compatible because of the for  syntax.
for n in ${@:2};      for each argument except the first...
{echo "$[$1-n]\t$n"}  output the difference from the first argument
                        and then the original number
|tr -d -              poor man's abs()
|sort -n              sort by first num (difference), tiebreaking by second num
                        (original value)
|head -1              take the thing that sorted first
|cut -f2              print field 2 (aka discard the difference)

Thanks to dev-null for 2 bytes!

TeaScript, 10 bytes
T#(y-l)a)░

TeaScript doesn't support array input so in the console run: TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS) to runthis.
Explanation
T#  // Sort input by...
  (y-l)a // absolute difference with input
)░  // First item in array

R, 42 bytes
x=sort(scan());x[which.min(abs(x-scan()))]

Stax, 7 bytes
ôXêUe>┤

Run and debug it

T-SQL, 93 Bytes
SELECT MIN(B) FROM(SELECT B,abs(B-@v) AS C FROM @A) D WHERE C=(SELECT MIN(abs(B-@v)) FROM @A)

Example:
DECLARE @A TABLE(B  INT);
DECLARE @v INT = 5;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3)) AS A(B);

SELECT MIN(B) -- 3. Finally, select the minimum list value from the rowset
FROM(
        SELECT B,abs(B-@v) AS C -- 1. Get list value along with absolute value of the difference.
        FROM @A
    ) D
WHERE C = (SELECT MIN(abs(B-@v)) -- 2. Filter for the smallest absolute difference.
          FROM @A
          )

C# 61 52 bytes
int v(int i,int[] a)=>a.Min(x=>(Math.Abs(i-x),x)).x;

Or function body only: 29 bytes.

PHP, 62 bytes
foreach($a as $i){$s[$i]=abs($i-$n);}
asort($s);print key($s);

Try it online!
First PHP answer, please help!
(Define the number and array in header section)


text:
Print the input in hexadecimal
Challenges
You need to do a program that outputs the input string to hexadecimal!
For each character in the input string, convert it's ascii value to hexadecimal and output it out.
Example
Something = 536f6d657468696e67

Of course, this is code golf, so the shorter code wins!

See Default input/output methods. A file is allowed by default and there isn't much (if any) difference after this (apart from separating by spaces in the other question)

I'm downvoting because this question is too simple.

Pyth, 3 bytes
.Hz

Pyth docs:
.H <str>
  Converts A to a hexadecimal string, treating the string as a base 256 integer.

z is a variable autoinitialized to input().
Try it here.

'That's what I get for writing a try-it link'

@muddyfish Hahaha. To be fair, you ninja'd my answer verbatim while I was writing an explanation on the last challenge :D

Bash, 6 bytes
xxd -p

JavaScript ES6, 49 bytes
s=>s.replace(/./g,l=>l.charCodeAt().toString(16))

Try it online

Wouldn't this replace newlines in the input with a instead of 0a?

@Doorknob the OP hasn't specified that and a is the hexadecimal value of 10 (newline) so I'm not sure

Should it become necessary, (l.charCodeAt()+256).toString(16).slice(1) edges out ('0'+l.charCodeAt().toString(16)).slice(-2) by one byte.

Python3 console, 21 bytes
input().encode("hex")

input() -- Gets the input in a string.
       .encode("hex") -- Encodes it to hexadecimal.

Doing this on the console saves the print argument.

If you do it on the console, it will print itself

You should mention, that this doesn't work in the recent Python versions 3.4 and 3.5. https://docs.python.org/3/whatsnew/3.4.html#codec-handling-improvements

, 7 chars / 9 bytes
ïⓢ⒨⒞ⓧ)⨝

Try it here (Firefox only).
Explanation later.

JavaScript ES6, 50 bytes
s=>[for(c of s)c.charCodeAt().toString(16)].join``

Using an array generator comprehension, it loops through each character of the string and generates an array of the transform, then call .join() with an empty string as an argument to prevent inclusion of commas in default array toString() method.
Try it Online
This currently only works in Firefox v ≥ 30

TeaScript, 5 bytes
ΣcT16

I really need to add base conversion built-ins
Try it online
Explanation
Σ    // Loop through input
 c   // Get char code
 T16 // To hexadecimal

Perl 6, 25 bytes
{lc [~] .ords».base(16)}

Usage:
my &code = {lc [~] .ords».base(16)}

say code 'Something';
# 536f6d657468696e67

Python, 24 bytes
lambda x:x.encode("hex")

Test:
a=lambda x:x.encode("hex")
a("something")    # 736f6d657468696e67
a("Hello World!") # 48656c6c6f20576f726c6421