text:
What's my middle name?

Note: The winning answer will be selected on 4/12/17 the current winner is Jolf, 1 byte.

I'm surprised that we haven't had a what's my middle name challenge on this site yet. I did alot of searching but found nothing. If this is a dup, please flag it as such.
Your challenge
Parse a string that looks like Jo Jean Smith and return Jean.
Test cases
Input: Samantha Vee Hills
Output: Vee

Input: Bob Dillinger
Output: (empty string or newline)

Input: John Jacob Jingleheimer Schmidt
Output: Jacob Jingleheimer

Input: Jose Mario Carasco-Williams
Output: Mario

Input: James Alfred Van Allen
Output: Alfred Van

(That last one is incorrect technically, but fixing that  would be too hard.)
Notes:

Names will always have at least 2 space-separated parts, with unlimited middle names between them or can be a list/array of strings.
Names may contain the alphabet (case-insensitive) and - (0x2d)
You may output a trailing newline.
You may require input to have a trailing newline.
Input from STDIN, a function parameter, or command-line argument is allowed, but hard-coding it in is not allowed.
Standard loopholes forbidden.
Output may be function return value, STDOUT, STDERR, etc.
Trailing spaces/newlines/tabs in the output are allowed.
Any questions? Comment below!

This is code-golf, so the shortest anwser in bytes wins!

Can input be taken in as list?

@AnthonyPham yes.

Can the output be a list of strings?

If other formats than a space-separated string are allowed, please edit that into the specification.

@programmer5000: if the input can be a list of strings, how about the output? Is ["John", "Jacob", "Jingleheimer", "Schmidt"] -> ["Jacob", "Jingleheimer"] a valid solution?

Are leading spaces allowed?

May we assume that all names are unique?

@Adám no, you can't.

@nimi yes, you can.

Requested test case: James Alfred van Allen

@Adám All names will be capitalized.

Can you clarify what you mean by That last one is incorrect technically, but fixing that would be too hard.? If it's incorrect, why include it?

@DJ Because "Van" isn't his middle name, it's part of his last name. A particularly vexing case is David Lloyd George, whose first name is David and last name is Lloyd George. Any attempt to parse real people's names like this is doomed. In fact, you can't even tell what the first and last names are (think Li Shi).

Can we have leading spaces?

What are 'Standard loopholes' ?

@2501 https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/

You may output a trailing newline. What is a trailing newline? A newline at the end of each word, or a newline at the end of the entire output?

@2501 At the end of the entire output.

@programmer5000 Thanks, I though so.

@programmer5000 - current leader is Jolf at one byte!

Jolf, 1 byte
€

Gets the inside of the input. Try it here!

Can't seem to get the example running - nothing seems to happen when I click any of the buttons. Using Chrome 57.0.2987.133

@YiminRong I can only assure it to work on firefox.

Ohm, 2 bytes (CP437)
Accepts and returns a list of strings.
()

Explanation:
()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output

The right tool for the job I guess

Vim, 6 5 bytes
dW$BD

Try it online!
(outputs with a trailing space)
Since Vim is reverse-compatible with V, I have included a TIO link for V.
Explanation
dW                      " Delete up to the next word (removes the first name)
$                       " Go to the end of the line
B                       " Go back one word
D                       " Delete it

Drat, you beat me to it. dWWD saves you one byte.

@DJMcMayhem That only works for exactly one middle name.

What's the difference between dW and dw?

@DuncanXSimpson dW deletes until whitespace. dw deletes until non-word characters.

Python, 24 bytes
lambda n:n.split()[1:-1]

Try it online string input!
Input Format: string

Python 2, 16 bytes
lambda n:n[1:-1]

Try it online list input!
Input Format: List

You should edit the title with Python instead of Python 2, because it works for Python 3 as well, was just about to post that.

@L3viathan since OP hasn't mentioned the output format must be a string, and since the input format is allowed to be a list, print a list cannot be considered as a wrong result!

According to the comments on the question, you can both input and output a list of strings. Save a bunch of bytes lambda n:n[1:-1]

Since you can read from STDIN, can replace the lambda with input() (Python 3 only)

You are right. Thanks. I've added the edits!

Brain-Flak, 133 bytes
{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>

Try it online!
132 bytes of code, plus 1 byte for the -c flag which allows ASCII input and output.
Unfortunately, this contains lots of duplicated code, but it would be really difficult to reuse. I'll look into it later. Here's an explanation:
#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

86 bytes when you remove the comments. I added the first two and the last line. TIO

@riley Cool solution. Feel free to post it yourself!

Haskell, 23, 17 9 bytes
init.tail

Takes and returns a list of strings. Try it online!
Drop first string, drop last string.
Edit: @Generic Display Name noted, that the input can be a list of strings, which saved 6 bytes.
Edit II: return list of strings instead of a single string

It looks like input as a list is allowed, so drop the words for -5 bytes

@GenericDisplayName: Oh, didn't notice. Thanks!

My Ohm answer and the Mathematica answer both output lists of strings as well, so you could probably drop unwords. for -8 bytes.

@NickClifford: yes, I saw that myself and asked the OP for clarification.

05AB1E, 2 bytes
¦¨

Try it online!
If outputting a list of middle names isn't allowed, I'll change it.

Mathematica, 10 bytes
Rest@*Most

An unnamed function that accepts and returns a list of strings.
Rest discards the the last element, Most discards the first element, @* is function composition. Swapping Rest and Most or using right-composition /* instead would also work. This beats indexing via #[[2;;-2]]& by one byte.

Brain-Flak, 86 bytes
(()()){({}[()]<{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>>)}{}

Try it online!
Most of this code comes from this answer. If you like my solution you should upvote that one as well.
#Push 2
(()())

#Loop twice
{({}[()]<

  #While not a space
  {
      #Pop
      {}

      #Not equals 32
      ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

  #Endwhile
  }

  #Pop the 0
  {}

  #Reverse Stack
  {({}<>)<>}<>

#End loop twice
>)}{}

Well done! I didn't think about holding a counter for pushing later, so I spent too long thinking about how to loop across different stacks.

AWK, 17 10 bytes
Saved 7 bytes thanks to @steve!
$NF=$1=x;1

Try it online!
Explanation:
$NF=    set last word to
$1=     set first word to
x       an empty variable, ie empty string
1       default action, ie print everything

Can be shaved down to 11 bytes, $NF=$1="";1

Or 10 using $NF=$1=x;1

@steve what does 1 do? I'm not so good at AWK :)

1 just means take the default action, that is, to print $0.

Java 7, 74 bytes
String f(String s){return s.substring(s.indexOf(' '),s.lastIndexOf(' '));}

Java 8, 49 bytes
s->s.substring(s.indexOf(' '),s.lastIndexOf(' '))

Function which identifies the first occurrence of the space character and the last one and extracts the middle. The resulting string is prefixed by a space character (at the time of the posting, OP hasn't clarified if leading spaces are allowed), which can be eliminated by adding .trim() to the code for an extra cost of 7 bytes.
Compared to C#, Java has the advantage of specifying the end index instead of sub-string length, which brings down the byte count.

JavaScript (ES6), 22 bytes
Takes and outputs an array of strings.
([_,...a])=>a.pop()&&a

Test cases

let f =

([_,...a])=>a.pop()&&a

console.log(f(["Samantha", "Vee", "Hills"]))
console.log(f(["Bob", "Dillinger"]))
console.log(f(["John", "Jacob", "Jingleheimer", "Schmidt"]))
console.log(f(["Jose", "Mario", "Carasco-Williams"]))

String version (27 bytes)
Takes and outputs a string. The output string is either a single space if no middle name was found, or the middle names with leading and trailing spaces.
s=>(/ .* /.exec(s)||' ')[0]

let f =

s=>(/ .* /.exec(s)||' ')[0]

console.log(f("Samantha Vee Hills"))
console.log(f("Bob Dillinger"))
console.log(f("John Jacob Jingleheimer Schmidt"))
console.log(f("Jose Mario Carasco-Williams"))

/./.exec.bind(/ .* /) seems to mimic #2, except null for none

Groovy, 19 bytes
{it.split()[1..-2]}

Explanation:
{
 it                  all closures have an implicit argument called "it"
   .split()          splits by spaces by default. Returns an array of words
           [1..-2]   take the whole array from the second index (1) to the penultimate index (-2). Implicitly return
                  }

A closure / anonymous function

Welcome to PPCG! Can you take a list of strings as input to skip the .split()?

Martin Ender Yes, if you assume that the input will always be a list of strings then {it[1..-2]} would work.

PHP, 37 Bytes
<?=join(" ",array_slice($argv,2,-1));

-4 bytes for an output as array
print_r(array_slice($argv,2,-1));

PHP, 42 Bytes
echo trim(trim($argn,join(range("!",z))));

PHP, 50 Bytes
echo preg_filter("#(^[^\s]+ |[^\s]+$)#","",$argn);

Perl 5, 27 18 bytes
Need to run with -n option.
/ (.+) /&&print$1

Try it online!
Wanted to do something similar in sed first, but, unfortunately, it doesn't support non-greedy quantifier. It is needed in case middle name is more than one word.
Edit
-9 bytes thanks to Dada.
Non-greedy quantifier is not needed anymore, among with some other things.

/ (.+) /&&print$1 should be sorter. Great to see some new people golfing with Perl!

@Dada Thanks for the tip! It's actually my first time ever writing in Perl. Do you know why print if s| (.+) |\1| doesn't work? To me it looks similar to what you wrote.

print if s| (.+) |\1| replaces the middle part with... the middle part! (minus the spaces before and after), so it doesn't work. On the other side, what I suggested only matches the middle part and print only it ($1).

Nice! You can get this down using -p too and using x instead of &&: Try it online!

sed, 21 19  17  15 bytes + -E
new:
idea thanks to @user41805
-2 thanks to @xigoi
-2 thanks to @ user41805
s/^\S+ |\S+$//g

old:
-1 thanks to @user41805
s/\S+ ((.+ )*).+/\1/

Try it online!

Is it possible for you to edit in a link to an online interpreter, such as Try it online!, so that others can run your program?

@ChartZBelatedly Is that better?

[^ ] can become \S. But I think if you split your program into two substitutions you can save some bytes.

@user41805 I tried that and it worked!:) I've already updated my answer

I think the second substitution should be s/ ?\S+$// instead for it to work on 'Bob Dillinger'. But now, you should be able to combine these two substitutions with a |.

Fixed and two bytes shorter: Try it online!

Combining them gives two bytes less s/^\S+ |\S+$//g.

Retina, 11 bytes
^\S+ |\S+$

Try it online!
Matches the first word (including the space after it) and the last word, and removes both of them.
If I/O can be a linefeed-separated list, it can be done in 8 bytes instead:
A1`
G-2`

Try it online!

Javascript (ES6) 49 16 bytes
Edit:
a=>a.slice(1,-1)

Try it online!
ungolfed:
function(name) {
  return a.slice(1, -1); //start at the second item and end at the second to last item
};

I forgot some of the simple properties of slice, and that the input can be an array. Thanks to @Neil and @fəˈnɛtɪk I was able to remove 27 bytes. Still not really competing.
Original:
This isn't really competing but here's a Javascript solution:
a=>{a=a.split(' ');return a.slice(1, a.length-1)}

This creates an anonymous function equal to:
function(name) {
  let name = name.split(' '); //first middle last -> [first, middle, last]
  return name.slice(1, name.length - 1); //get the second item to the second to last item in the array.
}

How I golfed it
This is a pretty simple golf. I turned the function into an arrow function. Then I "minified" the code. This included renaming name into a single character(a in this case) and removing the let decloration of the variable.
Snippet

var a=b=>b.slice(1,-1)

//example code

let form = document.querySelector('#form'),
    input = document.querySelector('#input'),
    result = document.querySelector('#result');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  let value = input.value.split` `;
  result.textContent = a(value).join(' ');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form id="form">

    <input id="input" class="form-control" />

      <button class="btn btn-primary">Submit</button>

</form>

Hope this helps anyone who is stuck on the challenge.

The length - is unnecessary, as slice already accepts negative lengths as being relative to the end. This means that you no longer need the intermediate variable, so you can turn your arrow function from a block into an expression.

Actually the way it works is that -1 is the last but one that you need here.

It is also slice(1,-1). slice(1,-2) removes two from the end.

You can also assume that you were passed an array to begin with, which lets you just perform slice and you are done.

I'm 99% sure that was changed since I started it. Thanks again.

Arn, 4 bytes
†Û⁺%

Try it!
Explained
Unpacked: .{.}
_ Variable initialized to STDIN; implied
  .{ Take
    .} Then drop
         Output implicit

Strings are split on spaces if any or ever character if there are non (when casted to an array).

Husk, 6 4 bytes
;htw

Try it online!
-2 bytes from Zgarb.

@JoKing like you said earlier, h and t return a list of strings, so something strange happens when w is applied.

Nah, the issue was that the first w was being interpreted as words, and the second as uwpshw, which makes sense as the type system is greedy

Use ; to "format" the output instead of J

Röda, 9 bytes
{_[1:-1]}

Try it online!
Not a very interesting solution. Takes a list from the stream and returns the middle names.
21 bytes and I/O:
{[(_/" ")[1:-1]&" "]}

Try it online!
This uses / (split) and & (join).

Matlab, 81, 79, 78, 55 Bytes
function x=a(s)
s=strsplit(s);x=strjoin(s(2:end-1));end

Takes in an input string, s, is split (by the default delimiter, whitespace char) into a cell array, from which the middle element is accessed. Then the middle elements are concatenated, or an empty string is returned.
Edit: thanks to Luis Mendo for saving 3 bytes!
Edit 2: Better solution from Ankit!

I am not a smart man! edited.

You can't use nnz on a cell array, but I did the other two changes :)

Suggested Edit by Ankit, who doesn't have enough rep to comment. (55 bytes): function x=a(s) s=strsplit(s);x=strjoin(s(2:end-1));end

Jelly, 2 bytes
ḊṖ

Try it online!
This works as a non-inline link (i.e. function), not a full program.
'John','Jacob','Jingleheimer','Schmidt' → 'Jacob','Jingleheimer'
As a full program, it would be 3 bytes: ḊṖK, which prints a space-separated middle name.

Pyth, 2 bytes
Pt

Online interpreter

C#, 67 bytes
s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

Anonymous function which identifies the first occurrence of the space character and the last one and extracts the middle. It also extracts a trailing space, which can be removed at the cost of 2 bytes.
Full program with test cases:
using System;

namespace WhatsMyMiddleName
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f =
            s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

            Console.WriteLine(f("Jo Jean Smith"));          // "Jean"
            Console.WriteLine(f("Samantha Vee Hills"));     // "Vee"
            Console.WriteLine(f("Bob Dillinger"));          // ""
            Console.WriteLine(f("John Jacob Jingleheimer Schmidt"));// "Jacob Jingleheimer"
            Console.WriteLine(f("Jose Mario Carasco-Williams"));    // "Mario"
            Console.WriteLine(f("James Alfred Van Allen")); // "Alfred Van"
        }
    }
}

Ruby, 24 13 bytes
p ARGV[1..-2]

Saved 11 bytes thanks to Piccolo pointing out that array-like output is allowed.
Takes the name as separate command line arguments, e.g.:
$ ruby script.rb John Jacob Jingleheimer Schmidt

or
$ ruby -e 'p ARGV[1..-2]' John Jacob Jingleheimer Schmidt

Previous code (outputs a proper string):
puts ARGV[1..-2].join" "

@Jordan Good idea - however with $><<ARGV[1..-2].join" " it complains about the " " being unexpected, so I'd have to add parentheses - which would add 1 byte in the end.

Ah, of course. My bad.

The original poster said that the output can be an array, so you can shave some characters off by just changing your code to puts ARGV[1..-2], just so you know.

@Piccolo Huh? I don't see that anywhere? If true; p ARGV[1..-2] for 13 bytes - just looks nothing like the output in OPs challenge

@Flambino http://codegolf.stackexchange.com/questions/114927/whats-my-middle-name/114993?noredirect=1#comment280325_114927

@Piccolo Ah, in the comments - well, 13 bytes then! Thanks

Kotlin, 39 bytes
s.filterIndexed{i,j->i!=0&&i!=s.size-1}

Try it online!
i.e.
s.filterIndexed{ index, value -> index != 0 && index != (s.size - 1) }

Golang, 152 81 bytes
import ."strings"
func f(x string)[]string{var k=Fields(x);return k[1:len(k)-1];}

It takes input as "Samantha Vee Hills" (with double quotes) and return the middle name to the stdout.
Try it Online!
Edit: @Dada, note that the "function as answer is allowed" shorten my code 71 bytes. a big thanks!

Welcome on the site.  Submitting a function as answer is allowed, so you could shorten your code by doing something like this: Try it online!. Have a look at the Tips for Golfing in Go!

thank you @Dada for tips and shorten my code. It was my first code entry.

VBA, 69 bytes
Sub m(n)
f=InStr(1,n," ")
Debug.?Mid(n,f+1,InStrRev(n," ")-f)
End Sub

R, 30 27 22 bytes
Current solution due to user11599!
head(scan(,''),-1)[-1]

Takes input from stdin, returns each middle name as a separate string. Returns character() in the case of no middle name; that is, a vector of class character of length 0.
Explanation:
Read stdin into a list of strings, separated by spaces
     scan(,'')

Remove the last element. head returns the first n elements of a list, with n defaulting to 6. If n is -1 it returns all but the last element.
head(scan(,''),-1)

Now, remove the first element of this list.
head(scan(,''),-1)[-1]

This yields the middle name(s).

Even shorter:  head(scan(,''),-1)[-1]      22 bytes.  Note that '' are two single quotes.

If you don't want each name quoted, use, at 27 bytes, cat(head(scan(,''),-1)[-1])

Explanation:  scan(,'') breaks the string into words, head(...,-1) drops the last word, head(...,-1)[-1] then drops the first word, cat() formats the output dropping the quotes.  For no middle name, result isn't perfect, it's character(0), the empty string.

@user11599 Wow, thanks! I had played around with head() and tail(), but I didn't know you could pass a negative number as the second argument. Nice!

Your use of scan(,'') inspired me.  I didn't think of approaching that way.

Grime, 6 bytes
<\ 0\

Try it online!
Note the trailing space.
Explanation
        Match a substring S that satisfies:
<       S is contained in a string of the form
 \      a space
   0    then S
    \   then another space.

This matches a substring that's surrounded by spaces.
By default, Grime prints the longest match it finds (without the spaces).
If no match exists, nothing is printed.

C, 42 bytes
f(char**b){for(;b[2];printf("%s ",*++b));}

The parameter is a NULL terminated array of pointers to char.
See it work here.
The command line arguments may also be used with the same function.
C, 51 bytes
main(a,b)char**b;{for(;b[3];printf("%s ",b++[2]));}

A full program. Input is done through command line arguments.
See it work here.
C, 54 bytes
f(char**b){*strrchr(*b=strchr(*b,32),32)=0;*b+=!!**b;}

The parameter is an in/out parameter.
See it work here.

Welcome to PPCG!

I'm receiving the following error when compiling with Visual Studio 2012:error C2100: illegal indirection

@JohanduToit VS is not C11 or even C99 conforming. My code is. As practical proof, both gcc and clang compile a valid program.

Clojure, 43 bytes:
#(drop 1(butlast(read-string(str"("%")"))))

Here we read string as an edn data, then choosing its center.

Or for stdout, 57 bytes:
#(apply pr-str(drop 1(butlast(read-string(str"("%")")))))

You can also check it here.

Is the space in str " necessary?

@JonathanFrech it leads to "RuntimeException Unmatched delimiter: )  clojure.lang.Util.runtimeException (Util.java:221)" without space

@JonathanFrech I add link to online Clojure REPL, so you can check it.
UPD: where it works... It's strange.

To me it looks like you changed it in your online REPL, did not change your post and said it would not work ... (TIO).

Powershell, 32 bytes
''+($args|sls ' .+ '|% m*)|% t*m

Test script:
$f = {
''+($args|sls ' .+ '|% m*)|% t*m
}

@(
    ,("Samantha Vee Hills"    ,"Vee")
    ,("Bob Dillinger"    ,"")
    ,("John Jacob Jingleheimer Schmidt"    ,"Jacob Jingleheimer")
    ,("Jose Mario Carasco-Williams"    ,"Mario")
    ,("James Alfred Van Allen"    ,"Alfred Van")
) | % {
    $name,$expected = $_
    $result = &$f $name
    "$($result-eq$expected): $expected"
}

Output:
True: Vee
True:
True: Jacob Jingleheimer
True: Mario
True: Alfred Van

Brainfuck, 98 bytes
>+[,>++++[<-------->-]<]>++++[<++++++++>-]<[>,]++++[<-------->-]<[[-]++++[<-------->-]<]<[<]>>[.>]

Explanation
>+[,>++++[<-------->-]<] Skip input until first space

>++++[<++++++++>-]< Store a Space char incase there is no middle name
[>,] Store input to a char array

++++[<-------->-]<[[-]++++[<-------->-]<] Goto the last space and zero the last space

<[<] Goto the start of the char array
>>[.>] Print the char array

Factor, 17 16 bytes
[ rest 1 head* ]

(-1 byte as 1 head* is 1 byte shorter than but-last.)
Explanation:
It's a quotation (anonymous function) that takes a sequence of strings as input and leaves a sequence of strings as output.

rest Take all elements of a sequence but the first.
1 head* Take all elements of a sequence but the last.

AWK, 9 bytes
NF--,$1=a

Try it online!
NF--,     - Cut out the last argument (also eval's to "true")
     $1=a - Blank out the first argument

Since there's always at least 2 input fields NF--1 is always truthy, so the code prints $0.
In case the leading space isn't allowed (the question was asked in the comments under the initial posting but there was no response), then this is the shortest I've come up with.
AWK, 15 bytes
NF-=sub($1FS,a)

Try it online!
    sub($1FS,a)  - Remove the first field, plus space from the input
NF-=             - Decrement "NF" by one (the return from "sub")

Nice NF-- trick, but this outputs with one leading space, which I don't think is allowed.

I couldn't tell if the leading space was allowed or not.  Several people asked the in the comments about the question, but there was no response from the person who submitted it.  I saw a couple others that seems to have a leading space though, so I assumed it was ok?

Then out of curiousity, because I don't know much awk, how would you golfily fix this to remove the leading space? I've got https://tio.run/##SyzP/v/fz01XV01NxchWiUNJxUhHxdA28f//4Pzc1JKMzLx0Bdec4lQA so far

Ha!  I've been pondering ways to get rid of the leading space too...  I'll post the one I came up with as an alternative in my answer.

Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes
pq

Try it online!
pq
 q # Remove the tail
p  # Remove the head

Python 2, 42 19 16 Bytes
lambda n:n[1:-1]

Try it online! Thanks to @Kritixi Lithos for saving 23 bytes! Thanks @math_junkie for saving 3 more bytes. For input, put each part of the name as a string within a list like so:
["Samantha", "Vee", "Hills"]

And yes, the OP has approved a list to be a valid input.
Explanation
lambda n:n[1:-1]    # Returns only the middle elements... pretty literal here

print input()[1:-1] is shorter

Spring slicing sure is tricky

lambda n:n[1:-1] is even shorter

I may have tried with a wrong input. But when I tried, with Samantha Vee Hills as input in repl.it link that you've shared, this just prints amantha Vee Hill which is definitely not the output required.

@KeerthanaPrabhakaran The program accepts a list and not a string

@KeerthanaPrabhakaran The input should be ["Samantha", "Vee", "Hills"]

Names will always have at least 2 space-separated parts is the first point of the question right.

@KeerthanaPrabhakaran The OP said that the input can be a list.

Oh alright. That was a part of comment and didn't notice that.

APL (Dyalog), 8 6 bytes
¯1↓1↓⊢

Try it online!
This is a tacit train.
Explanation
When ↓ is a dyad, it returns all but the first/last n elements of its vector argument.
   1↓                  ⍝ Remove the first element in the
     ⊢                 ⍝ right argument
¯1↓                    ⍝ and remove the last element

C++, 91 bytes
#import<list>
#import<string>
void f(std::list<std::string>&n){n.pop_front();n.pop_back();}

Takes input as a reference to a list of strings and modifies the list directly.
Try it online!

Bash, 31 19 bytes
echo ${@:2:$[$#-2]}

Try it online!
Breakdown:
Prints parameter expansion from second to second last element.
Edit
Removed commented code from breakdown section, since it's now just one line long.
-12 bytes thanks to Neil

Can you not just echo the expression in the first line directly?

@Neil How can I do that, if the result of the expression is not $@?

Surely set -- assigns the result of the expression to $@?

@Neil Took me way too long to understand what you mean. This is embarrasing...

C (gcc), 144 139 91 86 bytes
y,z;char*f(char*s){for(y=0;*++s-32;);for(;s[y];y++)z=s[y]-32?z:y;z[s]=0;return!!*s+s;}

Try it online!
-48 bytes by learning C over the past year and a half since I first posted this
-7 bytes from Jonathan Frech
A function that takes in a char* and outputs a char* corresponding to the (character after the) first space in the string, but also edits the string so that it's last space is replaced with \0.
Note: this function will segfault if given a string without a space in it.
Full program:
y;z;char*f(char*s){y=0;while(*++s-32);while(s[y]){z=s[y]-32?z:y;y++;}s[z]=0;return s+!!*s;}
int main(int argc, char *argv[]){
	for (int i = 1; i < argc; ++i)
		printf("%s\n",f(argv[i]));
}

Un-golfed:
char *middle(char* name) {
	int index = 0, lastspace;
	while(name[0] != ' ') // move name pointer forward to the first space
		++name;
	while(name[index] != '\0') { // find the index in the (new) string of the last space
		if (name[index] == ' ') lastspace = index;
		index++;
	}
	name[lastspace] = '\0'; // Terminate the string at the last space
	if (name[0] == '\0') return name; // If the last space was the first space, return the empty string
	else return name + 1; // Else, return the new string
}

Try it online!

86 bytes.

68 bytes

Ruby, 13 bytes
->s{s[1..-2]}

The author confirmed in comments that the input and output can be arrays.

REXX, 42 bytes
arg a
say delword(delword(a,words(a)),1,1)

CJam, 6 bytes
{1>W<}

Anonymous block that expects an array of strings on the stack, and leaves an array of strings after.
Try it online!
Explanation
1>    e# Slice the array after the first element
  W<  e# Slice the array before the last element

Japt, 3 bytes
Å¯J

Try it or run all test cases

Alternative: s1J

Oh, I posted an answer over a year ago. I'm gonna update it to s1J if you don't mind.

Pip -s, 8 bytes
@<@>Ya^s

Try it online!
-1 from DLosc.

8 bytes, and you'll need the -s flag to handle cases with multiple middle names. If you take an array as input (using the -x flag--not available on TIO), you don't need the ^s and can therefore drop the Y. Or, if it's okay to take each of the name parts as a separate command-line argument (which is what you'd have if you typed them space-separated on the command line), you can use g instead of Ya^s.

Thanks! I'm keeping the 8byte version for now.

Perl 5 + -p040, 13 bytes
$_ x=$.>1&/ /

Try it online!
Explanation
With -p, input is implicitly stored in $_, the 040 flag makes space the line terminator which means the code is called for each word/name in the input. x= is the in-place string repetition operator which modifies the string in place (e.g. $_="abc";$_ x=3;# "abcabcabc") and the condition is $.>1 ($. is set to the current 'line' number, although since space is our line end character this is word/name number) &ed with / / (if $_ m//atches  , which it will for all but the last word/name). Because of -p the result (the string repeated zero or one times depending on the conditional) is implicitly printed.

GolfScript, 6 bytes
~(;);`

Try it online!
Input is taken in the form of ["name""name""name"]. Input string is converted to an array, then the first and last elements are separated and discarded, and the result is formatted and outputted.

Dash, 24 bytes
g=\ ${*#* };echo ${g% *}

Try it online!
Input via args.
Also handles the unmentioned case of a single name being provided, returning nothing.
While this feels not that clever compared to the posted bash answer, that answer doesn’t work in Dash and this is the best I could muster within its restrictions.

Vyxal S, 2 bytes
ḢṪ

Try it Online!
Removes head and tail of list. S flag joins by spaces.

K (ngn/k), 25 24 bytes
{" "/*(1;-1+#t)_t:" "\x}

Try it online!
Down 1 byte by using assignment in expressions
Does the same thing as the APL answer.
Explanation:
{" "/*(1;-1+#t)_t:" "\x}    Main function. Takes x as input
                  " "\x     Split x by whitespace
                t:          Assign to variable t
      (       )_            Then delete the following elements in t:
       1;                   The first element, followed by
            #t              The length of t
         -1+                - 1
                            Delete returns back the string as an array, so we need to
     *                      Get the first element of the array
 " "/                       And joined each element in the sub-array by whitespace
                            This is to handle cases like "James Alfred Van Allen",
                            where the result after delete will be ["Alfred", "Van"]

Ruby -p, 20 bytes
Basically identical to Yelp’s sed answer and others.
gsub /^\S+ |\S+$/,""

Attempt This Online!

Go, 106 bytes
import."strings"
func f(s string)(o string){l:=Split(s," ")
if k:=len(l);k>2{o=Join(l[1:k-1]," ")}
return}

Attempt This Online!

Thunno 2 Ṡ, 2 bytes
ḣṫ

Attempt This Online!
ḣ   # head remove
 ṫ  # tail remove
    # Ṡ flag joins by spaces

Batch, 70 bytes
@set s=.
:l
@if not "%3"=="" set s=%s% %2&shift&goto l
@echo(%s:~2%

The loop concatenates arguments starting with the second, shifting them until the third argument is empty. This results in a leading space, so to remove that I prepend with a . so that I can slice the string (slicing an empty string produces an erroneous result in Batch). If a trailing space on output is acceptable, then for 66 bytes:
@set s=
:l
@if not "%3"=="" set s=%s%%2 &shift&goto l
@echo(%s%

Ruby, 33 bytes
->s{$><<s.split[1..-2].join(' ')}

TI-Basic (TI-84 Plus CE), 131 bytes
Prompt Str0
inString(Str0," →A
length(Str0)–A→L
sub(Str0,A,L→Str0
" →Str2
For(B,1,L
sub(Str0,B,1)+Str2→Str2
End
inString(Str2," →A
L-A→L
sub(Str2,A,L→Str2
" →Str0
For(B,1,L
sub(Str2,B,1)+Str0→Str0
End
Disp Str0

Explanation:
Prompt Str0              # 4 bytes, input user string
inString(Str0," →A       # 10 bytes, store the index of the first space in A
length(Str0)–A→L         # 10 bytes, store the length of the string (after removing the first A characters) in L
sub(Str0,A,L→Str0        # 12 bytes, remove first A-1 and last characters of Str0
" →Str2                  # 6 bytes, temporary string to reverse Str0
For(B,1,L                # 7 bytes, reverse Str0 into Str2
sub(Str0,B,1)+Str2→Str2  # 16 bytes
End                      # 2 bytes
inString(Str2," →A       # 10 bytes, store the index of the first space in A
L-A→L                    # 6 bytes, get new length
sub(Str2,A,L→Str2        # 12 bytesremove first A-1 and last characters of Str2
" →Str0                  # 6 bytes, temporary string to reverse Str2
For(B,1,L                # 7 bytes, reverse Str2 into Str0
sub(Str2,B,1)+Str0→Str0  # 16 bytes
End                      # 2 bytes
Disp Str0                # 3 bytes, display final string with (2 trailing spaces)

Sed, 23 20 bytes
s/\w* (.*) \w*$/\1/

Unlike my last sed entry which involved a pipeline from one sed command to another, this one is just a simple, single command, so I'm only counting the bytes of the sed script.
Edited: Plus a 1-byte penalty for the -r flag. Thank you, Krixti Lithos, for pointing that out!

Can you use the -r flag to save some bytes from escaping the groups?

@Kritixi I could but I'm not sure how to score that. Does it count as 2 bytes for the -r flag or only 1 byte?

It counts as only 1 byte

@Kritixi Thanks! I just found this answer on meta, too. And I see another change I can make to improve it as well.

Python 3, 28 bytes
print(input().split()[1:-1])

Try it online!

Ruby, 17 bytes
$><<$*[1..-2]*' '

Full program, takes input as command line arguments, e.g.:
$ ruby middle.rb john jacob jingleheimer shmidt
jacob jingleheimer

If we don't mind having the result wrapped in quotation marks, can just use:
p$*[1..-2]*' '
$ ruby middle2.rb john jacob jingleheimer shmidt
"jacob jingleheimer"

Of course, we can also just take a list and return a list, which can be as short as a 13 byte lambda.
->s{s[1..-2]}
# usage:
y = ->s{s[1..-2]};
y.call ["john","jacob","jingleheimer","shmidt"] #=> ["jacob", "jingleheimer"]

Japt, 7 3 bytes
s1J

Try it online!
This is essentially Input.slice(1,-1). The -1 wraps around to the last item in the input.

Clojure, 107 bytes
(fn[f](clojure.string/join" "(map #(apply str %)(drop 1(drop-last(take-nth 2(partition-by #(= % \ )f)))))))

Unfortunately drop/drop-last was shorter than subvec.
(defn middle-name [full-name]
  ; Partition the string into a list of names split on spaces, then take every second element
  ;  since partition keeps the spaces
  (let [sub-names (take-nth 2
                    (partition-by #(= % \ ) full-name))]

    ; ... then join the middle names together on a space.
    (clojure.string/join " "
      ; Drop returns list of chars, so turn them back into strings...
      (map #(apply str %)
           ; Drop the first and last name
           (drop 1
             (drop-last sub-names))))))

Lua, 39 bytes
print(io.read("*l"):match(" (.+) .+$"))

c, 53 bytes
main(a,b)char**b;{for(++b;--a>2;printf("%s ",*++b));}

Try it online

Noodel, 5 bytes
Input must be an array of the names.
Ẹ⁻2¤İ

Try it:)

How it works
      # Pushes the input on implicitly.
Ẹ⁻2¤İ
Ẹ     # Takes the last item of an array and pushes it to the back.
 ⁻2   # Pop the first two items off of the array.
   ¤  # Push the string "¤" onto the stack which represents a space.
    İ # Concatenates the array elements by the "¤" string.
      # Implicitly output the top of the stack to the screen.

C#, 72 69 bytes
Takes a string, returns a string...
s=>string.Join(" ",s.Split(' ').Skip(1).TakeWhile(n=>!s.EndsWith(n)))

C# 43 bytes
Takes a string array, returns a string array...
s=>s.Skip(1).TakeWhile((n,i)=>i<s.Length-2)

Pushy, 17 bytes
32K-$.;@$.;.@32+"

Try it online!
32 K-    \ Take away 32 from every character.
         \ Now we have the value 0 where there were spaces.
$        \ Until we reach a zero:
 .;      \   Pop a character from the end
         \ Everything after the last space is now removed
@        \ Reverse stack
$.;      \ Do the same
.        \ Pop the leading space
32+      \ Add 32 to everything to map the numbers back to their original characters
@"       \ Reverse and print

This is the first method I thought of, and looks like the shortest.

c, 72 bytes
g(char*p){char*e,*s=0;for(;*p;p++)*p-32?0:s?(e=p):(s=p);*e=0;puts(s+1);}

Try it online

JavaScript (ES6), 16 Bytes
x=>x.slice(1,-1)

Simple. Return the array passed from the second element to the second from last.

Welcome to PPCG! Nice submission!

Javascript ES6 23Bytes
x=>x.pop()*x.shift()||x
use * instead of && to save 1 byte
Try it online

Tcl, 28 bytes
proc R n {lrange $n 1 end-1}

Try it online!

Gambit Scheme (gsi), 48 bytes
(lambda(x)(if(>(length x)2)(cadr(reverse x))""))

Try it online!

Arturo, 29 bytes
$->a[take drop a 1(size a)-2]

Try it

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


text:
Reuse your code!
In this challenge we try to solve two important problems at once. They are:

Given integers \$a\$ and \$b\$, tell if \$a^b-1\$ is a prime number.
Given integers \$a\$ and \$b\$, return \$a\choose b\$.

Specifically, you must write two programs, one that does the first task and one that does the other. As we want to solve both problems at once, it is encouraged to use a same piece of code in both programs.
Scoring
The score of an answer is the Levenshtein distance between the two programs. Lower score is better. In case of a tie, the answer with the shortest combined code of the two programs wins. You can use this script to calculate the score of your solution.
Rules

You must write two programs in the same language that solve the tasks described above. You can use any I/O methods you want. For task 1, you can return a truthy/falsy value or choose two values to mean true and false and return them accordingly. Eg. you can choose that "prime" means true and "not prime" means false.

The algorithms you use must work for all possible inputs, but it is OK if the code fails for large numbers due to limitations of the used number type. You can assume that the input is valid.

No subset of the program must solve the problem, ie. the code must not work if any character(s) are removed. For example, the following code is not valid, because it is possible to remove the unused else-block without breaking the program:
 if (1) { /* change to 0 to get the second program*/
     ...
 } else {
     ...
 }

Standard loopholes are not allowed.

Test cases
\$a^b-1\$ is prime?
a b
1 1 false
2 3 true
5 2 false
2 5 true
4 3 false
2 7 true

\$a\choose b\$
a b nCr(a,b)
1 1 1
5 2 10
4 3 4
10 7 120
12 5 792

This may be handy to compute Levenshtein distance

The idea is nice, but I think you'll still get solutions with Levenshtein distance 1 that manage to prevent modifications to unused parts one way or another and then effectively result in the structure you want to prohibit.

@LuisMendo The issue is that many of those solutions are really slow. You can use this Mathics script instead.

I think a better metric would have been the Levenshtein distance divided by the total length of the two programs.

@GregMartin Wouldn't that result in code bowling? It is possible to artificially make programs larger and still claim that they don't have any unnecessary code.

What does tell us if mean? Are truthy/falsy values allowed? Do they have to be consistent?

Also, you say given integers. Can we assume the integers are non-negative? Can we assume that a in task 1 is positive? Can we assume that a ≥ b in task 2?

@Dennis You can return a truthy/falsy value or choose two values and use them consistently. However, the truthy/falsy value doesn't need to be consistent. You can assume that the input is always valid. I added clarifications to the post.

Ruby, Distance 1, Combined Length 194
Prime check:
->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][0]';require'math'<<s.size*2;eval s}

Try it online!
nCr:
->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][1]';require'math'<<s.size*2;eval s}

Try it online!
As predicted in the comments, some jerk always has to go against the spirit of the problem. It was fun finding a way to work around it, though! Here's how it works: We have two separate solutions to the problems. We run both, put them into an array, and then either choose the 0th element or the 1st, for an edit distance of 1. This would ordinarily be illegal, since you could just delete everything but the calculation you wanted and it would still work. However, each code snippet is written to rely on the loading of the same standard library, 'mathn':

The first uses its builtin prime?
The second relies on mathn changing how division works--before loading it, 3/4 evaluates to 0, while afterwards it evaluates to the fraction (3/4). Since the intermediate result of (a+1-i)/i is not always a whole number, the overall result is wrong without the library.

Now we just need to make loading the library contingent on the rest of the code being unmodified. We do this by generating the name mathn using the character length of the rest of the main code: the combined calculation has length 55, which doubled to 110 is the ASCII value of 'n'. So concatenating this onto the string 'math' gives the desired library.
As a bonus, introducing the library dependencies also makes the code run in a reasonable amount of time. In particular, the naive approach to nCr wouldn't generate fractional intermediate results.

MATLAB, distance 10
Primality:
function x=f(a,b);x=isprime(a^b-1);

nCr:
function x=f(a,b);x=nchoosek(a,b);

That's the built-in I was searching for!

PHP, distance 29
a^b-1 prints 0 for true and any integer value > 0 for false
[,$a,$b]=$argv;for($c=-$i=1;$i<=$d=$a**$b-1;$d%++$i?:$c++);echo$c;

nCr(a,b)
[,$a,$b]=$argv;for($c=$i=1;$i<=$a;$c*=$i**(1-($i<=$a-$b)-($i<=$b)),$i++);echo$c;

PHP, distance 36
a^b-1 prints 1 for true nothing for false
[,$a,$b]=$argv;for($c=-1,$i=1;$i<=$d=-1+$a**$b;)$d%++$i?:$c++;echo$c<1;

nCr(a,b)
[,$a,$b]=$argv;for($c=$d=$i=1;$i<=$a;$c*=$i++)$d*=$i**(($i<=$a-$b)+($i<=$b));echo$c/$d;

05AB1E, distance 3
nCr
sc

Try it online!
isPrime(a^b-1)
m<p

Try it online!

Stacked, distance 13
[([@.!]$/{%y!x y-!*})fork!]
[^#-:([]1/$%{!n 1-!})fork!=]

Try it online! The first calculates nCr, the second primality, using Wilson's theorem.
(f g h) fork! pops N args from the stack (call them a0 ... aN)  and applies a0 ... aN f a0 ... aN h g.
For the first program:
[([@.!]$/{%y!x y-!*})fork!]
[(                  )fork!]  apply the fork of:
  [@.!]                      equiv. { x y : x ! } => `x!`
       $/                    divided by
         {%        }         two-arg function
           y!                y!
             x y-                 (x - y)!
                 *              *

And for the second:
[^#-:([]1/$%{!n 1-!})fork!=]
[^                         ]  exponentiate  (a^b)
  #-                          decrement     (a^b-1)
    :                         duplicate     (a^b-1 a^b-1)
     (              )fork!    apply the fork to:
      []1/                    1-arg identity function
          $%                  modulus by
            {!     }          1-arg with `n`:
              n 1-             (n-1)
                  !                 !
                          =   check for equality

Python 2, distance 15, length 172
Task 1
D=lambda k:max(k-1,1)
P=lambda n,k=0:n<k or P(n-1,k)*n/k
lambda a,b:P(a**b-2)**2%D(a**b)

Task 2
D=lambda k:max(k-1,1)
P=lambda n,k=1:n<k or P(n-1,D(k))*n/k
lambda a,b:P(a,b)/P(a-b)

Try it online!

Mathematica, distance 10
Task 1: PrimeQ[#2^#-1]&
Task 2: Binomial[#2,#]&
Both functions take the inputs in the order b,a.

Javascript ES7, distance 14
Thanks @Conor O'Brien for reducing the distance by 7
Primality:
f=x=>y=>{t=x**y-1;s=1;for(i=2;i<t;i++){if(!t%i)s=i-i}return s}

Returns 1 if prime returns 0 if not prime.
Incredibly inefficient prime check, checks the number modulo every number smaller than it and greater than 1...
nCr:
f=x=>y=>{t=x+1;s=1;for(i=1;i<t;i++){if(y<i)s*=i/(i-y)}return s}

Multiplies 1 by each number from y+1 to x and divides by each number from 1 to x-y (x!/y!)/(x-y)!

Changing the second program to f=x=>y=>{t=x+1;s=1;for(i=1;i<t;i++){if(y<i)s*=i/(i-y)}return s} gives edit distance 14. Try it online!

Octave, distance 17 16 15
nCr
a=input("");b=input("");f=@(x)factorial(x);printf("%d",f(a)/f(b)/f(a-b))

Try it online!
isprime(a^b-1)
a=input("");b=input("");f=@(x)isprime(x);printf("%d",f(a^b-f(8-6)))

Try it online!
I am not very fluent in Octave, so I don't know if there is a builtin to calculate nCr.

MATL, distance 4, length 6
Tell if a^b-1 is prime:
^qZq

Try it online!
Compute nCr(a,b):
Xn

Try it online!
How it works
Tell if a^b-1 is prime:
^      % Power with implicit inputs
q      % Subtract 1
Zq     % Is prime? Implicit display

Compute nCr(a,b):
Xn     % nchoosek with implicit inputs. Implicit display

Pyth, distance 4, total length 8
Primality of a^b-1
P_t^F

Try it online!
nCr(a, b)
.cF

Try it online!
Both take input as tuples/lists of integers (e.g. (1,2)).

PHP, distance 14
Writing a program with two functions and only calling one of them would lead to a distance of 1, but it´d be too lame.
Prime Test, 100 bytes:
[,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n%$i;);return$i==1;}echo f($a**$b*-1)*(1|f($a-$b));

nCr, 98 bytes:
[,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n*=$i;);return$n*=1;}echo f($a)/(f($b)*f($a-$b));

Jelly, distance 4, length 5
Task 1
*’ÆP

Task 2
c

Try it online!
How it works
Task 1
*’ÆP  Main link. Argument: a, b

*     Yield a**b.
 ’    Decrement; yield a**b-1.
  ÆP  Test the result for primality.

Task 2
c     nCr atom

JavaScript, Score:1, Length:144 142 126 117
function(a,b){s="a=Math.pow(a,b)-t;for(b=2;a%b++;);b>a1for(;b;)t=t*a--/b--";t=s.length-56;return eval(s.split(1)[0])}

    function(a,b){s="a=Math.pow(a,b)-s.length+79;for(b=2;a%b++;);b>a1for(t=s.length-79;b;)t=t*a--/b--";return eval(s.split(1)[1])}
function A(a,b){a=Math.pow(a,b)-(B+0).length+63;for(b=2;a%b++;);return b>a;}
function B(a,b){for(t=(A+0).length-76;b;)t=t*a--/b--;return t;}
F=A

Both subroutines use the other one's length to calculate its own constant, so no char can be removed

source: Stack Exchange

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

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

sort: votes


text:
Pigeonhole Principle & Code Golf
The pigeonhole principle states that

If N items are put into M boxes, with N > M, then at least one box must contain more than one item.

For many, this principle has a special status compared to other mathematical enouncements. As E.W. Dijkstra wrote,

It is surrounded by some mystique. Proofs using it are often regarded as something special, something particularly ingenious.

The challenge
The purpose of this challenge is to illustrate the pigeonhole principle using ASCII art representations. Specifically:

Take as input N (number of items) and M (number of boxes), with N non-negative and M positive. N may be smaller than M (even if the principle does not apply in that case).
Randomly select one of the possible assignments of items to boxes. Each assignment should have a non-zero probability of being picked.
Produce an ASCII art representation of the assignment as follows:

There are M lines, each corresponding to a box.
Each line starts with a non-whitespace character, such as |.
Following that character is another non-whitespace character, such as #, repeated as many times as there are items in that box.

Consider for example N = 8, M = 5. If the selected assigment of items to boxes is 4, 1, 0, 3, 0, the representation is
|####
|#
|
|###
|

A different run (resulting in a different assignment) of the same program could give
|#
|##
|#
|#
|###

There is some flexibility regarding the representation; see below.
Specific rules
The code should theoretically run for any values of N and M. In practice it may be restricted by memory size or data type limitations.
Since observing the output is not sufficient to determine if all assignments have non-zero probability, each submission should explain how the code achieves that, if not obvious.
The following representation variations are allowed:

Any pair of different, non-whitespace characters can be chosen. They must be consistent across program executions.
90-degree rotations of the representation are acceptable. Again, the choice must be consistent.
Trailing or leading whitespace is allowed.

As an example with a different representation format, for N = 15, M = 6 the results of two executions of the program could be
VVVVVV
@@@@@@
@@ @@@
 @  @@
    @

or
VVVVV
@@@ @
@@@ @
@ @ @
@ @ @
@

Likewise, N = 5, M = 7 could give, using another variation of the representation,
  *
* * * *
UUUUUUU

or
 *** **
UUUUUUU

or
   *
*  *
*  *
UUUUUUU

Note how the principle is not applicable in this case, because N <M.
General rules
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Input can be taken by any reasonable means; and with any format, such as an array of two numbers or two different strings.
Output means and format are also flexible. For example, the output can be a list of strings or a string with newlines; returned as function output argument or displayed in STDOUT. In the latter case it is not necessary to worry about line wrapping caused by limited display width.
Shortest code in bytes wins.

It actually took me until now to get the title...

@MartinEnder Is it that "pigeonhole principle" has more characters than "code golf", or is there some other joke?

@dorukayhan In a standard browser, look at the text slightly above the question title...

Jelly, 9 8 bytes
=þṗX¥S⁵*

This is a dyadic link that takes M as its left and N as its right argument. Output is an array of integers, where 0 represents pigeons and 1 represents holes.
Try it online!
How it works
=þṗX¥S⁵*  Main link. Left argument: m. Right argument: n

    ¥     Combine the two links to the left into a dyadic chain and call it
          with arguments m and n.
  ṗ        Compute the n-th Cartesian power of [1, ..., m], i.e., generate all
           vectors of length n that consist of elements of [1, ..., m].
   X       Pseudo-randomly choose one of those vectors with a uniform distribution.
=þ        Equal table; for each k in [1, ..., m] and each vector to the right,
          compare the elements of the vector with k. Group the results by the
          vectors, yielding a 2D Boolean matrix.
     R    Range; map 1 to [1], 0 to [].
      S   Take the sum of all columns.
       ⁵* Raise 10 to the resulting powers.

Mathematica, 68 bytes
Print/@(10^RandomSample@RandomChoice[IntegerPartitions[+##,{#}]-1])&

An unnamed function that takes two integer arguments, the number of boxes, followed by the number of items.
It first computes all possible partitions of N+M into exactly M positive parts, and subtracts 1 from each partition afterwards. This gives us all possible partitions of N into M non-negative parts (which IntegerPartitions wouldn't generate otherwise). Then pick a random partition and shuffle it. This guarantees all possible ordered partitions with zeros are allowed. Finally, convert each bin of the partition to an output line by raising 10 to the corresponding power (such that each line becomes 1000... with k zeros). An example output might look like:
100
10000
1
10
10

I believe PadRight wouldn't pad to M zeros if N < M.

@LegionMammal978 Thanks, managed to fix it at the same byte count.

...I'm honestly impressed. I was about to do a similar solution, but PadRight's non-listability would make it much longer.

@LegionMammal978 Another way to avoid PadRight would be IntegerPartitions[#,{#2},0~Range~#].

No buitltin? I'm surprised... :D But nice answer. I just need to figure out how it works first :P

@HyperNeutrino I'm happy to improve the explanation of you let me know what's unclear.

Oh no, I understand what it means now that I read the explanation. I didn't understand it the first time through because I somehow missed a line while reading.

Python 2, 77 86 bytes
from random import*
n,m=input()
exec'c=randint(0,n);n-=c;print 10**c;'*~-m
print 10**n

Generates a number in [0, n], prints that many items and substracts it from n. It does this m times.
This makes it very unlikely anything makes it to the last box, but the question only asked that every output be possible, not equally likely.

Batch, 164 bytes
@for /l %%i in (1,1,%1)do @set h%%i=1
@for /l %%j in (1,1,%2)do @call set/ab=%%random%%%%%%%1+1&call set/ah%%b%%*=10
@for /l %%i in (1,1,%1)do @call echo %%h%%i%%

I think 7 consecutive % signs might be a new personal best! Note: this produces odd output should it ever assign more than 9 items to the same box; if that's a problem, then for 180 bytes:
@for /l %%i in (1,1,%1)do @set h%%i=1
@for /l %%j in (1,1,%2)do @call set/ab=%%random%%%%%%%1+1&call call set h%%b%%=%%%%h%%b%%%%%%0
@for /l %%i in (1,1,%1)do @call echo %%h%%i%%

Yes, that's 28 %s in total on the second line.

C, 102 bytes
n,m;main(x){srand(time(0));for(scanf("%d %d",&n,&m);m--;n-=x)printf("|%0*s\n",x=m?rand()%(n+1):n,"");}

Takes input on stdin, e.g.:
echo "5 4" | ./pigeonhole

Won't generate each output with equal probability, but is capable of generating all possible combinations.
Breakdown:
n,m;
main(x){
    srand(time(0));             // Seed random number generator
    for(scanf("%d %d",&n,&m);   // Parse input values into n and m
        m--;                    // Loop through each bucket (count down)
        n-=x)                   // Subtract number assigned to bucket from total
        printf(                 // Output a formatted string using padding
            "|%0*s\n",          // (turns out %0s will actually zero-pad a string!)
            x=m?rand()%(n+1):n, // Calculate a number of items for this bucket
            "");
}

Relies on GCC's handling of the undefined behaviour of %0s — normally %0 will zero-pad an integer or float, but it can only pad (never truncate), so it's not possible to print a blank. But the behaviour for strings isn't defined, and GCC decided to make it zero-pad the same way, so this zero-pads an empty string to be able to write zero-or-more 0s.

Since functions are allowed, you could cut off a few characters by using a(b,c){...} instead of main and scanf.

Python 2, 102 99 97 90 bytes
m-1 times, chose a random amount x between 0 and n, inclusive and subtract it from n. Then print a 1 and '0'*x.
Finally, print 1 and the rest of 0s. Not at all equal chances, but all configurations are possible.
from random import*
n,m=input()
exec'x=randrange(n+1);n-=x;print 10**x;'*(m-1)
print 10**n

(Reused code from the broken Python answer.)

I think this answer should've been a suggestion on my answer as it's literally the same answer with a small bug fix.

@orlp If you look at the history of this answer, it just became that in the latest version. If I would have made it like this initially, I would have posted it as a comment instead.

Ah then it's fine, the way it looked (and that you wrote 'reused code') made it look differently than it is. Sorry.

@orlp No problem. Yours is working now and shorter than mine anyways, I can also delete this answer if you feel that it is too close to yours, I don't mind, just wanted to clarify that I didn't just copy-paste your answer.

Haskell, 114 94 bytes
import System.Random
n#m=map(10^).take m.until((==n).sum.take m)tail.randomRs(0,m)<$>newStdGen

A bit of a brute force approach: Generates an infinite list of random numbers, takes n numbers of the start of the list, sums them up, and checks if they're equal to m. If not, take the first element off the list and repeat.
Try it online!
Note: 73 bytes without the import
EDIT: Saved some bytes with the 10^ trick (Try the new version online!)

C, 175 138 bytes
Thanks to @Dave for saving 37 bytes!
i;f(n,m){char**l=calloc(m,8);for(i=0;i<m;)l[i]=calloc(n+1,1),*l[i++]=124;for(i=n+1;--i;)*strchr(l[rand()%m],0)=35;for(;i<m;)puts(l[i++]);}

Try it online!

Hi, a few things which could help you reduce this: calloc will give you 0-initialised memory (no need to set all the 0s yourself), strchr can find the end of a string, comma can chain operations, avoiding the need for {}, and x[0] == *x. Also watch out; you're not mallocing enough memory if all the items are in the same box.

CJam, 30 31 21 bytes
:B1a*:C\{CBmrAt.*}*N*

Input is two numbers n m on the stack. Uses 1 for the column character and 0 for the repeated character.
Explanation:
:B          e# Store m in B (without deleting it from the stack)
1a          e# Push 1 and wrap it in an array: [1]
*           e# Repeat the array m times
:C          e# Store this array in C (without deleting)
\{          e# Do n times:
  CBmrAt    e#   Create an array of 1s with a random element replaced with 10.
  .*        e#   Vectorized multiplication: multiply the respective elements in the arrays.
            e#   Effectively, we multiply a random value in the array by 10 (and add a 0 to the end).
}*          e# End loop.
N*          e# Join with newlines.

REXX, 74 bytes
arg n m
m=m-1
o.=@
do n
  a=random(m)
  o.a=o.a||#
  end
do a=0 to m
  say o.a
  end

Output (8 5):
@#
@###
@
@#
@###

Output (8 5):
@#
@#
@
@####
@##

AHK, 66 bytes
2-=1
Loop,%2%{
Random,r,0,%1%
Send,|{# %r%}`n
1-=r
}
Send,|{# %1%}

I followed the same principal that orlp did using random numbers from 0 to N and then subtracting it from N. Unfortunately, I couldn't save bytes by using 10^r because of the way the Send function works. Alas and alack. Here are some outputs for n=8, m=5:
|##     |#####    |##       |##     |#      |##
|##     |#        |#####    |       |###    |#
|#      |##       |         |###    |###    |
|###    |         |         |       |#      |
|       |         |#        |###    |       |#####

Röda, 79 bytes
f n,m{a=[0]*m
i=0{{n--
a[i%m]++}if randomBoolean
i++}while[n>0]
a|[`|`.."#"*_]}

Try it online!
This creates an array of zeroes and increments them at random places.

Python 2, 80 95 89 88 bytes
from random import*
n,m=input()
while m:x=randint(0,n);print'1'+'0'*[n,x][m>1];m-=1;n-=x

Try it online!

Added 15 Bytes: Previous edit was a bit flawed, some piegons were left out.
Saved 6 Bytes: replaced if else by [n,x][m>1]
Saved 1 Byte: import *

MATLAB, 103 94 bytes
function a(m,n)
d=@(p)disp(char([1,~(1:p)]+48));for i=1:m-1;p=randi([0,n]);d(p);n=n-p;end;d(n)

With Formatting
function a(m,n)
for i=1:m-1
    d=@(p)disp(char([1,~(1:p)]+48));  % inline function for displaying
    p=randi([0,n]);              % picking a random number b/w 0 and n
    d(p);                        % '1' represents the box/pigeonhole, with '0's denoting entries
    n=n-p;
end
d(n);                            % writing the remaining entries/zeros

Sample Output
>> a(4,7)
10
10000
10
10

There are trailing whitespaces since each array entry is displayed with a tab between them, but this should be acceptable as per specs.
This seems like a very simplistic implementation to me, so I'm sure this could be improved.
Thanks to @Luis Mendo for suggestions.

You can save quite a few bytes defining the display statement as an anonymous function, to avoid writing it twice: d=@(p)disp(char([1,~(1:p)]+48));for i=1:m-1;p=randi([0,n]);d(p);n=n-p;end;d(n)

@LuisMendo Thanks for the suggestion, I'll update. Can I also define my actual function the same way, eg. a=@(m,n)... since that will also reduce the number of bytes. How do people generally remove/shorten the "function name(args)" in MATLAB code-golf answers?

Yes, you could also use an anoymous function as the answer. You can even skip the a=. In this case you can't do that, in principle, because anonymous functions can't contain loops. But you could use the trick of putting everything into eval('...'). BTW, that's normally considered ugly and bad practice in Matlab, but here we like abusing languages :-)

Hmm.. I'll update based on your suggestion and think some more about it and see if I can avoid the loop, though that seems unlikely. I can think of a logic that could do that, but not sure how to implement it.. I'm thinking of defining a number 10^n, and finding m numbers which are all powers of 10, and then just printing them out. It'll be exactly the same output as I have now.. :D Any suggestions? Feel free to post it as another answer.

I meant m factors (not just any numbers)

I wasn't planning on posting an answer, but your suggestion to try to avoid the loop was too tempting :-) BTW if you come up with a totally different approach you can leave this answer if you want and post another one, even if it uses the same language

Nice, @LuisMendo! I also just posted another answer without the for loop: http://codegolf.stackexchange.com/a/115428/67708

I see. Nice approach!

TI-Basic, 63 62 bytes
Prompt N,M
For(A,1,M
N→B
If M-A
randInt(0,N→B
":→Str0
For(C,1,B
Ans+"X→Str0
End
Disp Ans
N-B→N
End

Each assignment should have a non-zero probability of being picked.

This criteria made this program much easier to write.
Example I/O:
prgmPIDGEON
N=?5
M=?2
:XXXX
:X

Explanation:
Prompt N,M     # 5 bytes, input number of items, number of boxes
For(A,1,M      # 7 bytes, for each box
N→B            # 4 bytes, on last box, make sure the sum is met by adding N items
If M-A         # 5 bytes, if not last box
randInt(0,N→B  # 8 bytes, add random number of items from 0 to N to box A
":→Str0        # 6 bytes, first character
For(C,1,B      # 7 bytes, add B items to the box
Ans+"X→Str0    # 8 bytes
End            # 2 bytes
Disp Ans       # 3 bytes, print this box
N-B→N          # 6 bytes, subtract the items used in this box
End            # 1 byte, move on to next box

Python 2, 81 bytes
from random import*
def f(n,m):l=['#']*m;exec('l[randrange(m)]+="o";'*n);return l

Returns a list of strings.

Javascript (ES7), 75 bytes
(N,M)=>{for(r='';M;M--,N-=x=~~(Math.random()*(N+1)),r+=10**x+`
`);return r}

I thought I was clever for coming up with the powers of 10 idea only to realize that most answers were already using that.

AWK, 78 bytes
{srand();for(;n++;)c[k]=c[k=int($2*rand())]"#"}END{for(;j<$2;)print"|"c[j++]}

Takes 2 arguments, first the number of items, then the number of boxes.  Starts by seeding the random number generator so each run is different. Then simply builds up strings in an array,
Example usage:
awk '{srand();for(;n++;)c[k]=c[k=int($2*rand())]"#"}END{for(;j<$2;)print"|"c[j++]}' <<< "12 5"

Example output:
|##
|###
|##
|##
|###

JavaScript, 105 bytes
x=>y=>{s=[];for(;x>1;y-=t)s[--x]="|"+"#".repeat(t=Math.random()*(y+1)|0);s[0]="|"+"#".repeat(y);return s}

Try it online!
Due to the method of assigning the rows, this will tend to place more towards the bottom, although there is a small chance that the top will get some.

PHP, 100 bytes
list($z,$m,$n)=$argv;$a=array_fill(0,$n,z);while($m>0){$a[rand(0,$n-1)].=a;$m--;}echo join("\n",$a);

Breakdown :
list($z,$m,$n)=$argv;     // assigns the input vars to $m and $n
$a=array_fill(0,$n,z);    // creates an array $a of $n elements containing 'z'
while($m>0){              // randomly populate array $a
    $a[rand(0,$n-1)].=a;  //
    $m--;                 //
}                         //
echo join("\n",$a);       // output $a contents separated by a new line

Outputs for m=7 and n=5 :
First execution :
za
zaa
za
za
zaa

Second execution :
za
zaa
zaaa
z
za

Try it online!

You could use [,$m,$n]=$argv; from PHP 7.1 to save a few chars. You can replace \n with an actual line break to save 1 byte. you can use for(;$m-->0;)$a[rand(0,$n-1)].=a; to save the breaks, a $m and a semicolon. [,$m,$n]=$argv;$a=array_fill(0,$n,z);for(;$m-->0;)$a[rand()%$n].=a;echo join("\n",$a); 85 byte

This golfs down even further [,$m,$n]=$argv;for(;$m--;)${rand()%$n}.=a;for(;$n--;)echo"z${$n}\n"; 67 byte.

@Christoph I saw the notation [,$m,$n]=$argv; on other code-golfs but wasn't able to make it work either in my dev environment or on eval.in

try it here: http://sandbox.onlinephpfunctions.com/code/704d86b3fd03dfcf3ff8314bb8e13794f946ea1a.

Nice. I think you can post your snippet as an answer since it differs quite a lot from mine ;)

Ruby, 52 bytes
->(n,m){r=Array.new(m){?|};n.times{r[rand m]+=?#};r}

Creates an anonymous function which takes two integers as arguments and returns an array of Strings:
>> puts ->(n,m){r=Array.new(m){?|};n.times{r[rand m]+=?#};r}.call 7,5
|#
|#
|##
|##
|#

Octave, 62 54 bytes
@(n,m)strcat(62,(sum(randi(m,1,n)==(1:m)',2)>=1:n)*42)

Anonymous function that takes two numbers and outputs a 2D array of chars with > for boxes and  * for objects. All results are equally likely.
Try it online!

MATLAB, 73 64 58 bytes
Update#3
I do need the sorting, it seems, since otherwise I get negative integers. I did replace disp(sprintf(...)) with fprintf(...) now, though, so the answer remains 58 bytes.
@(m,n)fprintf('%i\n',10.^diff([0;sort(randi(n,m-1,1));n]))

Update#2:
I realized I didn't need to sort the array, and in fact sorting would actually reduce the average of numbers in the array. So I deleted the sort(...) part. Note that the output remains the same, so I am not updating the "sample output".
@(m,n)disp(sprintf('%i\n',10.^diff([0;randi(n,m-1,1);n])))

Finally closing in on the Octave answer by Luis! :D
Update#1:
@(m,n)disp(sprintf('%i\n',10.^diff([0;sort(randi(n,m-1,1));n])))

Instead of converting to string, I just display numbers directly. I could reduce to 58 bytes, by removing the disp(...), but then I get the extra ans = with just sprintf, and don't know if that's acceptable.
Initial code:
@(m,n)disp(strjust(num2str(10.^diff([0;sort(randi(n,m-1,1));n])),'left'))

Thanks to some suggestions by Luis, I got rid of the loop in my previous answer. Now I first create a vertical array of m random numbers adding up to n (diff([0;sort(randi(n,m-1,1));n])), then use them as exponents of 10, convert them to a string, left-justify them, and display them.
I could technically get rid of the disp(...) to save another 6 bytes, but then an "ans" gets printed which may violate specs. There may also be a way around to changing them to string and left-justifying to get the desired end format, so I'm open to suggestions.
Sample output:
>> a=@(m,n)disp(strjust(num2str(10.^diff([0;sort(randi(n,m-1,1));n])),'left'));
>> a(4,6)
1000
10
100
1

Note: I have changed my function to an anonymous function here, based on suggestions. In the sample output, I have assigned that to a in order to demonstrate. I hope this does not violate specs, but if it does please let me know and I will change it.

I just realized the top answer uses the same logic of 10^.. For what it's worth, and if it matters, I didn't use that as a reference for my answer.. (but dang, someone beat me to it! :P)

Also wanted to note credit to this answer for the idea of creating m random integers that add up to n, since I was stuck on that part for a long while.. (Still can't add more than 2 links in my answers, so including it in a comment)

Stacked, 29 bytes
('|')\rep\[:randin'#'push@.]*

Try it online!
Behaves by constructing an array of M singletons containing '|', then adding '#' to a randomly chosen array N times.

Nice! And so all results are equally likely, right?

@LuisMendo it should be, since randin uses the Fisher-Yates algorithm internally. (This is the same algorithm that the CJam answer uses FWIW)

Charcoal, 19 bytes
≔ＥＮ⟦⟧θＦＮ⊞‽θ#Ｅθ⁺|⪫ιω

Try it online! Link is to verbose version of code. Explanation:
  Ｎ                 Input `M`
 Ｅ                  Map over implicit range
   ⟦⟧               Empty array
≔    θ              Assign resulting nested array to `q`

       Ｎ            Input `N`
      Ｆ             Loop over implicit range
          θ         Nested array `q`
         ‽          Random element
           #        Literal string
        ⊞           Append to array

             θ      Nested array `q`
            Ｅ       Map over array
                 ι  Current element
                  ω Empty string
                ⪫   Join
               |    Literal string
              ⁺     Concatenate
                    Implicitly print on separate lines

Vyxal j, 19 bytes
Ṅ'L⁰≤;℅₅⁰εð*ƛ0;JÞ℅↵

Try it Online!
Ṅ                   # The partitions of the first number
 '   ;              # Filtered by...
  L⁰≤               # Length is less than or equal to the second input
      ℅             # Choose a random item of this
       ₅            # Get length
        ⁰εð*        # Subtract from second input, and get that many spaces
            ƛ0;     # Fill with 0s
               J    # Append this to the current string
                Þ℅  # Get a random permutation of this
                  ↵ # 10 to the power of each item of this

Japt -R, 17 (15?) 16 (14?) bytes
@¶Xx}a@ô öVÃ£ApX

Try it
If we don't have to allow for the possibility of all N items ending up in the same box then we can save 2 bytes:
@¶Xx}a@öVÃ£ApX

Try it
@¶Xx}a@ô öVÃ£ApX     :Implicit input of integers U=N & V=M
@                    :Left function, taking an array X as argument
 ¶                   :  Is U equal to
  Xx                 :  X reduced by addition
    }                :End function
     a               :Get the first result of the right function that returns true when passed through the left one
      @              :Right function
       ô             :  Range [0,U]
         öV          :  Get V random elements (or V random elements in [0,U) if ô is omitted)
           Ã         :End function
            £        :Map each X
             A       :  10
              pX     :  Raised to the power of X
                     :Implicit output joined with newlines

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