text:
Given a truth table, output a Stackylogic program that satisfies it
Stackylogic is a programming language I made up in a previous challenge: Run Stackylogic. Read that post for full details and examples, but here is how it works paraphrased:

Stackylogic takes 0's and 1's for input and outputs a single 0
  or 1 upon completion.
A program consists of lines that only contain the characters 01? as
  well as exactly one < at the end of one of the lines. Lines may not
  be empty and the line with the < must have at least one 0, 1, or
  ? before it.
Here's a sample program that computes the NAND of two bits:
1
?<
11
?
0

Every line in a program is considered a stack, with the
  bottom on the left and the top on the right. Implicitly, there is an
  empty stack (i.e. empty line) before the first line in a program and after the last
  line.
The <, called the cursor, marks the stack to start on
  when a program is run. Execution proceeds as follows:

Pop the top character off the stack the cursor is currently pointing to.

If the character is ?, prompt the user for a 0 or a 1 and act as if that was the character.
If the character is 0, move the cursor one stack up (to the line above the current line).
If the character is 1, move the cursor one stack down (to the line below the current line).

If the stack the cursor moves to is empty, output the last value that was popped off a stack (always a 0 or 1), and end the
  program.
Else, if the stack the cursor moves to is not empty, go back to step 1 and repeat the process.

The key thing to realize for this challenge is that all Stackylogic programs equate to a truth table. Some predetermined number of boolean values are input and exactly one boolean is deterministically output.
So your task is to produce a Stackylogic program that satisfies or simulates, i.e. has the same output as any given truth table. But it's not obvious that Stackylogic can simulate any truth table, so here's a proof by induction:

Base Case
The two 0-input truth tables are the tables that always output 0 or
  1. The Stackylogic equivalents of these tables are 0< and 1<
  respectively.
Inductive Step
Assume Stackylogic can simulate any N-input truth table. Let M = N +
  1.
An M-input table, T, can be expressed as two N-input tables,
  T0 and T1, plus the additional input bit B. When
  B is 0, the result of T0 is used. When B is 1, the result
  of T1 is used.
For example, the 3-input truth table corresponding to the pseudocode
if B:
    result = x OR y
else:
    result = x NAND y

is
B x y | result
0 0 0 | 1
0 0 1 | 1
0 1 0 | 1
0 1 1 | 0
1 0 0 | 0
1 0 1 | 1
1 1 0 | 1
1 1 1 | 1

which is really the two 2-input truth tables for NAND and OR stacked
  atop each other with the muxing bit B.
Let S0 and S1 be the Stackylogic programs that
  satisfy T0 and T1 respectively (we know these exist based on the first assumption). Program S that
  satisfies T can then be constructed as:
[lines of S0 excluding the cursor, with 0 appended to all lines below the cursor]
?<
[lines of S1 excluding the cursor, with 1 appended to all lines above the cursor]
This arrangement effectively muxes between S0 and
  S1 based on the first input bit (from line ?<). If it is
  0, the cursor will ride the appended 0's up to the original cursor
  position of S0, which will then be bordered top and bottom by
  empty stacks, and thus run exactly identical to the original
  S0. Likewise, if 1 is input, the cursor will ride the
  1's down to S1's cursor position and proceed to execute
  it as if it were alone.
For example, Stackylogic programs for OR and NAND are
?
?<

and
1
?<
11
?
0

They can be combined to simulate
if B:
    result = x OR y
else:
    result = x NAND y

like so:
1
?
110
?0
00
0
?<
?1
?

Thus, any truth table can be simulated by a Stackylogic program.

Challenge
Write a program or function that takes in an N input truth table (N > 0) in the form of a list of 2N boolean values that represent the outputs of the table in ascending binary order.
Any reasonable input format is alright. e.g. for an OR truth table
x y | OR
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1

any of these styles of inputs would be fine:
0111
0, 1, 1, 1
0
1
1
1

[False, True, True, True]
Print or return a Stackylogic program that satisfies the truth table, i.e. has the exact same output given the same input. Any finite program that satisfies that table is valid output. You do not need to follow the inductive proof's method of construction. The Stackylogic programs do not need to be optimally short.
For example, if the input were 11100111, one valid output would be
1
?
110
?0
00
0
?<
?1
?

but there are many others.
The shortest code in bytes wins.
See the original Stackylogic challenge if you need an interpreter.

Can we take N as a second input?

@LeakyNun Yes (or 2^N), if necessary.

Pyth, 53 bytes
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hbjXF+yQ\<

Try online
This is an exact implementation of the system described in the challenge for how to implement arbitrary truth tables in Stackylogic. We simply cut the truth table in half, implement it recursively, and then append 0 and 1 as appropriate.
This defines a recursive function, whose return value is [1, ['0', '?', '1']], where the first number is the location of the pointer, and the rest is a stackylogic program.
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hbjXF+yQ\<
                                                         Q = eval(input())
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hb
L                                                 def y(b): return
 ?tb                                              if b[1:] (base case on false)
                                      ,0]`hb      else: [0, str([0])]
                                                  then:
           c2b                                    Cut the input in half
         yM                                       Map y over the halves
        J                                         Store that in J
    ,leh                                          The cursor position is the length
                                                  of the body of the first function
                 .e                 J             enum-map, where k is the index
                                                  and b is the value, over J
                   .e             eb              enum-map, Y is the index and
                                                  Z is the value, over body of b
                     +W         Zk                Add to Z (line) k (the overall
                                                  index, 0 or 1) conditional on
                          -Yhb                    Y (line index) - cursor
                       _Wk                        Negated if k
                      >       0                   > 0
               X0                    \?           Add '?' to the first element
              s                                   Concatenate, giving the body

jXF+yQ\<
    yQ      Call the above on the input
   +  \<    Append a '<'
 XF         Splat the 3 element list into the 'append-at' function,
            adding the curson in the right place
j           Join on newlines and print.

Well... I just went back home to correct my solution...

Python 3, 352 208 205 bytes
This is still very ungolfed, and I will try to add an explanation later. After some modifications, I managed to remove 144 147 bytes.
f=lambda x,l=len,r=range:'\n'.join(*x)if l(x)<2 else f([[x[i][j]+['0',''][j<=l(x[i])//2]for j in r(l(x[i]))]+[['?','?<'][l(x)<3]]+[x[i+1][j]+['1',''][j>=l(x[i])//2]for j in r(l(x[i]))]for i in r(0,l(x),2)])

A function f that takes input of the truth table values as a list of Booleans of the form ['1','1','1','0','0','1'...], where '1' is truthy and '0' is falsey, and returns a Stackylogic program.
Try it on Ideone
If you want to test a produced program, you can use GamrCorps's Convex interpreter here.
How it works
This is a recursive function and uses the inductive method described in the question.
At the zero-indexed recursion level a, the function creates n/2 a+1-input Stackylogic programs from the n a-input programs in the list. This is done by joining all adjacent pairs of two programs in the list with ?; since the cursor is always at the middle element of each constituent program, the required appending of 0 or 1 can be performed by iterating over each line of the programs being joined, and appending if the index of the current line is less than or equal to/greater than or equal to the middle index as appropriate. If the list contains only two programs, the next recursive call will give the final program; since this requires a cursor, joining instead occurs on ?<.
When the list has length 1, the list must contain just one element containing the full program. Hence, all lines in the program are joined on a newline, and then returned.
An example helps to illustrate this:
Take the input ['1', '1', '1', '0', '0', '1', '1', '1'].

Level  Return value

0  [['1', '?', '1'], ['1', '?', '0'], ['0', '?', '1'], ['1', '?', '1']]
1  [['1', '?', '10', '?', '11', '?', '0'], ['0', '?', '10', '?', '11', '?', '1']]
2  [['1', '?', '10', '?', '110', '?0', '00', '?<', '01', '?1', '101', '?', '11', '?', '1']]
3  '1\n?\n10\n?\n110\n?0\n00\n?<\n01\n?1\n101\n?\n11\n?\n1'

which when printed gives:

1
?
10
?
110
?0
00
?<
01
?1
101
?
11
?
1


text:
Substring Sum Set
Introduction
Let's observe this array: [3, 2, 4, 1, 1, 5, 1, 2].
Each element displays the length of the substring which must be summed up. Let's take a look at the first element of the above array:
[3, 2, 4, 1, 1, 5, 1, 2]
 ^

The element at the first index is 3, so we now take a substring of length three with the same index as the starting position:
[3, 2, 4]

When summed up, this results into 9, so the first element of the substring sum set is 9.
We do this for all the elements in the array:
3 -> [3, 2, 4]
2 -> [2, 4]
4 -> [4, 1, 1, 5]
1 -> [1]
1 -> [1]
5 -> [5, 1, 2]
1 -> [1]
2 -> [2]

You can see that the number 5 is a bit of a weird case. That number exceeds the length of the array:
[3, 2, 4, 1, 1, 5, 1, 2]
                ^  ^  ^  ^  ^

We'll ignore everything that exceeds the array, so we just use [5, 1, 2].
The last step is to sum everything up:
[3, 2, 4]     -> 9
[2, 4]        -> 6
[4, 1, 1, 5]  -> 11
[1]           -> 1
[1]           -> 1
[5, 1, 2]     -> 8
[1]           -> 1
[2]           -> 2

And that is the array that needs to be outputted:
[9, 6, 11, 1, 1, 8, 1, 2]

The Task
Given an non-empty array with positive (non-zero) integers, output the substring sum set. This is code-golf, so the submission with the smallest number of bytes wins!
Test cases
[1, 2, 3, 4, 5] -> [1, 5, 12, 9, 5]
[3, 3, 3, 3, 3, 3, 3, 3] -> [9, 9, 9, 9, 9, 9, 6, 3]
[5, 1, 2, 4, 1] -> [13, 1, 6, 5, 1]
[1] -> [1]

I think you mean "sub-list", not "substring". There's no strings.

@mbomb007 I think substring has the same meaning here as in the longest common substring problem, i.e., a subsequence whose elements are adjacent. Data types aside, a string is just a finite sequence of elements of an alphabet set (in this case, the positive integers).

Jelly, 6 bytes
ṫJḣ"ḅ1

Try it online! or verify all test cases.
How it works
ṫJḣ"ḅ1  Main link. Argument: A (array)

 J      Index; yield the 1-based indices of A.
ṫ       Tail; map k to the postfix of A that begins with the k-th element.
  ḣ"    Vectorized head; for each k in A, truncate the corr. postfix to length k.
    ḅ1  Convert the resulting slices from base 1 to integer.

Python, 40 bytes
f=lambda x:x and[sum(x[:x[0]])]+f(x[1:])

Test it on Ideone.

I figured there would be a golfier recursive solution, but you beat me to it.

Excel, 21 bytes
=SUM(OFFSET(A1,,,A1))
Open a new spreadsheet, put the test values in column A. Enter the formula in B1 and double click the cell handle to ride the range.

I'd give you a second upvote for teaching me about that double-click trick if I could.

While it works it's a bit of cheating as execution requires manual input.

@user3819867 not significantly more than most program execution, I'd argue. Perhaps it would be even more comparable if you save a spreadsheet only containing the formula in B1  - then open, add the data to column A, and double-click the handle on B1 to execute. YMMV of course.

Python 3, 47 bytes
lambda X:[sum(X[i:i+k])for i,k in enumerate(X)]

Pretty straightforward implementation. Python's default behavior for slices that go past the end of the list was very convenient here.

Haskell, 34, 33 bytes
f l@(x:y)=sum(take x l):f y
f x=x

One byte saved by nimi.

JavaScript ES6, 50 bytes
a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

Pretty self-explanatory. It maps over each element in the array, getting the slice from that index through the index plus that element's value, and reduceing by adding.

f=
  a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

;[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(function(test){
  document.getElementById('p').textContent += test + ' => ' + f(test) + '\n';
});

J, 11 bytes
+/@{."_1]\.

Usage
   f =: +/@{."_1]\.
   f 3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2
   f 1 2 3 4 5
1 5 12 9 5

Explanation
+/@{."_1]\.  Input: A
        ]\.  Get each suffix of A from longest to shortest
   {."_1     For each value in A, take that many values from its corresponding suffix
+/@          Sum that group of values taken from that suffix
             Return the sums

JavaScript (ES6), 45
reduce beaten again!
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))

F=
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))

;[[3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]].forEach(t=>console.log(t+' -> '+F(t)))

As far as I know, you can remove the f=, just as in this answer.

@LarsW right, the f= is already not counted in the 45 bytes

Mathematica 60 55 bytes
Tr@Take[#,UpTo@#&@@#]&/@Drop[#,t-1]~Table~{t,Length@#}&

eg
f = %; f /@ {{1, 2, 3, 4, 5}, {3, 3, 3, 3, 3, 3, 3, 3}, {5, 1, 2, 4, 1}, {1}}

(*    {{1, 5, 12, 9, 5}, {9, 9, 9, 9, 9, 9, 6, 3}, {13, 1, 6, 5, 1}, {1}}    *)

Thanks @MartinEnder for shaving off 5 bytes :)

Here is an idea to avoid the table: #+Tr@Take[x=Rest@x,UpTo[#-1]]&/@(x=#)& Still not sure it's optimal but it saves 17 bytes.

Retina, 38 bytes
Byte count assumes ISO 8859-1 encoding.
\d+
$*
M!&`\b1(1)*(?<-1>,1+)*
M%`1
¶
,

Input and output are comma-separated lists.
Try it online! (The first line enables a linefeed-separated test suite.)

05AB1E, 11 8 bytes
[D¬£Oˆ¦Ž

Explanation
[         # infinite loop
 D        # duplicate current list
  ¬       # get head of list
   £      # get that many elements from list
    O     # sum
     ˆ    # add to global array
      ¦   # remove first element of list
       Ž  # break if stack is empty
          # implicitly push and print global array

Try it online

Pyth, 8 bytes
.es:Qk+b

Test suite.
Translation of El's answer in Python.

Erlang, 69 bytes
f(A)->put(1,1),L=lists,[L:sum(L:sublist(A,put(1,get(1)+1),X))||X<-A].

Erlang's higher-order functions for lists do not receive the index of the current element. This uses the process dictionary to set the index of the current element.

Pyke, 12 7 bytes
FKo>i<s

Try it here!
        - o = 0
F       - for i in input:
  o     -    o+=1
   >    -    input[o:]
    i<  -   ^[:i]
      s -  sum(^)

VBA, 160 bytes
Function e(g())
Dim h()
k=LBound(g)
l=UBound(g)
ReDim h(k To l)
On Error Resume Next
For i=k To l
For j=i To i+g(i)-1
h(i)=h(i)+g(j)
Next
Next
e=h
End Function

Matricks, 25 bytes
Yay, finally a challenge I don't need new features for!
md{z:l-g:c;+c;q:c;};:1:l;

Run with: python matricks.py substring.txt [[<input>]] 0
Explanation:
m                  :1:l;   #loop over entire input
                           #set each value to...
 d{               }        #the sum of...
   z:l-g:c:+c;q:c;         #the input cropped to
                           #the length of the value in the cell

Pyth, 6 bytes
ms<~tQ

Test suite
This is a different solution from any others so far. It loops over the input, slicing an summing the initial values, then removing the first element of the stored input, and repeat.
Explanation:
ms<~tQ
ms<~tQdQ    Implicit variable introduction
            Implicit: Q = eval(input())
m      Q    Map d over the input, Q
  <  Qd     Take the first d elements of Q
 s          Sum them
   ~tQ      Afterwards, set Q to the tail of Q, removing the first element.

MATL, 17 14 13 bytes
fGy+!-R0<G*!s

Explanation
Try it online! Or verify all test cases (code modified to handle several inputs).
f     % Take input implicitly. Indices of nonzero elements: this gives [1 2 ... n]
      % where n is input size
G     % Push input again
y     % Push a copy of [1 2 ... n]
+     % Add. Gives [a+1 b+2...] where [a b...] is the input
!     % Transpose into a column vector
-     % Subtraction with broadcast. Gives 2D array
R     % Keep upper triangular part, making the rest of entries 0
0<    % True for negative entries. Each row corresponds to a substring sum.
      % For each row, this gives true for the entries of the input that make up
      % that substring sum. Each row is thus a mask to select entries of the input
G     % Push input again
*     % Multiply with broadcast. This multiplies the input times each row
!s    % Sum of each row. Implicitly display

Javascript (using External Library) (66 bytes)
n=>_.From(n).Select((v,i)=>_.From(n).Slice(i,i+v).Sum()).ToArray()

Link to lib: https://github.com/mvegh1/Enumerable
Code explanation: _.From is loading the input array into the library, which is basically LINQ for js. Then each item in the array is mapped according to the following predicate: Take the input, and slice it from current item index and take that index plus the current item's value. Then Sum up that subsequence. Convert the result to a native JS array and return it

Remove the var  from the variables, you don't need that in golf. You can also change .forEach to .map which costs less bytes.

Oh yeah, you're right about var. Thanks! I'll go through this answer again tomorrow. It looks like native JS (es6) kills my solution lol

Good call on removing var. I also realized another solution which reduces the byte count a lot and is also more intuitive

F#, 84 82 bytes
let f(A:int[])=[for i in 0..A.Length-1->Seq.skip i A|>Seq.truncate A.[i]|>Seq.sum]

Julia, 39 bytes
!x=x!=[]?[take(x,x[])|>sum;!x[2:end]]:x

Try it online!

JavaScript (ES6) - 79 Bytes
A recursive solution that does not use any of the Array methods:
f=([a,...t],n)=>a&&n?a+f(t,n-1):0;g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r

Testing:

f=([a,...t],n)=>a&&n?a+f(t,n-1):0;
g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r;

[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(a=>console.log(''+g(a)));

C#, 89 bytes
int[]s(List<int>a)=>a.Select((n,i)=>a.GetRange(i,Math.Min(n,a.Count-i)).Sum()).ToArray();

pretty straight forward
improvement ideas appreciated

Brachylog, 27 bytes
.v|h~l(A:Tc?;A?)b:0&~b.h~+A

Try it online! or verify all test cases.
Explanation
  .v           Input = Output = []
|            Or
  h~l          A is a list, its length is the value of the first element of the Input
  (
    A:Tc?        The concatenation of A with another list T results in the Input
  ;            Or
    A?           A = Input
  )
  b:0&         Call recursively on Input minus the first element
  ~b.          Output is the output of that call with an extra element at the beginning
  h~+A         That extra element is the sum of the elements of A

Dyalog APL, 15 bytes
{+/¨⍵↑∘⌽¨⌽,\⌽⍵}

or
{⌽+/¨(-↑¨,\)⌽⍵}

PHP program, 72 Bytes
<?foreach($a=$_GET[a]as$i=>$v)echo array_sum(array_slice($a,$i,$v)),"
";

call with php-cgi -f <filename> 'a[]=3&a[]=2&a[]=4...
+11 as a function:
function f($a){foreach($a as$i=>$v)$r[]=array_sum(array_slice($a,$i,$v));return$r;}

+9 without builtins:
function p($a){foreach($c=$r=$a as$i=>$v)for($k=$i;$k--;)if(--$a[$k]>0)$r[$k]+=$v;return$r;}

($c keeps the original values, $a counts down for each index, $r gets the sums)
-3 as program:
<?foreach($a=$r=$c=$_GET[a]as$i=>$v)for($k=$i;$k--;)if(--$c[$k]>0)$r[$k]+=$v;print_r($r);

q (37 bytes)
{sum each(til[count x],'x)sublist\:x}

Example:
q){sum each(til[count x],'x)sublist\:x}3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2

Clojure, 63 bytes
(defn f[[b & r]](concat[(apply + b(take(dec b)r))](if r(f r))))

Uses pattern matching to decompose input argument in to the first and the rest of the arguments.

C#, 94 bytes
Console.Write(String.Join(",",a.Select((v,i)=>a.Skip(i).Take(v).Sum().ToString()).ToArray()));

Where a is an int[] that represents the input to be solved.

you arent allowed to assume a variable is predefined

The variable a is the input to be solved.

source: Stack Exchange

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

sort: votes


text:
Bring ASCII art to the 3rd dimension
In this challenge, You have to bring ASCII art (which are usually 2D) to 3D!
How?
like this,
X X DD
 X  D D
X X DD

to...
  X X DD
 X X DD D
X X DDDD
 X XDDD
X X DD

Then How do we do that?
Given the ascii art and N, repeat this N times.

for every character (we will call this A):
let B be the character which is exactly 1 right and 1 up from A
if B is a space or is undefined:
set B to A.

Specs

The first input can be a string with newline characters or a list of strings representing the 2D ASCII art.
You are allowed to use %END% to tag the end of input, but this is not required.
The second input will be N. It will be a positive integer.
all the lines of the strings will be the same length.

Examples
Input: ("###\n###",1)
Output:
 ###
####
###

Rules
Basic code-golf rules apply.
also, If you have questions, be sure to ask in the comments!

You might want to clarify that "blank" refers to space (U+0020) or nothing.

@LeakyNun Is it fixed now?

Is extra whitespaces allowed?

Yes, Those are allowed.

I think there should be a whole in the top right corner of your D. the bottom left D can't reach all the way up there.

@MartinEnder My program confirms that.

Can I assume that the length of each line will be the same? (Can I pre-pad the input with spaces on the right?)

@MartinEnder mine confirms your finding as well.

I've taken the liberty to edit your question. Feel free to revert any edit.

Can I take the second input one higher?

Can the input be a 2D array in the sense of a char matrix? Rows right-padded with spaces so they all have the same length

Some of the answers here print ANSI escape sequences to move a terminal cursor around. This is allowed by consensus, but it might not be the kind of approach you intended, so I feel like it’s worth chiming in on.

@Lynn Well, that is one of the approach that I thought of.

Will the thing only have printable characters (and newlines)?

Yes, otherwise, we can't input it, I guess?

Again, can the input be a 2D array of chars (matrix of chars)? Please clarify :-)

Perl, 81 bytes
75 bytes code + 6 for -i -n0.
Note that the \e characters are ASCII \x1b but \e is used for ease of testing.
Please note that this solution uses ANSI escape sequences and requires a compatible terminal, as well as using the -i commandline argument to pass in the number of 'dimensions' you'd like.
$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I

Usage:
In a Linux compatible terminal, run PS1= first to ensure your prompt doesn't overwrite the displayed image.
perl -i10 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< '
ROFL:ROFL:ROFL:ROFL
         _^___
 L    __/   [] \
LOL===__        \
 L      \________]
         I   I
        --------/
'

          ROFL:ROFL:ROFL:ROFL
         ROFL:ROFL:ROFL:ROFL
        ROFL:ROFL:ROFL:ROFL
       ROFL:ROFL:ROFL:ROFL\
      ROFL:ROFL:ROFL:ROFL\_]
     ROFL:ROFL:ROFL:ROFL\_]
    ROFL:ROFL:ROFL:ROFL\_]/
   ROFL:ROFL:ROFL:ROFL\_]/
  ROFL:ROFL:ROFL:ROFL\_]/
 ROFL:ROFL:ROFL:ROFL\_]/
   LOL==___^___]_\_\_]/
  LOL==__/ \_[]_\_\_]/
 LOL===__ \______\_]/
  L      \________]/
          I---I---/
         --------/

perl -i3 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< 'X X DD
 X  D D
X X DD
'
   X X DD
  X X DD D
 X X DDDD
  X XDDD
 X X DD

CJam, 25 24 bytes
{{' 1$f+La@+..{sS@er}}*}

An unnamed block that expects a list of strings and the number of repetitions on the stack and leaves a new list of strings instead.
Test it here. (Includes a test wrapper that reads the string from STDIN for convenience.)
Explanation
{       e# Repeat this block N times...
  '     e#   Push a space character.
  1$    e#   Copy the current grid.
  f+    e#   Prepend the space to each line of the grid.
  La    e#   Push [[]].
  @+    e#   Pull up the other copy of the grid and prepend the [].
        e#   We've now got two copies of the grid, one shifted right by
        e#   a cell and one shifted down by a cell. We now want to replace
        e#   spaces in the latter with the corresponding character in the
        e#   former.
  ..{   e#   For each pair of characters in corresponding positions...
    s   e#     Turn the character in the down-shifted grid into a string.
    S   e#     Push " ".
    @   e#     Pull up the character from the right-shifted grid.
    er  e#     Replace spaces with that character.
  }
}*

Ten roflcopters! http://goo.gl/PEK4iB

Why doesn't S work for the initial space? Also, is it allowed to use variables (which might have been overwritten) in a function?

@LuisMendo S doesn't work, because then f would be mapping over that string instead. Re functions, I believe so, in "normal" languages, there are also many functions submissions that rely globals which aren't tampered with between invocations.

Thanks. I forgot that a character in CJam is not the same as a one-character string

You can save one byte by using Convex as it has a one-char transliterate operator instead of a two-char: http://convex.tryitonline.net/#code=cU4vIDIKCnt7JyAxJGYrTGFAKy4ue3NTQMOLfX0qfQoKfk4q&input=WCBYIERECiBYICBEIEQKWCBYIERE (shameless plug)

@GamrCorps Thanks, I've posted it as a separate answer.

APL, 49 bytes
{⎕UCS 32⌈{s+(s=0)×1⊖¯1⌽s←0⍪⍵,0}⍣⍺⊣(32∘≠×⊣)⎕UCS↑⍵}

Input: vector of character vectors.
Example:
      2 {⎕UCS 32⌈{s+(s=0)×1⊖¯1⌽s←0⍪⍵,0}⍣⍺⊣(32∘≠×⊣)⎕UCS↑⍵} 'X X DD' ' X  D D' 'X X DD'
  X X DD
 X X DD D
X X DDDD
 X XDDD
X X DD

How it works:

↑⍵ turns the argument into a matrix of chars
⎕UCS from char to integer
(32∘≠×⊣) substitute the spaces (32) with zeroes
...⍣⍺⊣ apply ⍺ (the left argument) times the function on the left
s←0⍪⍵,0 border with zeroes on top and on the right the argument
1⊖¯1⌽ rotate 1 up and 1 right
s+(s=0)× sum to the original the shifted version but only on top of the zeroes of the original
32⌈ turns back the zeroes into 32s
⎕UCS from integer to char

MATL, 24 bytes
:"ct32>*TTYatFTEqYSy~*+c

Input format is
2
{'X X DD', ' X  D D', 'X X DD'}

So the other example is
1
{'###', '###'}

The output contains extra whitespace, which is allowed by the challenge.
Try it online!

If a 2D char array is acceptable as input (I've asked the OP twice...), the first c can be removed, so 23 bytes:
:"t32>*TTYatFTEqYSy~*+c

Input format in this case is (all strings have equal lengths, which may require right-padding with spaces):
2
['X X DD '; ' X  D D'; 'X X DD ']

Try it online!

Explanation
:        % Input number n implicitly. Generate [1 2 ... n]
"        % For loop: repeat n times
  c      %   Convert to char array. In the first iteration it inputs a cell array of
         %   strings implicitly and converts to a 2D char array, right-padding with
         %   spaces. In the next iterations it does nothing, as the top of the stack
         %   is already a 2D char array
  t32>*  %   Convert characters below 32 into 0
  TT     %   Push array [1 1]
  Ya     %   Pad the 2D char array with one zero in the two directions (up/down,
         %   left/right), on both sides
  t      %   Duplicate
  FTEq   %   Push array [-1 1]
  YS     %   Circularly shift the 2D char array one unit up and one unit right
  y      %   Push a copy of the non-shifted 2D array
  ~      %   Logical negate: nonzero entries become 0, zero entries become 1. This
         %   will be used as a mask for entries that need to be changed. Since the
         %   values at those entries are zero, we can simply add the new values. We do
         %   that by multiplying the mask by the shifted array and adding to the
         %   non-shifted array
  *      %   Multiply element-wise
  +      %   Add element-wise
  c      %   Convert the 2D array back to char
         % End for
         % Implicitly display

Convex, 23 bytes
Byte count assumes CP-1252 encoding.
{{' 1$f+La@+..{sS@Ë}}*}

An unnamed block that expects a list of strings and the number of repetitions on the stack and leaves a new list of strings instead.
Try it online!
This is a direct port of my CJam answer to Convex (which is heavily based on CJam). The only difference is that Convex uses Ë instead of er for transliteration, saving one byte. Thanks to GamrCorps for letting me know about it.

Pyth, 54 33 bytes
ju+++dhG.bsmh|-d;;.t,Y+dNdtGGeG.*

Test suite.

why do you need two ;?

@ven ; is not the usual ; in programming languages.

; is a variable.

ah pyth overloads ; in lambdas...

@ven When you get along with Pyth, you would use I, .?, V, F, ;, (explicit statements) very less, and they will be replaced by ?, m, u, F, M, L, R, #, ...

Ruby, 95 bytes
->a,n{n.downto(0){|i|f="<Esc>[1C"
$><<a.gsub(/^/,f*i).gsub(" ",f)+(i>0?"<Esc>[#{a.lines.size-1}A":"")}}

Each <Esc> is a literal ESC character (0x1b).
Usage
Assign the lambda to a variable e.g. func.
art = <<END
X X DD
 X  D D
X X DD
END

func[art, 2]
# Prints:
#   X X DD
#  X X DD D
# X X DDDD
#  X XDDD
# X X DD

Ungolfed
->(art, num) {
  num.downto(0) do |i|
    forward = "\e[1C"
    $> << art.gsub(/^/, forward * i).gsub(" ", forward) +
            (i > 0 ? "\e[#{art.lines.size - 1}A" : "")
  end
}

The forward escape sequence, \e[1C, moves the cursor forward (right) 1 space and \e[<n>A moves it up n lines. Basically what this code does is print the "layers" back to front, replacing spaces with the forward sequence to avoid overwriting the other layers with a space.

You accidentally put a f= before the -> in the golfed version. Remove it for -2 bytes.

Python 2, 116 bytes
S=' '
def f(a,d):e=[S*len(`a`)];exec"a=[''.join(t[t[1]>S]for t in zip(S+x,y+S))for x,y in zip(a+e,e+a)];"*d;return a

I’ll golf this more soon.

Are you sure a lambda isn't shorter?

I need the assignment of e in there. Also, exec is a statement, so it can’t be in a lambda.

Ok. Just making sure.

JavaScript (ES6), 128 bytes
f=(a,n)=>n?f((a=[``,...a].map(s=>[...s||` `])).map((b,i)=>i--&&b.map((c,j)=>a[i][++j]>' '?0:a[i][j]=c))&&a.map(b=>b.join``),n-1):a

Accepts and returns an array of strings, prepends an extra row for the output, ensures each row contains at least a space, splits them all up into characters, loops though trying to copy the characters to the row above and column to the right, then recursively calls itself to complete the loop.

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


text:
Help the poor Cryptographers - DLP Edition
Introduction and Motivation
I'm mainly active on Cryptography.SE and as such have already stumbled across the question: "How the hell am I supposed tools like cado-nfs to do stuff!?". They are super-complicated tools for a super-complicated task: Factoring large integers and computing large-scale discrete logarithms.
Now I'm standing here (in a metaphoric sense) and I am asking you:
Please give us poor cryptographers a usable tool. :(
This question in particular is about the discrete logarithm problem which was broken by Logjam, is frequently used in the world of online security and you're supposed to solve it (as far as current technology goes)!
Specification
Input
Your input will be three (potentially) large numbers: A generator, a prime and an argument. The integer encoding should be hex or decimal big-endian. Additionally you may require arbitrary generator and prime dependent state (a bunch of pre-calculations and stuff). The generators, primes and arguments for the score evaluation will not be public. But there will be several arguments for one set of generators and primes so caching does make sense here.
Output
The output is supposed to be one (potentially large) integer, the discrete logarithm of the argument to the base of the generator in the field defined by the prime. Additionally you may output intermediate state that will speed-up future calculations.
What to do?
Using any library, tool and language you like (no online-services), hit the lowest time of execution for calculating the (correct) discrete logarithm. The parameters will be:

There will be three pairs of random (safe) prime and an appropriate (small) generator
Each pair will receive three distinct (random) arguments, for the latter two, intermediate state will speed things up significantly
The tests will be run on an AWS EC2 c4.large instance
The tests will use 332-bit (100 decimal digit) primes and arguments

Who wins?
This is fastest-code so the fastest code wins!
Submissions are evaluated earliest three days after lack of activity (these evaluations cost money!) and clearly inefficient submissions will not be evaluated at all.
OS: The submittant has the choice between the default Amazon-provided OSes which are Windows Server (2003 R2 - 2012 R2 Base), Red Hat Enterprise Linux 7.2, SUSE Linux Enterprise Server 12 SP1, Ubuntu Server 14.04 LTS, Debian 8 Jessie (community AMI), CentOS (6 or 7; community AMI) additionally the submittant can link to or provide instructions on using / creating a custom Amazon Machine Image (AMI) for testing
Installation instructions or links to those need to be provisioned.
(Potentially) Helpful resources:

Cado-NFS
The GNFS, the mainly used algorithm for this

This might be an overkill question.

I'm not sure if I'm understanding this correctly; the question is supposed to be about writing a script to install and invoke some factoring tools?

@feersum, it's not about factoring (but rather a different, similarly used mathematical concept called discrete logarithm) and it doesn't require an installation script. Just some program that computes a discrete logarithm (quickly). Using the pre-built and engineered tools for this task would certainly help reduce code sizes and run-times.

@ardaozkal, I was fearing the same. But in the end the resulting program should be "rather short", even though the required mathematical / technical skill may actually be overkill :/

Cado-nfs is the right tool to use.
It provides abstract enough way of handling any case, but relies on input specific optimizations that cannot be done by the program anyway.
There is no general (applicable to anything with same efficiency) solution (even theoretical one) for NFS that can be implemented in program at the moment.
Judging by the work done in CADO-nfs, simply coming up with a good enough algorithm for just 100 digit number would take several months of research before any programming can be done.
You should ask around on CADO-nfs forums, there were at least couple of tests mentioning 103-104-digit algorithms, that might be more useful.
If nfs is not a strict requirement, you could mention it in question.
Sadly, I cannot comment yet; and no, I am far from specialist in any of the areas.

In fact, cado-nfs already has kind of a one-shot tool for calculating discrete logarithms. It's just that it requires MAGMA to be installed (boo) and that some pre- and post- processing on the in- and outputs is needed... And the parameters are deliberately chosen such that the (G)NFS is the only viable tool for the job.

Well, do you strictly require NFS solution? If so, you would need to map out mathematical algorithm for the procedure as a part of the question so that other may translate it into some programming language. I doubt you can expect anyone to go through whole theory, explanations and this particular implementation (CADO) before a single line of code can be written.
Or you are looking for the fastest simple (intuitive) solution?


text:
Low pass filter
The goal of this challenge is to implement a digital low-pass filter.
You are free to implement any type of digital filter you want, however whatever results produced must pass the validation script below.
Here's a general description of what the validation script expects:

When an FFT is taken of the filtered signal, the filtered signal amplitude at any frequency bucket:

If the input signal has a frequency bucket with a value below -80dB, then the output signal bucket needs only be at or below the -80dB level.
A decade below the cutoff frequency must not differ from the source signal amplitude by more than 3dB at the corresponding frequency bucket.
At or above the cutoff frequency must be at least 3dB below the source signal amplitude at the corresponding frequency bucket of the input signal.

The output signal must be in the time domain and have the same number of samples and sample rate as the input signal.
You need not preserve any phase information or worry about aliasing.
The output signal must consist of only finite real values (no NaN/ infinities).

Input
Your program is given the following inputs:

A time domain sampled signal consisting of real numbers representing the amplitude of the signal at the sample time. Your program will be given the entire sample data at the beginning, but this is not necessarily the same between different runs of your program. You may assume the number of samples is sufficiently small that you don't have to worry about running out of memory. You may assume any single input sample is between [-1, 1]
A positive real number representing the sample rate (in Hz)
A positive real number representing the cutoff frequency (in Hz)

You are free to dictate the exact form of the input as long as no additional information is given (ex.: passing a data pointer+length for the time domain signal is ok, but passing in FFT information is not). The input can come from any source desired (file io, stdio, function parameter, etc.)
Output
Your program should output the time domain filtered signal. The output may be written to any source desired (file io, stdio, function return value, etc.). You should not need the filtered signal sample rate since it should be the same as the input sample rate.
Validation Python function
This should work with Python 2 or 3 (requires NumPy)
from __future__ import division, print_function
import numpy as np

def validate(original, filtered, srate, cfreq):
    '''
    Validates that the filtered signal meets the minimum requirements of a low-pass filter.
    A message of the failure mode is printed to stdout

    @param original the original signal (numpy array)
    @param filtered the filtered signal (numpy array)
    @param srate the sample rate (float)
    @param cfreq the cutoff frequency (float)
    @return True if filtered signal is sufficent, else False
    '''
    # check length
    if(len(original) != len(filtered)):
        print('filtered signal wrong length')
        print('len(original): %d, len(filtered): %d'%(len(original),len(filtered)))
        return False
    # assert filtered signal is not complex
    if(np.any(np.iscomplex(filtered))):
        print('filtered contains complex values')
        return False
    # assert filtered signal is all finite floats
    if(not np.all(np.isfinite(filtered))):
        print('filtered signal contains non-finite floating point values')
        return False
    o_fft = abs(np.fft.rfft(original))
    f_fft = abs(np.fft.rfft(filtered))
    f_fft /= np.amax(o_fft)
    o_fft /= np.amax(o_fft)
    fft_freqs = np.fft.rfftfreq(len(original), 1/srate)

    orig_small_mask = (o_fft < 1e-4)
    big_mask = ~orig_small_mask
    # check small values
    if(np.any(f_fft[orig_small_mask] > 1e-4)):
        print('input signal had a bucket below -80 dB which the filtered signal did not')
        return False

    ob_fft = o_fft[big_mask]
    fb_fft = f_fft[big_mask]
    fftb_freqs = fft_freqs[big_mask]
    low_mask = (fftb_freqs < 0.1*cfreq)
    high_mask = (fftb_freqs >= cfreq)
    lows = abs(fb_fft[low_mask]/ob_fft[low_mask])
    highs = abs(fb_fft[high_mask]/ob_fft[high_mask])
    # check pass bands
    if(np.any(lows > np.sqrt(2)) or np.any(lows < 1/np.sqrt(2))):
        print('pass region is outside of +/- 3dB')
        return False
    # check filter bands
    if(np.any(highs > 1/np.sqrt(2))):
        print('filter region is not at least -3dB below original')
        return False
    # passed all tests!
    return True

Examples
Here are some Python functions which can be used to generate example datasets. Note that these scripts require NumPy. The output of each function is a tuple containing (samples, sample_rate, cutoff_freq). Note that it is very easy to get a different test case by choosing a different cutoff frequency; the example ones are just somewhat "interesting" cases.
from __future__ import division, print_function
import numpy as np
def case1():
    # simple sine wave, cutoff including primary frequency
    t = np.linspace(0, 1, 10000)
    srate = 1/(t[1]-t[0])
    return np.sin(2*pi*t),srate,1

def case2():
    # simple sine wave, cutoff above primary frequency
    t = np.linspace(0, 1, 10000)
    srate = 1/(t[1]-t[0])
    return np.sin(2*pi*t),srate,10

def case3():
    # random noise
    t = np.linspace(0, 1, 10001)
    srate = 1/(t[1]-t[0])
    return np.random.rand(t.size)*2-1,srate,10

def case4():
    # sinc function
    t = np.linspace(-1, 1, 10000)
    srate = 1/(t[1]-t[0])
    return np.sinc(2*np.pi*srate*t), srate, 10

def case5():
    n = 200000
    t = np.linspace(0, 1, n)
    y = np.zeros(t.size)
    for i in range(3):
        amp = np.random.rand(1)
        freq = i*103+101
        phase = np.random.rand(1)*2*np.pi
        tdecay = 1e-3
        decay = 1e-1
        for j in range(1,10):
            fj = freq*j
            if(fj >= 0.9*n):
                break
            y += amp*(np.sin(2*np.pi*fj*t+phase))*np.exp(-decay*(j-1)**2)*np.exp(-tdecay*t)
    y -= np.mean(y)
    y /= max(np.amax(abs(y)),1)
    srate = 1/(t[1]-t[0])
    return y,srate, 1e3

Scoring
This is code golf, shortest answer in bytes wins. Standard loop-holes apply. You may use any built-ins desired.

I just want to note that the question has a lot of unclear language (to me at least) when it comes to what the challenge is about. What is an "FFT"? What's a low-pass filter? What's a frequency bucket? Maybe the question is out of my league, but I don't really see descriptions of those things, and the question should be self-contained. Consider why it has gone 1.5 yrs without an answer until now.

Python: 99 bytes
from numpy.fft import *
def f(o,s,c):
 a = rfft(o);b=rfftfreq(o.size,1/s);a[b>=c]=0;return irfft(a)

This is a very simple rectangle/brick filter. It takes the real fft of the signal, sets all components equal to or higher than the cutoff frequency to 0, then returns the inverse real fft.

SmileBASIC, 54 bytes
DEF L D,S,C
DIM A[99]BQPARAM A,1,S,C,1BIQUAD D,D,A
END

Call as:
L sample array , sample rate , cutoff frequency
(untested)


text:
Gear Train, Rotating
Gears transfer different amount of speeds, depending on the size of the meshed gear.

Jack has a machine, that rotates a Gear Train. but you don't know the speed of the last gear.
Luckily, You are a great code golfer, so you can help him!
So, What should I do?
Each gear is represented by 2 numbers, the radius of the inner gear and the radius of the outer gears.
If gear A is [a,b] and gear B is [c,d], then the ratio between the speed of A and the speed of B would be c:b.
Given a list of gears (list of 2-tuples), output the speed of the last gear.
You can assume the speed of the first gear is 1.
Worked out example
Let's say our input is [[6,12],[3,10],[5,8]].
The first gear, [6,12], would have a speed of 1.
Then, the second gear, [3,10], would have a speed of 1*12/3 = 4.
Then, the last gear, [5,8], would have a speed of 4*10/5 = 8.
Testcases
input                    output
[[1,1],[2,2]]            0.5     (1/2)
[[1,2],[1,2],[1,2]]      4       (2/1*2/1)
[[6,12],[3,10],[5,8]]    8       (12/3*10/5)

Rules
Basic code-golf rules apply.

Since you're allowing floating point output, you should probably clarify how accurate results have to be.

Can we take input as a flattened list instead of list of tuples?

Yes, like [6,12,3,10,5,8]. just mention it if you wanna use it.

That's a tad unfair. I had a different 7-byte version that I didn't post because I considered it less interesting. It would have been 6 bytes without flattening. Please consider using the sandbox next time to avoid this kind of situation.

Haskell, 19 bytes
foldr1(/).tail.init

Given a flat list like [a,b,c,d,e,f], tail.init removes the first and last elements, and then foldr1(/) creates a cascade of divisions b/(c/(d/e)))) that works out to alternating * and /: b/c*d/e.

but the question states that the programs gets list of 2-tuples, not a flat list

A flat list was allowed in the comments.

Jelly, 6 bytes
ḊṖU÷@/

Test suite.
ḊṖU÷@/   Main monadic chain. temp <- third argument (first input)
Ḋ        temp <- temp with first element removed
 Ṗ       temp <- temp with last element removed
  U      temp <- temp reversed
   ÷@/   temp <- temp reduced by reversed floating-point division.
         implicitly output temp.

Ah, alternating division. That's clever.

C, 115 123 121 83 80 76 71 70 bytes
4 bytes saved thanks to @LeakyNun!
My first golf, probably not the best.
c;float r=1;float g(a,s)int*a;{for(;c<s-2;)r*=a[++c]/a[++c];return r;}

Takes an array and size.
Ungolfed:
int counter;
float ret=1;
float gear(int *arr, int size) {
    for(; counter < size-2; )
        ret = ret * arr[++counter] / arr[++counter];
    return ret;
}

Welcome to PPCG! :)

What is the maximum number of numbers you can support? Welcome to PPCG!

j;float r=1;float f(int a[]){for(;j<sizeof a;)r=r*a[j++]/a[j++];return r;} (not tested)

Not j++, ++j and sizeof-2. 4 bytes saved. Thanks!

It seems we can't measure the size of passed arrays. I edited the answer.

Jelly, 7 bytes
U÷Ḣµ2\P

Try it online! or verify all test cases.

JavaScript (ES6), 44 bytes
a=>(t=1,a.reduce((x,y)=>(t*=x[1]/y[0],y)),t)

37 bytes for a flattened array:
a=>1/a.slice(1,-1).reduce((x,y)=>y/x)

Unlike (e.g.) Haskell, reduceRight is such a long name that it's cheaper to reduce the wrong way and take the reciprocal at the end.

inspired answer there... I couldn't have gone lower than that...

Pyth, 8 bytes
.UcZb_Pt

Test suite.

J, 8 bytes
%/@}:@}.

Try it online!
Usage
>> f =: %/@}:@}.

>> f 1 1 2 2
<< 0.5

>> f 1 2 1 2 1 2
<< 4

>> f 6 12 3 10 5 8
<< 8

where >> is STDIN and << is STDOUT.
Explanation
"Reduce" in J defaults from right to left, which took off a few bytes :p
divide       =: %
reduce       =: /
atop         =: @
remove_first =: }.
remove_last  =: }:

f =: (divide reduce) atop (remove_last) atop (remove_first)

Mathematica, 26 bytes
#2/#&~Fold~#[[-2;;2;;-1]]&

An unnamed function that takes a flat even-length list of values and returns the exact result (as a fraction if necessary).
This uses the same approach as some other answers of folding division over the reversed list (after removing the first and last element).

MATL, 9 bytes
6L)9L&)/p

Input format is any of these:
[[6,12],[3,10],[5,8]]
[6,12,3,10,5,8]
[6 12 3 10 5 8]

EDIT (July 30, 2016): the linked code replaces 9L by 1L to adapt to recent changes in the language.
Try it online!
Explanation
6L    % Predefined literal: index from second to second-last element
)     % Apply index to implicit input. Removes first and last elements
9L    % Predefined literal: index for elements at odd positions
&)    % Two-output indexing. Gives an array with the odd-position elements
      % and the complementary array, with the even-position elements of the
      % original array
/     % Divide those two arrays element-wise
p     % Product of all entries. Implicitly display

JavaScript, 54 bytes
(a,s=1)=>a.map((v,i)=>s*=(x=a[i+1])?v[1]/x[0]:1).pop()

Usage

f=(a,s=1)=>a.map((v,i)=>s*=(x=a[i+1])?v[1]/x[0]:1).pop()

document.write([
  f([[1,1],[2,2]]),
  f([[1,2],[1,2],[1,2]]),
  f([[6,12],[3,10],[5,8]])
].join('<br>'))

Ungolfed
function ( array ) {
  var s = 1;                                  // Set initial speed

  for ( var i = 0; i < array.length ; i++ ) { // Loop through array
    if ( array[i + 1] === undefined ) {       // If last element
      return s;                               // Return speed
    } else {                                  // Else
      s = s * ( array[i][0] / array[i+1][0])  // Calculate speed
    }
  }
}

Of course, the golfed variant is a bit different. With .map(), it replaces the first value of the array with the speed after the second wheel, the second value with the speed of the third wheel, and the last value and the second last value with the speed of the last wheel. So, we just take the last element with .pop().

PHP, 80 79 69 bytes
<?for($r=1;++$i<count($a=$_GET[a]);)$r*=$a[$i-1][1]/$a[$i][0];echo$r;

takes input from GET parameter a; prints result
initializes $r with 1, then loops from second to last tuple to multiply with first element of previous and divide through second element of current tuple.

Thanks to Jörg for reminding me of $_GET; that saved 7 bytes.

more elegant version, 88 bytes:
<?=array_reduce($a=$_GET[a],function($r,$x){return$r*$x[1]/$x[0];},$a[0][0]/end($a)[1]);

<?for($r=$i=1;$i<count($a=$_GET[a]);)$r*=$a[$i-1][1]/$a[$i++][0];echo$r; 72 Bytes

05AB1E, 5 bytes
¦¨.«/

Port of @xnor's Haskell answer, so also takes the input as a flattened list.
Try it online or verify all test cases.
Longer, but more interesting answer (9 bytes):
ü2εÅ/`/}P

Takes the input as pairs, like the challenge description.
Try it online or verify all test cases.
Explanation:
¦¨       # Remove the first and last items of the (implicit) input-list
  .«     # Then left-reduce it by:
    /    #  Dividing
         # (after which the result is output implicitly)

ü2       # Create overlapping pairs of the (implicit) input-list of pairs
  ε      # Map over each overlapping 2x2 block:
   Å/    #  Pop and push its main anti-diagonal: [[a,b],[c,d]] → [b,c]
     `   #  Pop and push both values separated to the stack
      /  #  Divide the first by the second: b/c
  }P     # After the map: pop and push the product of the list
         # (which is output implicitly as result)

JavaScript, 59 58 56 bytes
a=>a.reduce((p,c)=>p*c[1]/c[0],a[0][0]/a[a.length-1][1])

Explanation
Reduce the array and multiply by every second value and divide by every first value. So for [[6,12],[3,10],[5,8]] it does 12/6*10/3*8/5. Of course, the actual computation we wanted was 12/3*10/5 so we just want to ignore that first /6 and last *8 by multiplying *6 back in and dividing /8 back out. That cancelling out is done by setting 6/8 as the initial value for the reduce.

I came to the same solution. You can save two bytes by appending the post-operations *.../... to the initial value 1.

Python 2, 52 bytes
lambda x:reduce(lambda x,y:y/float(x),x[1:-1][::-1])

An anonymous function that takes input of a flattened list via argument and returns the output.
This makes use of the division cascade idea, as in xnor's answer.
Try it on Ideone

Python 3, 59 bytes
lambda x:eval('/'.join('{}*{}'.format(*i)for i in x)[2:-2])

An anonymous function that takes input of a non-flattened list via argument and returns the output.
How it works
For every pair of integers in the input, a string of the form 'int1*int2' is created. Joining all these pairs on / gives a string of the form 'int1*int2/int3*int4/...', which is the desired calculation, but includes the undesired first and last integers. These are removed by slicing out the first two and last two characters in the sting, leaving the desired calculation. This is then evaluated and returned.
Try it on Ideone

Pascal (FPC), 94 bytes
A recursive (had to do it..) function that takes a static 2D array and its length (no. of rows) as an input. Using some pointer math on the array.
function r(a:pdouble;n:integer):double;begin r:=a[1]/a[2];if n=2then exit;r:=r*r(a+2,n-1);end;

Try it online!
Ungolfed:
function ratio(a: pdouble; n: integer): double;
begin
  ratio := a[1] / a[2];
  if n=2 then
    Exit;
  ratio := ratio * ratio(a+2, n-1);
end;

Actually, 14 bytes
pXdX2@╪k`i/`Mπ

Try it online! (currently not working because TIO is a few versions behind)
This program takes a flattened list as input.
Explanation:
pXdX2@╪k`i/`Mπ
pXdX            remove the first and last elements
    2@╪k        push a list where each element is a list containing every two elements of the original list (chunk into length-2 lists)
        `i/`M   map division over each sublist
             π  product

R, 64 bytes
Turns out the vectorized approach and the for loop are equivalent in this case:
x=scan();prod(sapply(1:(sum(1|x)/2-1)*2,function(i)x[i]/x[i+1]))

or the for loop:
x=scan();for(i in 1:(sum(1|x)/2-1)*2)T=c(T,x[i]/x[i+1]);prod(T)}

`

Vyxal, 6 bytes
ḢṪ‡$/ḭ

Try it Online!

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


text:
Reverse Bayer Filter of an image
Almost all digital camera sensors are organized in a grid of photosensors. Each photo sensor is sensitive for one of the primary colors: red, green and blue. The way those photo sensors are organized is called the Bayer filter, after its inventor, Bryce Bayer of Eastman Kodak. After an image is taken, four photo sensors compose the RGB value of one pixel in the resulting image. Your task is to reverse that process and colorize the resulting pixels according to their filter color. For the sake of simplicity, we will ignore gamma correction.
For example: the "normal" forward Bayer filter steps are:

a lightray with a Pantone Beeswax color hits the sensor;
the BGGR (Blue - Green / Green - Red) filter decomposes this into four rays.
The four rays hit the sensor, which reads: 81 - 168 / 168 - 235 (sensor values range from 0 - 255);
The Bayer filter translates this to one RGB pixel with color (235, 168, 81).

The reverse Bayer filter steps are:

RGB pixel with color (235, 168, 81) is split into four pixels with RGB values: (0,0,81) - (0,168,0) / (0,168,0) - (235,0,0).

Challenge
You should write the shortest possible function or program that does the following:

Take a filename as in input and output the DeBayered image.

The output may be written to a file or displayed on the screen.

The output must be twice the width and twice the height of the original image.

Each pixel of the input image must be mapped according to the BGGR (Blue - Green / Green - Red) Bayer filter pattern as explained graphically in the following picture:

We'll assume that both green photosensors receive the same signal, so both the G values in the Bayer matrix are equal to the G value in the RGB image.

You may not return an array representation of the resulting image. The output must be an image or a file (in any suitable image format) that can be displayed as an image.

Example
Given this file as an input:

The resulting image should be:

Reference python implementation:
from PIL import Image
import numpy
import sys

if len(sys.argv) == 1:
    print "Usage: python DeByer.py <<image_filename>>"
    sys.exit()

# Open image and put it in a numpy array
srcArray = numpy.array(Image.open(sys.argv[1]), dtype=numpy.uint8)
w, h, _ = srcArray.shape

# Create target array, twice the size of the original image
resArray = numpy.zeros((2*w, 2*h, 3), dtype=numpy.uint8)

# Map the RGB values in the original picture according to the BGGR pattern#

# Blue
resArray[::2, ::2, 2] = srcArray[:, :, 2]

# Green (top row of the Bayer matrix)
resArray[1::2, ::2, 1] = srcArray[:, :, 1]

# Green (bottom row of the Bayer matrix)
resArray[::2, 1::2, 1] = srcArray[:, :, 1]

# Red
resArray[1::2, 1::2, 0] = srcArray[:, :, 0]

# Save the imgage
Image.fromarray(resArray, "RGB").save("output.png")

Remember: this is a code-golf, so shortest code wins!

Nearly got a seizure when I scrolled

@Fatalize sorry for that! ;-) Weird effect, isn't it?

The instructions show a cell with BG on the top row and GR on the bottom, while the example image shows RG on top and GB on the bottom.  Does that mean any arrangement that puts the two green cells on a diagonal is acceptable? (the others would be GB / RG and GR / BG.)

@LevelRiverSt my intention was to adhere to BGGR (as specified in the fourth challenge bullet). My mistake if the actual example image is in RGGB. I'll correct that as soon as I'm on my laptop.

I don't think your example image is correct, for one it has a weird blue tint

@orlp fixed this

Pyth, 26 bytes
MXm03H@GH.wsMsgLRRR,U2tU3'

Expects the input filename with quotation marks on stdin, and writes to o.png. Example output:

You answer is the shortest so far. I tend to accept it, but it would be nice if you could add an explanation how your program works.

I just used the Kronecker product, using an answer from a previous question: http://codegolf.stackexchange.com/questions/78797/calculate-the-kronecker-product/78811.

Matlab, 104 92 bytes
This makes use of the 3d-array/matrix representation of RGB images in Matlab, as well as the Kronecker product which is exactly what we need creating this new 2x2 "metapixel" form each source pixel. The output is then displayed in a popup window.
a=double(imread(input('')));for n=1:3;b(:,:,n)=kron(a(:,:,n),[1:2;2:3]==n)/255;end;imshow(b)

Resized screencapture:

That [1:2;2:3]==n is clever! Can't you remove b=[a,a;a,a];?

@LuisMendo Thanks=) It does indeed work, I didn't expect that!

Python 3, 259 254 bytes
from PIL.Image import*
o=open(input())
w,h=o.size
n=new('RGB',(2*w,2*h))
P=Image.putpixel
for b in range(w*h):x=b//h;y=b%h;r,g,b=o.getpixel((x,y));c=2*x;d=2*y;G=0,g,0;P(n,(c,d),(0,0,b));P(n,(c+1,d),G);P(n,(c,d+1),G);P(n,(c+1,d+1),(r,0,0))
n.save('o.png')

The input filename is given in standard input. Outputs to o.png.
Example usage:
$ echo mona-lisa.jpg | python bayer.py

Welcome to PPCG, nice first answer!

Mathematica 118 127 bytes
The original submission used an actual picture as input. This uses a filename instead.
It applies two replacement rules to the image data of the referenced file:

For each row of the image data matrix,replace each pixel {r,b,g} with a blue pixel, {0,0,b} followed by a green pixel, {0,g,0};
Separately, for each row of the image data matrix, replace each pixel {r,b,g} with a green pixel {0,g,0} followed by a red pixel, {r,0,0};

Then Riffle (i.e. interleave) the matrices resulting from 1 and 2.
Image[Riffle[#/.{{_,g_,b_}:>(s=Sequence)[{0,0,b},{0,g,0}]}&/@(m=Import[#,"Data"]/255),#/.{{r_,g_,_}:>s[{0,g,0},{r,0,0}]}&/@m]]&

Image[Riffle[#/.{{_,g_,b_}:>(s=Sequence)[{0,0,b},{0,g,0}]}&/@(m=Import[#,"Data"]/255),#/.{{r_,g_,_}:>s[{0,g,0},{r,0,0}]}&/@m]]&["mona.jpg"]

Not sure, but this doesn't seem to satisfy "Take a filename as in input"

agtoever, It now uses as input a filename instead of an image.

J, 100 96 90 bytes
load'bmp'
'o'writebmp~,./,./($a)$2 1 1 0(_2]\(2^0 8 8 16)*{)"1(3#256)#:,a=:readbmp]stdin''

This is a script in J that reads the filename of the input image from stdin and outputs the result to a file named o. The input and output images will both be in bmp format. It also expects only the filename to be input, meaning that leading and trailing whitespace should not be present.
Sample Usage
$ echo -n mona.bmp | jconsole reversebayer.ijs

Explanation
A=:readbmp]stdin''  Store the image in A as a 2d array of 24-bit rgb ints
,                   Flatten it into a list
(3#256) #:          Convert each 24-bit int to a tuple of 8-bit r/g/b ints
2 1 1 0 {"1         Select each column in BGGR order
(2^0 8 8 16) *      Shift each color to make it a 24-bit rgb value
_2 ]\               Convert each row from dimensions 1x4 to 2x2
($A) $              Reshape the list of 2x2 matrices into a matrix of
                    2x2 matrices with dimensions matching A
,./                 Append the 2x2 matrices by column
,./                 Append the 2x2 matrices by row - This is now a matrix of
                     24-bit rgb values with twice the dimensions of A
'o'writebmp~        Write the image array to a bmp file named 'o'

Python 2, 256 275 bytes
First I simplified the original code:
from PIL import Image
from numpy import*
import sys

# Open image and put it in a numpy array
srcArray = array(Image.open(sys.argv[1]), dtype=uint8)
w, h, _ = srcArray.shape

# Create target array, twice the size of the original image
resArray = zeros((2*w, 2*h, 3), dtype=uint8)

# Map the RGB values in the original picture according to the BGGR pattern#

# Blue
resArray[::2, ::2, 2] = srcArray[:, :, 2]

# Green (top row of the Bayer matrix)
resArray[1::2, ::2, 1] = srcArray[:, :, 1]

# Green (bottom row of the Bayer matrix)
resArray[::2, 1::2, 1] = srcArray[:, :, 1]

# Red
resArray[1::2, 1::2, 0] = srcArray[:, :, 0]

# Save the imgage
Image.fromarray(resArray, "RGB").save("o.png")

Then minify to:
from PIL import Image
from numpy import*
import sys
a=array(Image.open(sys.argv[1]),dtype=uint8)
w,h,_=a.shape
b=zeros((2*w,2*h,3),dtype=uint8)
b[::2,::2,2]=a[:,:,2]
b[1::2,::2,1]=a[:,:,1]
b[::2,1::2,1]=a[:,:,1]
b[1::2,1::2,0]=a[:,:,0]
Image.fromarray(b,"RGB").save("o.png")

Resulting in the image o.png:

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


text:
Interquartile Mean
Task
Given (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the interquartile mean.
One possible algorithm

Discard the lowest and highest quarters of the data points.
Calculate the average (sum divided by count) of the remaining data points.

Note: If the dataset size is not evenly split-able in four, you will have to weigh the datapoints that are shared by sub-sets. See Example evaluation 2 below.
Example evaluation 1
Given {1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38}

Data count is 12, so we remove lowest and highest 3 datapoints:{1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38}
Average of the remaining 6 datapoints:(5 + 6 + 6 + 7 + 7 + 8) / 6 = 6.5

Example evaluation 2
Given {1, 3, 5, 7, 9, 11, 13, 15, 17}

Count is 9, so each quarter has 2¼ datapoints:{1, 2, (0.25×5), (0.75×5), 7, 9, 11, (0.75×13), (0.25×13), 15, 17}
Average of the remaining 4.5 datapoints:(0.75×5 + 7 + 9 + 11 + 0.75×13) / 4.5 = 9

More test cases would help. Will there ever be fewer than 4 numbers?

@qwr Sure, there could be less than 4 numbers. Just use weighing. As for more text cases, you have plenty of solutions below. Just use them to generate results for any given input.

Scilab, 8 bytes
trimmean

See the documentation. By default, discard=50, so the IQM is computed.
EDIT: You know, this is a trivial built-in answer, so I’m marking it as CW.

I guess this will be the winner. Well done.

Pyth, 11 10 bytes

.O><lQS*4Ql
.OsPtc4S*4

Test suite.
How it works
It quadruplicates the input list to ensure that the data count is divisible by 4.
It still needs sorting, because *4 applies to the whole list instead of to each individual element.
Then, it splits the list into four equal parts, then takes away the first and the last part.
The remaining list is flattened and the average is taken.

MATL, 12 11 bytes
4Y"G"6L)]Ym

Input is a horizontal vector, with the format
[1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38]

or
[1 3 4 5 6 6 7 7 8 8 9 38]

Try it online!
Explanation
4Y"    % Input horizontal vector implicitly. Repeat each element 4 times (run-length
       % decoding). The resulting array is still sorted.
G"     % Push input, for each: repeat as many times as the input size
  6L)  %   Remove first and last elements, by applying the index "2:end-1"
]      % End for each
Ym     % Compute mean. Display implicitly

I don't get it. How does 6L) remove the first and last elements? When I do it, it pushes a bunch of complex numbers.

@DrGreenEggsandIronMan Complex numbers can be used for that in MATL. The imaginary unit stands for the end of the array, and if there are two of three numbers they define a range. So [2, -1+i] when used as an index means 2:end-1

Python 3, 50 bytes
lambda n:sum(sorted(n*4)[len(n):-len(n)])/len(n)/2

Ideone it!
How it works
It is a translation of my answer in Pyth.

Snowman, 66 bytes
}vg","aS:10sB;aM4aRAsOal`,4nD,`aG0AaGal`NdE`AaL1AfL:nA;alaF,nDtSsP

Try it online!
Uses the same algorithm as @LeakyNun's answers.
}         enable variables b, e, and g
vg        read a line of input into b
","aS     split on commas (in-place)
:10sB;aM  convert each element in resulting array to number ("frombase(10)-map")
4aR       repeat the array 4 times
AsO       sort the array
al        take the length and put it in e without consuming b (the array)
`,        swap b and e, then move e to g; now b=length g=array
4nD       divide b by 4 (4 was stored in e, which is why the array was moved)
,`        move the array and length/4 back to their original positions
aG        split the array into groups of length (length/4)
0AaG      take all elements with index >0 (i.e. remove the first element)
al        store the length of the new array in e again
`NdE`     bring it up to b, decrement, and put it back
AaL       take all elements with index <length-1 (i.e. remove last)
1AfL      flatten the array 1 level deep
:nA;      push a block that adds two numbers (to e)
al        store the length of this new array in g
aF        fold b over e (sum the numbers)
,         move g (the length) into e
nD        divide the sum by the length, resulting in the average
tSsP      to-string and print

This language looks awful. I love it.

Jelly, 14 13 12 bytes

x4ṫL‘$ḣLN$S÷LH
x4ṫLḊḣLN$S÷LH
x4œs4ḊṖFS÷LH

Try it online!
Test suite.
How it works
It is a translation of my answer in Pyth.

I'm pretty sure this can be shortened, as I can do it 15 in APL.

@Adám Please post your solution (so that I may copy haha)

I want to give Marinus a chance...

Here you go!

Enough of a chance after more than 9 months, certainly

Pyke, 16 13 bytes
4*S4ftOsDsRl/

Try it here!

You broke my streak...

I'm so sorry :(

Brachylog, 21 bytes
:3jo@4brbcLl/N,L+:N*.

Try it online! or verify multiple test cases
Explanation
This is basically @LeakyNun's Pyth answer algorithm.
:3j      Append 3 copies of the input to itself
o@4      Sort and split in 4 lists of equal length
brb      Remove the head and the tail of the list of lists
cL       Concatenate the 2 sublists into a list L
l/N,     N is the inverse of the length of L
L+:N*.   Output is the product of N and the sum of the elements of L

The only small trick there is in multiplying by the inverse of the length instead of dividing by the length, because division between 2 integers is integer division.

J, 20 18 bytes
2 bytes thanks to @miles

#-:@%~-@#+/@}.#}.4#]
-@#(+/%#)@}.#}.4#]

Try it online!
(Online interpreter)
Usage
>> f =: -@#(+/%#)@}.#}.4#]
>> f 1 3 5 7 9 11 13 15 17
<< 9

How it works
It is a translation of my answer in Pyth.

Online J interpreter.

@Adám Thanks, added.

You can just directly take the average of the middle portion -@#(+/%#)@}.#}.4#] for 18 bytes.

Octave, 44 bytes
@(x)mean(reshape(~~(1:4)'*x,[],4)(:,2:3)(:))

This defines an anonymous function.
The input is a horizontal vector.
Try it on ideone.
Explanation
The input horizontal vector is first matrix-multiplied (*) by a column vector of four ones (built with ~~(1:4)'). The result is a four-column matrix where each row is a copy of the input vector. This is then reshaped, while maintaining the linear order of the elements, into a 4-column matrix (reshape(...,[],4)). The center two columns are kept ((:,2:3)) and linearized into a single column ((:)), of which the mean is computed (mean(...)).

You can save 1 byte with the more readable [x;x;x;x] instead of ~~(1:4)'*x

@(x)mean([x;x;x;x](:)((b=numel(x))+1:3*b)) is also 2 bytes less. That was why I had come up with, but it's basically the same as your approach.

@TomCarpenter I don't think it's that similar. I think you should post it as a separate answer

Octave, 42bytes
Another anonymous function for Octave.
@(x)mean([x;x;x;x](:)((b=numel(x))+1:3*b))

You can try it online. Simply enter that command, and then do ans([1 2 4 5 6 9]) or whatever numbers are required.
This one starts by creating from the input array one with 4 of each input element by first concatenating four copies vertically, and then flattening it vertically. This maintains the sort order.
Then is extracts the range of elements from the length of the input array plus 1 up to three times the length of the input array. Because the new array is four times longer, this chops off the upper and lower quartiles.
Finally the mean of the new array is returned.

05AB1E, 15 bytes
€D€D¹gô¦¨˜DOsg/

Explanation
€D€D             # quadruple each element in list
    ¹gô          # split into pieces the size of input
       ¦¨˜       # remove the first and last and flatten the middle 2
          DOsg/  # sum and divide by length

Try it online

Actually, 20 15 13 bytes

;l╗;+;+S╜@t╜τ@HΣ╜τ@/
;l;τ;a;+;+StHΣ/
;l;τ;aττStHΣ/

Try it online!
How it works
It is a translation of my answer in Pyth.

For once, an Actually answer which is readable (in Greek).

@Adám Pyth uses ASCII.

JavaScript (ES6), 75 bytes
a=>a.concat(a,a,a).sort(g=(x,y)=>x-y).slice(l=a.length,-l).reduce(g,0)/l/-2

Uses the obvious quadruplicate-and-sort approach, and I get to use reduce, which is nice. The only trickery here is to save 4 bytes by reusing the sort comparator to subtract all the array elements from zero, which gives me -2l times the answer I want.

APL (Dyalog), 15 bytes
IQM←(+/÷≢)≢↓-∘≢↓4∘/

Try it online!
4∘/ quadruplicate each element
-∘≢↓ drop as many trailing elements as there are elements in the arguments
≢↓ drop as many leading elements as there are element in the argument
(…) apply the following tacit function:
 +/ the sum
 ÷ divided by
 ≢ the tally

Java 146 126 Bytes
Such java much verbose!
float m(float[]n){float r=0;int l=n.length,i=l/4;r-=(n[i])*(l%4)/4;r+=n[i*3]*(4-(l%4))/4;for(;i<l*3/4;r+=n[i],i++);return r/l*2;}

Older Ungolfed partially readable with test cases
/**
 *
 * @author rohan
 */
public Golf{

float m(float[]n){
//declarations
float r=0;
int x,i=0,l=n.length;
//sum the array
for(float m:n){r+=m;}
//remove the excess
for(;i<l/4;r-=n[i]+n[l-i-1],i++);
//weight the quartiles
r-=(n[l/4]+n[l*3/4])*(l%4)/4;
//return the sum/length but multiply by two since only half of the set is averaged
return r/l*2;
    }
static void interQuartileMean(float... set){
    System.out.println(new Golf().m(set));
}
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    //test cases pass with flying colours
        interQuartileMean(1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38);
        interQuartileMean(1, 3, 5, 7, 9, 11, 13, 15, 17);
    }

}

R, 17 11 bytes
mean(n,0.25)

Assuming n is the input vector in the standard R form n=c(1, 2, 3, ...).
This is in no way surprising since R can be considered “THE language for  statistical computing” and has many statistical built-ins.
UPDATE. Saved 6 bytes thanks to rturnbull because trim is the first optional argument by default!
Test cases:
a <- c(1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38)
b <- c(1, 3, 5, 7, 9, 11, 13, 15, 17)
mean(a,trim=0.25) # Returns 6.5
mean(b,trim=0.25) # Returns 9

Since trim is the default second argument, you don't need to name it; 0.25 can be shortened to .25 or 1/4. This saves you six bytes.

Golfscript, 28 29 bytes

~.4*$\,.@/1>2<{+}*{+}*'/'@2*
~.4*$\,.@/1>2<{+}*{+}*\2*-1?*

Try it online!

Actually, 12 bytes
4α;l¼≈;±(Htæ

Try it online! (currently doesn't work because TIO is a few versions behind)
Explanation:
4α;l¼≈;±(Htæ
4α            repeat each element 4 times
  ;l¼≈        length divided by 4, as integer
      ;±      copy, unary negate
        (Ht   remove first and last quartiles
           æ  mean

Mathematica, 51 bytes
Mean@#[[(l=1+Length@#/4);;-l]]&@Sort@Join[#,#,#,#]&

Sorts four copies of the list (to prevent issues with list length not multiples of four), takes part "1 quarter the length of resulting list plus 1" through to the "1/4 length list + 1 from the end", takes their Mean.

Clojure, 82 81 bytes
Edit: 1 byte less by re-writing "didvide by 2 n" part.
#(let[n(count %)](*(/ n)0.5(apply +(subvec(vec(for[i % j(range 4)]i))n(* 3 n)))))

Previous:
#(let[n(count %)](/(apply +(subvec(vec(for[i % j(range 4)]i))n(* 3 n)))(* 2.0 n)))

Uses for to generate 4 repeated values, using float 2.0 not to have fractional results, the rest is just standard.

Excel, 17 bytes
=TRIMMEAN(A:A,.5)

Relaxed input format make this easy.  Input one per row in Column A.

Perl 5, 80 + 2 -pa = 82 bytes
map{shift@F;pop@F}1..($b=@F/4);map$_*=1-($b-=0|$b),@F[0,-1];$_=sum(@F)/(@F-2*$b)

Try it online!

Awk, 68 bytes
{while(++i%5)p[++a]=$0}END{for(l=a/4;l<3*a/4;)s+=p[++l];print 2*s/a}

Try it online!

JavaScript (Node.js), 65 bytes
a=>eval(a.flatMap(x=>[x,x,x,x]).slice(n=a.length,-n).join`+`)/2/n

Try it online!


text:
Collect and place items
The goal of this challenge is to collect selected items in a list and move them to a certain location in the list.
As a visual example, take the input values (represented by black boxed integers) and a corresponding list of truthy values where true denotes the item is selected (represented by blue boxes, where T is truthy and F is falsy):

The first logical step is to separate the items marked truthy and not truthy into their corresponding lists. Note that relative order in each list must be maintained (i.e. the order of selected items must be 1,4,5, and the order of unselected items must be 2,3,6,7)!

The second logical step is given an index in the remaining list of unselected items, insert all selected items before the item at the given index. Assuming indexing starts at 0, suppose you want to insert the selection at index 3. This corresponds to the spot before the 7 box, so the selected items should be inserted before the 7.

The final solution is then 2,3,6,1,4,5,7.
Note that this logical diagram depicts one way this could be done; your program does not need to take the same logical steps as long as the output always produces the same observable result.
Input
Your program is given 3 inputs:

A list of integers representing the items. This may be an empty list. This list will always consist of unique positive integers, not necessarily in sorted order (i.e. 5 will not be in the list twice).
A list of truthy/falsy values with the same length as the list of items, where a truthy value represents that the item at the same index has been selected.
An integer representing where to insert the selection. You may choose what the index of the first item of the list is as long as it is constant in every run of your program (e.g. the first item could be index 0 or index 1). Please specify which convention your program adheres to. This index should be in the range [starting_idx, ending_idx+1], i.e. it will always be a valid index. For the case index is ending_idx+1, the selection should be inserted at the end of the list.
You may assume this integer will fit into your language's native integer type.

The input may come from any source desired (stdio, function parameter, etc.)
Output
The output is a list representing the final sequence of items. This can be to any source desired (stdio, return value, function output parameter, etc.). You are allowed to modify any of the inputs in-place (for example, given a modify-able list as a function parameter, and having your function operate in-place on that list).
Test cases
All of the following test cases assume 0-based indexing. I've used 0 and 1 to indicate falsy/truthy values respectively for the selection mask.
Test cases happen to have lists formatted as [a,b,c], but as long as your input lists represent a finite ordered sequence that's fine.
Input:
[]
[]
0

Output:
[]

Input:
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
3

Output:
[2,3,6,1,4,5,7]

Input:
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
0

Output:
[1,4,5,2,3,6,7]

Input:
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
4

Output:
[2,3,6,7,1,4,5]

Input:
[1,2,3,4,5,6,7]
[1,1,1,1,1,1,1]
0

Output:
[1,2,3,4,5,6,7]

Input:
[1,2,3,4,5,6,7]
[0,0,0,0,0,0,0]
5

Output:
[1,2,3,4,5,6,7]

Input:
[1,3,2,5,4,6]
[1,0,0,1,1,0]
3

Output:
[3,2,6,1,5,4]

Scoring
This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You are allowed to use any built-ins desired.

Can the input and output be like '"1 2 3", "1 0 0", 1'?

Yes, anything that represents two finite ordered integer sequences and an integer index in is fine.

Will the first array contain negative items or zero?

I want to say no, but I'm also intrigued at what solution you have which requires this. So yes, you may assume the first list contains only positive integer.

@PeterTaylor no. I fixed it to read "A list of truthy/falsy values...". Is there a good name to describe the "type" of truthy/falsy values? Boolean-like?

I've only seen them referred to as truthy and falsy.

MATL, 9 bytes
&)i:&)bwv

This solution accepts an array of T (true) and F (false) values as the second input. Also for the first test case, with empty arrays, it produces no output.
Try it Online! and a slightly modified version for all test cases.
Explanation
    % Implicitly grab the first two inputs
&)  % Index into the first array using the boolean, places two items on the stack:
    % 1) The values where the boolean is TRUE and 2) the values where it is FALSE.
i   % Explicitly grab the third input (N)
:   % Create an array from 1...N
&)  % Index into the FALSE group using this array as an index. Puts two items on the stack:
    % 1) The first N elements of the FALSE group and 2) other members of the FALSE group
b   % Bubble the TRUE members up to the top of the stack
w   % Flip the top two stack elements to get things in the right order
v   % Vertically concatenate all arrays on the stack
    % Implicitly display the result

Mathematica, 66 62 bytes
Saved 4 bytes from @MartinEnder.
a=#2~Extract~Position[#3,#4>0]&;##&@@@Insert[##~a~0,##~a~1,#]&

Anonymous function. Takes the 1-based index, the list, and the markers as input and returns the reordered list as output.

Haskell, 70 bytes
m%n=[e|(e,b)<-zip m n,b]
(l#s)p|(h,t)<-splitAt p$l%(not<$>s)=h++l%s++t

Usage example: ([1,2,3,4,5,6,7]#[True,False,False,True,True,False,False]) 3 -> [2,3,6,1,4,5,7].
How it works:
m%n=[e|(e,b)<-zip m n,b]        -- helper function, that extracts the elements of m
                                -- with corresponding True values in n
(l#s)p                          -- l: list of values
                                   s: list of booleans
                                   p: position to insert
  |                   (not<$>s) -- negate the booleans in s
                    l%          -- extract elements of l
          splitAt p             -- split this list at index p
   (h,t)<-                      -- bind h to the part before the split
                                -- t to the part after the split
     = h++l%s++t                -- insert elements at True positions between h and t

JavaScript (ES6), 76 bytes
(a,b,c)=>(d=a.filter((_,i)=>!b[i]),d.splice(c,0,...a.filter((_,i)=>b[i])),d)

Jelly, 10 bytes
¬+\>⁵Ḥ³oỤị

Try it online!
How it works
¬+\>⁵Ḥ³oỤị  Main link.
            Arguments: x (list of Booleans), y (list of inputs), z (index)
¬           Logical NOT; invert all Booleans in x.
 +\         Take the cumulative sum.
            This replaces each entry with the number of zeroes up to that entry.
   >⁵       Compare the results with z.
            This yields 0 for the first z zeroes, 1 for all others. The behavior
            for ones is not important.
    Ḥ       Unhalve; multiply the previous resulting by 2.
     ³o     Take the element-wise logical NOT of x and the previous result.
            This replaces all but the first z zeroes in x with twos.
       Ụ    Grade up; sort the indices of the result according to the corr. values.
        ị   Retrieve the items of y at those indices.

C#, 132 bytes
int[]r(int[]a,bool[]b,int l){var x=a.Where((i,j)=>!b[j]);return x.Take(l).Concat(a.Where((i,j)=>b[j])).Concat(x.Skip(l)).ToArray();}

ungolfed:
    public static int[] r(int[] a,bool[] b,int l)
    {
        var x = a.Where((i, j) => !b[j]);
        return x.Take(l).Concat(a.Where((i, j) => b[j])).Concat(x.Skip(l)).ToArray();
    }

improvement ideas appreciated.

Python 3, 106 93 bytes
def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):(f,t)[y[n]].append(x[n])
 f[z:z]=t
 return f

Older version:
def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):
  if y[n]:t+=[x[n]]
  else:f+=[x[n]]
 f[z:z]=t
 return f

Python 3, 91 bytes
def f(a,x,i):b=[c for c,z in zip(a,x)if z<1];return b[:i]+[c for c in a if(c in b)<1]+b[i:]

where a is the elements/numbers list,x is the True/False list and i is the index.
Multiline version for improved readability:
def f(a,x,i):
    b=[c for c,z in zip(a,x)if z<1]
    return b[:i]+[c for c in a if(c in b)<1]+b[i:]

How does it work?
The call to zip(a,x) results in a list of tuples where each of them contains the info: (element,0|1). Then a list comprehension is used to determine the elements that have a 0/False value associated and stores them in the variable b.
So [c for c,z in zip(a,x)if z<1] creates a list that contains all the elements that have a 0(False) value associated.
After that, the list of elements which have a True|1 value associated (which is determined by checking which elements of a are not present in b : [c for c in a if(c in b)<1]) is inserted in the list with all the elements that have a 0(False) value associated (list b) at the specified index i and the resulting list is returned.