Sum of positive integers. Problem:
Given a set of integers, find the sum of all positive integers in it.
Input:

t – number of test cases [t < 1000]
On each of next t lines, an integer N [-1000 ≤ N ≤ 1000]

Output
The program should output the sum of all the positive integers.
Check your code in online judge
Score
Score is equal to size of source code of your program except symbols with ASCII code ≤ 32.
Here is the best score list: Python Best Scores (Best score is 29)

Whitespace, 0

I couldn't resist. S= space, T= tab, N = newline, all have ASCII codes <= 32.

SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN

Base64 encoded for easy copy & paste.

ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ
ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg
IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo=


A Yoda-speaking challenge, this is The challenge
Well, I think it is quite clear, isn't it? You have to make a function or a program that takes a string as an argument and outputs the corrispondent Yoda-speaking.
This is code-golf, so least number of bytes wins.
The input
The input could be any string without linefeed. You can translate a string if it is composed like this:
Subject + Verb + Something else.
Where Subject is a personal pronoun (I, you, he, she, it, we, they). You don't have to recognize that the second word is a verb.
If the first word isn't a pronoun, the input is valid but the output will be Too difficult, this sentence is.
You have to win this code challenge -> Translatable
Luke has to win this code challenge -> Untranslatable

Input can end with a letter, a . or a !, not with a ?.
Furthermore, strings can contain Non-Ascii, Parenthesis, commas, colons ...
The output
In case of a translatable sentence, the output is the same sentence, with the subject and the verb at the end of the sentence.
You have to win this code challenge -> To win this code challenge, you have.

Comma, period and lower-case on the pronoun are mandatory. (Except, of course, if the pronoun is I).
As stated before, if it is untranslatable you have to output the string Too difficult, this sentence is.
Examples
You have to win this code challenge -> To win this code challenge, you have.
He won this code challenge -> This code challenge, he won.  (I know this is not yoda-speaking, but I don’t want to overcomplicate this challenge)
I ate an ice cream earlier! -> An ice cream earlier, I ate.
I liked the Star Wars original trilogy more than the prequel’s one. -> The Star Wars original trilogy more than the prequel’s one, I liked.
I find your lack of faith disturbing -> Your lack of faith disturbing, I find.
I think we are done with the examples -> We are done with examples, I think.
He is your son, Vader -> Your son, Vader, he is.
I think they’ll add new features -> They’ll add new features, I think.
I made a fantastic code challenge (I hope) -> A fantastic code challenge (I hope), I made.
I love constants like π -> Constants like π, I love.

I’ll be the next President, I swear! -> Too difficult, this sentence is.
This challenge is great! -> Too difficult, this sentence is.
Is this challenge great? -> Too difficult, this sentence is.
Luke is not ready for this task -> Too difficult, this sentence is.
Somebody loves constants like π -> Too difficult, this sentence is.
[Empty string] -> Too difficult, this sentence is.

Retina, 162 137 145 134 131 129
Multiple punctuation is now handled correctly. Test case: You will not win this challenge...! -> Not win this challenge..., you will.
Try it Online!
[.!]$

T`A-Z`a-z`^\w\w
G`^(I|we|you|s?he|it|they) \S+ \S
(\S+ \S+) (.*)
$2, $1.
T`a-z`A-Z`^.
^$
Too difficult, this sentence is.

Description:
If there is punctuation in the end, delete it.
[.!]$

^empty line

Transform the pronoun to lower case, except it is I.
T`A-Z`a-z`^\w\w

Filter out any line that does not match <Pronoun><space><word><space><word>...
G`^(I|we|you|s?he|it|they) \S+ \S

Split into pronoun + verb, remainder. Then rearrange.
(\S+ \S+) (.*)
$2, $1.

Transform the first character to upper case.
T`a-z`A-Z`^.

If the result is empty, it didn't pass the filter above. Print an error message.
^$
Too difficult, this sentence is.


Pseudosort a list in 2*n comparisons Write a program that takes a list of n space-separated integers, and outputs a permutation of that list using a maximum of 2*n comparisons.

It should loop this until an empty line is input.  Alternatively, it can accept inputs until an empty line is given, then output all the permutations.

Though your program only has to work on integers, it should be possible to implement your algorithm for any comparable data structures.  For example, using sign(a-b) to get extra comparisons is illegal, because the same algorithm can't be applied to data structures without numerical values.

Example session:

>0 1 2 3 4
0 1 2 3 4
>7 9 2 1
1 2 7 9
>6 7 4 5 2 3 0 1
0 2 3 1 4 5 6 7
>

or

>0 1 2 3 4
>7 9 2 1
>6 7 4 5 2 3 0 1
>
0 1 2 3 4
1 2 7 9
0 2 3 1 4 5 6 7

note: > shouldn't actually be printed, it's just being used to notate input vs output.

Scoring

Scoring is based mostly on how well sorted the permutations are, but also favours concise code.

Run your program with this file as input.  Use your program's output as input to this python script.  This script works under both python 2.7 and 3.3.  Other versions weren't tested.

import sys
def score(l):
    n = len(l)
    w = n**2 // 2
    s = sum(abs(l[i]-i)for i in range(n))
    return float(s)/w
s = 0.0
for i in range(40000):
    s += score([int(n) for n in sys.stdin.readline().split()])
print (int(s))

Your score is the output of the above script plus the length of your program

Explanation of Scoring

In the input file, there are 1000 lists for each length n in the range 10 <= n < 50.  In total, there are 40000 lists.  No two elements of a list will be equal.

To score a list, we define the unsortedness of a list as the sum of distances of each element from where it should be.  For example, for the list [0,1,4,3,2], the unsortedness is 4, because 4 and 2 are each 2 positions from where they should be, and the rest of the numbers are correct.

The worst case unsortedness of a list of length n is n^2 / 2, using integer division.

The score of a list is its unsortednes divided by the maximum unsortedness.  This is a number between 0.0 (sorted) and 1.0 (reversed).

Your total score is the sum of all scores in the input rounded down to an integer, plus the length of your program.  Because there are 40000 cases, a better pseudo-sort is likely better than shorter code, but if there is some optimal solution, then the shortest implementation of that solution will win.

Python, 7910 (7704 + 206)

This was inspired by shell sort.  I found relatively good coefficients for the gap sequence (g) by checking a few hundred alternatives.  The number of comparisons is limited by counting explicitly (n).

s=1
while s:
 s=map(int,raw_input().split());k=len(s);n=2*k;g=13*k/23
 while g:
  for i in range(g,k):
   n-=1
   if n<0:break
   if s[i]<s[i-g]:s[i],s[i-g]=s[i-g],s[i]
  g=3*g/5
 print' '.join(map(str,s))


Unique half rainbows If we take a positive integer \$n\$ and write out its factors.  Someone can determine \$n\$ just from this list alone.  In fact it is trivial to do this since the number is its own largest factor.
However if we take \$n\$ and write only the first half of its factors (factors that are smaller than or equal to \$\sqrt{n}\$), it becomes a lot more difficult to tell the original number from the list alone.  In fact, it frequently becomes impossible to tell at all.  For example both \$28\$ and \$16\$ give
\$
\begin{array}{ccc}
1 & 2 & 4
\end{array}
\$
as the first half of their factors (along with an infinite number of other solutions).  So if you show this list to someone they cannot know for sure what your original number was.
But some special cases do have a single unique solution.  For example
\$
\begin{array}{ccc}
1 & 2 & 3 & 5
\end{array}
\$
is unique to \$30\$.  No other number has these as its smaller factors.

The goal of this challenge is to write a program or function which takes as input an integer \$n\$ and determines if the first half of its factors are unique or not.
Your output should be one of two consistent values, one corresponding to inputs that are unique and one to inputs that are not.
This is code-golf so answers will be scored in bytes with fewer bytes being the goal.

Test cases
The first 120 truthy values are:
24 30 40 50 56 60 70 80 84 90 98 100 105 108 112 120 126 132 135 140 150 154 162 165 168 176 180 182 189 192 195 196 198 208 210 220 231 234 240 242 252 260 264 270 273 280 286 288 294 297 300 306 308 312 315 320 324 330 336 338 340 351 352 357 360 363 364 374 378 380 384 385 390 396 399 408 416 418 420 429 432 440 442 448 450 455 456 459 462 468 476 480 484 494 495 504 507 510 513 520 528 532 540 544 546 552 560 561 570 572 576 578 585 588 594 595 598 600 608 612

If you want more test cases I've written a reasonably fast generator (generates the first 500 in under 3 seconds on TIO).
Try it online!
For falsy values I recommend you check everything under 50 not on this list, but in particular 12.

Charcoal, 31 bytes
Ｎθ≔ＥＸ⊕θ²Φ⊕ι∧λ¬∨›Ｘλ²ι﹪ιλη⁼¹№η§ηθ

Try it online! Link is to verbose version of code. Inefficiently outputs a Charcoal boolean, i.e. - for unique, nothing if not. Explanation:
Ｎθ

Input n.
≔ＥＸ⊕θ²Φ⊕ι∧λ¬∨›Ｘλ²ι﹪ιλη

For all integers up to (n+1)², list those factors that do not exceed its square root.
⁼¹№η§ηθ

See whether the nth list is unique.
Edit: Switching from (2n)² to (n+1)² made the code an order of magnitude faster without generating false positives. At a cost of 3 bytes, 2+⁴√n⁵ would be even faster; this works because the worst case scenario is of the form p₁²p₂ where p₁<p₂<p₁²; the next integer with the same half rainbow is p₁p₂², and since p₂<p₁² we have p₂³<p₁⁶ and therefore (p₁p₂²)⁴<(p₁²p₂)⁵.


At least h with at least h Input

A list of nonnegative integers.

Output

The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h.

Test Cases

[0,0,0,0] -> 0
[12,312,33,12] -> 4
[1,2,3,4,5,6,7] -> 4
[22,33,1,2,4] -> 3
[1000,2,2,2] -> 2
[23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20

Rules

You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed.

Background

The h-index is a notion used in academia which aims to capture the impact and productivity of a researcher. According to Wikipedia, a researcher has index h, if he or she has published h scientific articles, each of which has been cited in other articles at least h times. Thus, this challenge is about computing the h-index from a list of citation counts.

Update

Wow, great answers all round! I have accepted the shortest one, but if someone else comes up with an even shorter one, I'll update my choice accordingly.

Winners by language

Here's a table of winners by language that I'll also try to keep up to date. I have included all posts with nonnegative score. Please correct me if I have made a mistake here.

APL: 7 bytes by @MorisZucca
Bash + coreutils: 29 bytes by @DigitalTrauma
C#: 103 bytes by @LegionMammal978
C++: 219 bytes by @user9587
CJam: 15 bytes by @nutki
GolfScript: 13 bytes by @IlmariKaronen
Haskell: 40 bytes by @proudhaskeller
J: 12 bytes by @ɐɔıʇǝɥʇuʎs
Java: 107 bytes by @Ypnypn
JavaScript: 48 bytes by @edc65
Mathematica: 38 bytes by @kukac67
Perl: 32 bytes by @nutki
Pyth: 10 bytes by @isaacg
Python: 49 bytes by @feersum
R: 29 bytes by @MickyT
Ruby: 41 bytes by @daniero
Scala: 62 bytes by @ChadRetz
SQL: 83 bytes by @MickyT
TI-BASIC: 22 bytes by @Timtech

Python, 52

f=lambda s,n=0:n<sum(n<x for x in s)and f(s,n+1)or n

A recursive solution. Run this in Stackless Python if you're worried about overflows.

Starting from n=0, checks whether at least n+1 of the numbers are at least n+1. If so, increments n and starts again. If not, outputs n.

The conditional is done using Python's short-circuiting for Booleans. The expression sum(n<x for x in s) counts the number of values in s that are greater than n by adding the indicator Booleans, which are treated as 0 or 1.

For comparison, the iterative equivalent is 2 chars longer. It requires Python 2.

s=input()
n=0
while n<sum(n<x for x in s):n+=1
print n

Unfortunately, the input need to be saved for a variable before being iterated over or else Python will try to read the input repeatedly.


(Python) Implementing incrementation Challenge: Implement incrementation without addition, multiplication, exponentiation, and any higher binary operators (and their opposites) in Python.
Winner is the person who can do it in the least amount of code. You score 5 characters less if you can do it for negative numbers and without unary operators.


Daily horoscope for zodiac signs Code a daily horoscope for the 12 zodiac signs, it needs to be self-sustained (no external ressources), quite randomized but fixed by zodiac sign for each day.

It needs to extract three "variables" from 1 to 3 :

love
work
money

Each one ranked from 1 to 3.

Ex. of variables that can be used (vars fixed for a day or more, can be extended) :

Year
Month
Day
Day of week
Math.PI
Zodiac signs order (from 1 to 12)

Python, 106 chars

import time,zlib
for i in range(12):n=zlib.crc32(time.strftime('%%Y%%j%d'%i));print 1+n%3,1+n/3%3,1+n/9%3

Calculates the CRC of a string made up of the current year, day of year, and zodiac sign.  Grabs some bits of the result for the horoscope.


Given a Tree generate its Prüfer Code In graph-theory a Prüfer code is a unique sequence of integers that denotes a specific tree.

You can find the Prüfer code of a tree with the following algorithm taken from Wikipedia:

  Consider a labeled tree T with vertices {1, 2, ..., n}. At step i, remove the leaf with the smallest label and set the ith element of the Prüfer sequence to be the label of this leaf's neighbor.

(Note that since it's a leaf it will only have one neighbor).

You should stop the iteration when only two vertices remain in the graph.

Task

Given a labeled tree as input output its Prüfer code.  You may take input in any reasonable manner.  Such as an adjacency matrix or your languages builtin graph representation. (You may not take input as a Prüfer code).

This is code-golf so you should aim to minimize the bytes in your source.

Test cases

Here are some inputs in ASCII with their outputs below.  You do not need to support ASCII input like this.

    3
    |
1---2---4---6
    |
    5

{2,2,2,4}

1---4---3
    |
5---2---6---7
|
8

{4,4,2,6,2,5}

5---1---4   6
    |       |
    2---7---3

{1,1,2,7,3}

Mathematica, 34 bytes

<<Combinatorica`
LabeledTreeToCode

Somebody had to do it....

After loading the Combinatorica package, the function LabeledTreeToCode expects a tree input as an undirected graph with explicitly listed edges and vertices; for example, the input in the second test case could be Graph[{{{1, 4}}, {{4, 3}}, {{4, 2}}, {{2, 5}}, {{2, 6}}, {{6, 7}}, {{5, 8}}}, {1, 2, 3, 4, 5, 6, 7, 8}].


Impatient divisibility test Your task is to write a program or function
that determines whether a number is divisible by another.
The catch is that it should give an answer as soon as possible,
even if not all digits of the number have been given.

Your program should take an integer D ≥ 2
and then a series of digits as input.
These represent the digits of another integer N ≥ 1,
starting at the least significant digit.
At the first point that N either must or must not be divisble by D,
your program should output the appropriate answer and exit.
If the end of the input is reached,
it should output whether the full N is divisible by D.

Here is a list of acceptable input formats for N
(leave a comment if you think something that isn't included should be allowed):

Standard input:
digits are given on separate lines;
end of input is EOF or a special value;
exit means that the function returns or the program exits.
Analog input:
through e.g. keystrokes or ten buttons representing each digit;
end of input is a special value;
exit means that the function returns or the program exits.
Function with global state:
called repeatedly with successive digits;
end of input is a special value;
exit means that the function returns a non-null value.
Note that if you use global state,
it must be cleared after a value is returned
or otherwise reset such that the function works multiple times.
Curried function:
returns either another function to be called with the next digit or a value;
end of input is a special value or calling the function with no argument;
exit means that the function returns an answer rather than another function.
GUI prompt or similar:
displayed repeatedly;
end of input is "cancel" or equivalent, or a special value;
exit means that prompts stop appearing.
Iterator function:
input is a stateful object or function that returns the next digit when called,
end of input is an exception or special value;
exit means that the iterator stops being called.

Input for D and the output
can be through any acceptable standard method.

Test cases:

2;   6               => true
5;   6               => false
20;  0 3             => false
20;  0 4             => true
100; 1               => false
100; 0 0             => true
100; 0 2             => false
4;   2 4             => false
4;   2 5             => true
4;   2 [eof]         => false
4;   4 [eof]         => true
625; 5 5             => false
625; 5 7 2           => false
625; 5 7 3 6         => false
625; 5 7 3 4         => true
7;   9 3 4 [eof]     => false
7;   9 3 4 5 [eof]   => true
140; 0 3             => false
140; 0 4 5 [eof]     => false
140; 0 4 5 1 [eof]   => true
14;  4 5 1 4 [eof]   => false
14;  4 5 1 4 1 [eof] => true

JavaScript (ES6), 70 bytes

Input format: Curried function

A function that takes the divisor and returns a function that takes each digit or \$-1\$ for EOF. The second function returns either \$0\$ (false), \$1\$ (true) or itself (no answer).

p=>(q='',g=(d,t=k=z=!~d||(q=d+q,p))=>k--?g(d,t-=(k+q)%p<1):t?t-z&&g:1)

Try it online!

How?

Given a divisor \$p\$ and a dividend \$q\$ consisting of \$n\$ decimal digits, we compute the following expression for all \$0 \le k < p\$:

$$k\times 10^n+q \pmod p\tag{1}$$

For any \$x\ge p\$ there exists \$m\ge 1\$ and \$0 \le k < p\$ such that \$x=mp+k\$, leading to:

$$x\times 10^n+q \pmod p=\\
(mp+k)\times 10^n+q \pmod p=\\
(mp\times 10^n \pmod p)+ (k\times 10^n+q \pmod p)\pmod p=\\
0+(k\times 10^n+q \pmod p)\pmod p=\\
k\times 10^n+q \pmod p$$

Therefore, if \$(1)\$ is equal to \$0\$ for all \$0 \le k < p\$, it will also be equal to \$0\$ for any \$k \ge p\$ and the answer is true.

For the same reason, if \$(1)\$ is greater than \$0\$ for all \$0 \le k < p\$, the answer is false.

If the results of \$(1)\$ are mixed, we can't decide yet and need either more digits of \$q\$ or the EOF notification.

Commented

p => (                       // p = divisor
  q = '',                    // q = dividend stored as a string, initially empty
  g = (                      // g() = curried function taking:
    d,                       //   d = next digit
    t =                      //   t = number of iterations yielding a non-zero value
    k =                      //   k = total number of iterations to process
    z =                      //   z = copy of k
      !~d ||                 //   if d == -1 (meaning EOF), use only 1 iteration
                             //   so that we simply test the current value of q
      (q = d + q, p)         //   otherwise, prepend d to q and use p iterations
  ) =>                       //
    k-- ?                    //   decrement k; if it was not equal to zero:
      g(                     //     do a recursive call to g():
        d,                   //       pass the current value of d (will be ignored anyway)
        t -= (k + q) % p < 1 //       test (k + q) % p and update t accordingly
      )                      //     end of recursive call
    :                        //   else:
      t ?                    //     if t is greater than 0:
        t - z && g           //       return 0 if t == z, or g otherwise
      :                      //     else:
        1                    //       return 1
)                            //


Reverse and add degeneracy Intro

Reverse and add is as simple as it sounds, take n and add it to its digits in reverse order. (e.g. 234 + 432 = 666).

If you apply this process repeatedly some numbers will eventually hit a prime number, and some will never reach a prime.

Example

I currently have

11431 rep.

11431 is not prime
11431 + 13411 = 24842 which is not prime
24842 + 24842 = 49684 which is not prime
49684 + 48694 = 98378 which is not prime
98378 + 87389 = 185767 which is prime!

This number hits a prime

In contrast any multiple of 3 will never hit a prime, this is because the all multiples of 3 have a digit sum that is a multiple of 3 and vice versa.
Thus reverse and add on a multiple of 3 will always result in a new multiple of 3 and thus never a prime.

Task

Take a positive integer n and determine if repeatedly reversing and adding will ever result in a prime number. Output a truthy or falsy value.  Either truthy for reaches a prime and falsy value for does not or the other way around both are acceptable.

Prime numbers will be considered to reach a prime number in zero iterations.

This is code-golf so try to make your code as short as possible.

Test Cases

True for reaches a prime false for never reaches a prime

11 -> True
11431 -> True
13201 -> True
13360 -> True
13450 -> True
1019410 -> True
1019510 -> True
22 -> False
1431 -> False
15621 -> False
14641 -> False

Hint

While I was writing this challenge I discovered a cool trick that makes this problem a good deal easier.  It is not impossible without this trick and it is not trivial with it either but it does help.  I had a lot of fun discovering this so I will leave it in a spoiler below.

   Repeated reverse and add will always hit a multiple of 11 in 6 iterations or less.  If it does not hit a prime before it hits a multiple of 11 it will never hit a prime.

Ruby, 84 79 77 74 bytes

->x{y=1;x+="#{x}".reverse.to_i while(2...x).any?{|z|0==y=x%z}&&x%11>0;y>0}

Try it online!

   If I got it right, when we reach a multiple of 11 we can stop (we will only get multiples of 11 after that)


Nest a string inside an array n times You must produce a function which nests a string s inside an array, n times

>>> N("stackoverflow",2)
[['stackoverflow']]

Parameters:

s - An ascii string
n - An integer >= 0

Rules

Shortest code wins.
The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Java and C#, 62 bytes

Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}

Should work without modification in both Java and C#.


Number of pieces on a checkers board Introduction

A normal checkers board contains 8 x 8 = 64 squares:

You can see that in total, there are 12 white pieces. Black and white always have the same amount of pieces. If there are any more pieces on the board, the pieces would neighbouring, which is not allowed for this challenge. To clarify things, here are some examples:

The smallest board possible for this challenge is 3 x 3:

You can see that the maximum amount of pieces is equal to 2. So, when given N = 3, you need to output 2. If the input is N = 4, we get the following:

You can see that the maximum amount is also 2. So for N = 4, the output should be 2. For N = 5, the output should be equal to 5:

Examples

STDIN:  3
STDOUT: 2

STDIN:  4
STDOUT: 2

STDIN:  5
STDOUT: 5

STDIN:  6
STDOUT: 6

STDIN:  8
STDOUT: 12

Rules

Your submission must be a program, or function etc.
that takes one integer and outputs or returns the number of pieces on the board
You can safely assume that the input is an non-negative integer > 2
This is code-golf, so the program with the least amount of bytes wins!
Note that the square in the lower left of the board is always dark. Pieces are only placed on dark squares
You have to occupy a full row with pieces

Hexagony, 19 bytes

?({{&2'2':{):!/)'*/

Try it online.

Explanation

This is still the same computation as I've used in my CJam and Labyrinth answers, but due to Hexagony's... special... memory model, it's a bit trickier to squeeze the computation into 19 bytes (so that it fits inside a side-length 3 hexagon).

Like my Labyrinth answer, this terminates with a division-by-0 error.

Here is the unfolded code:

As I said the code is entirely linear. You can piece the executed path together in order grey-purple-green-red-blue. The path actually continues a bit further until it hits the : on the left. Removing the / (which only redirect control flow), the entire program unrolled linearly is:

?({2':{)'*){&2':!:&?':

So the question is how does it work. Hexagony's memory is the line graph of a hex grid, where each edge of the grid contains an integer value (initially zero). The memory pointer (MP) is always on one edge and points in a certain direction along that edge. Arithmetic operations are generally applied to the two edges pointed at and stored in the edge the MP is on.

For this program, we'll be using the three edges labelled A, B, C, with the MP starting as shown here:

So here is how this works:

?  Read an integer N from STDIN into edge A.
(  Decrement to get N-1.
{  Move the MP forwards onto edge B.
2  Set the edge to 2.
'  Move the MP backwards onto edge C.
:  Divide edge A by edge B (rounding down) to compute (N-1)/2.
{  Move the MP forwards onto edge A.
)  Increment to restore value of N.
'  Move the MP backwards onto edge B.
*  Multiply edges A and C to compute N*(N-1)/2.
)  Increment to compute N*(N-1)/2 + 1.
{  Move the MP forwards onto edge C.
&  This actually a copy operation, but we use it to reset the edge to zero.
2  Set the edge to 2.
'  Move the MP backwards onto edge A.
:  Divide edge B by edge C to compute (N*(N-1)/2 + 1)/2.
!  Output the result as an integer. We're basically done now.
:  no-op (we already have this value)
&  Copy either B or C into A (doesn't matter).
?  Read a zero (EOF) into A.
'  Move the MP backwards onto an unused cell.
:  Divide some unused cell by A (which is zero), terminating with an error.


Implement QuickSort in BrainF*** As discussed in the Lounge room on Stack Overflow:

  if you can't implement the Quicksort algorithm given en.wikipedia.org/wiki/Quicksort in any language you have minimal knowledge of, you might want to consider a different profession. @sbi

but SBI also noted that maybe BrainF*** was an exception.

So, here's the puzzle/challenge: implement QuickSort in BrainF***. The implementation must

be interpreted by this and/or by the interpreter(s) here (for large scripts)
implement the algorithm as described on Wikipedia - if possible as an in-place sort
sort the following list of integers: [0,4,6,4,2,3,9,2,3,6,5,3] and print the result


Jolly gerrymandering Background

The United States has a unique love of gerrymandering––the deliberate manipulation of an electoral district to predict certain voting results. Just recently there was a gerrymandering case brought before the Supreme Court. Gerrymandering, especially when related to race, is ruled illegal and results in the requirement to redraw the district lines.

Given a rectangular map of a municipality (2d array), you will draw district lines to help your party get the most representation. That is, you will gerrymander. Every municipality has two parties, 0 and 1. The map will be comprised of squares with either 0 or 1 on them. Here is an example map:

Challenge

You will group the map into districts so that the 1 party will get at least the number of districts specified by the Input.

Input

The input will consist of a map, the number of districts to draw, and the minimum number of districts the 1 party needs to win (the minimum score).

Output

The output will be a map of the districts. Each district will be uniquely comprised of a capitalized letter of the alphabet. Yes, this means that there will not be more than 26 districts.

If there is no possible output where the inputted party wins enough districts, either:

Print “We tried...”
Fatally error because the party was irreparably injured by the  election results
Or both

Rules (also very important)

All districts must be contiguous
Districts may not have other districts in them
Each district must have at least four nodes in it. The input will be consistent with the rules, meaning that there will be at least number_of_districts * 4 nodes in the map
The score of each party is the number of districts it has a majority in
If a district has the same number of 0s and 1s, then neither party benefits from it
Normal no-cheating rules
This is code-golf, so shortest code in bytes wins.

Test cases

1. Input       1. Output       2. Input       2. Output     3. Input      3. Output
districts: 5   Image and map   districts: 3   Image below   districts: 3  fatal error
min wins: 3                    min wins: 3                  min wins: 3
map:                           map:                         map:
00000110000    AAAAAAAAAAA     101101                       101101
10000010000    AAAAAAAAAAA     100000                       100000
10010000011    AAAAAAAAAAA     011011                       011011
11001110000    BBBBBBBAAAA     111111                       100111
00111111000    BBBBBBBAAAA
01111111000    CCCCCDDDAAA
01111111001    CCCCCDDDAAA
01000111100    EEEEEDDDDDD
00000001000    EEEEEDDDDDD

Of course, your program should work for any valid test case, not just these ones.

R, 938 896  858 952 bytes

function(N,M,m){U="We tried...
"
L=length
A=matrix
W=which
K=sum
S=sample
G=unique
H=function(s,p=s-1){Y=S(c(s-j,s+j,p*(p%%j>0),(s+1)*(s%%j>0)))
Y[Y>0&Y<=k]}
C=function(v,z=W(r==v))K(z%%j<2,z-j<0,(z+j)>k)
m=A(strsplit(m,"")[[1]],1)
i=W(m<0)[1]-1
m=((t(A(m,i+1))[,1:i]>0)-.5)*2
if((K(m)<M&(N-M)<1)|K(m>0)<(3*M))cat(U) else{j=max(1,nrow(m))
k=i*j;w=g=T
while(w<9&g){Z=R=N;Q=M;b=0
r=A(0,j,i)
while(b<9&g){s=W(r<1)
s=s[S(L(s))][1:min(L(s),R)]
r[s]=1:L(s);a=0
while(K(r<1)>0&a<(k^2)){a=a+1
s=S(W(r>0&r<=R),1);p=r[s]
Y=H(s)
Y=Y[r[Y]<1]
if(L(Y)){Y=Y[order(m[Y])]
if(K(m[r==p]>1))r[Y[1]]=p else r[Y[L(Y)]]=p}}
if(a<(k^2)){for(v in 1:R){if(K(m[r==v])>0){r[r==v]=max(k,max(r))+1
Q=Q-1;Z=Z-1}}
if(Q<1){g=F
for(v in 1:R)r[r==v]=max(k,max(r))+1
for(v in G(c(r)))g=g|(K(r==v)<4)|(L(G(r[H(W(r==v))]))+C(v))<3}}
b=b+1;r[r<=R]=0;R=Z}
w=w+1}
if(g)cat(U) else{u=G(c(r))
for(v in 1:L(u))r[r==u[v]]=v
cat(paste(apply(A(LETTERS[r],j,i),1,paste,collapse=""),collapse="
"))}}}

Try it online!

A massive >900 >800 (nope!) >900 bytes solution.
The code works as follows. Let N be the number of electoral districts and M the minimum number of district where 1 wishes to have a majority.

First, the code randomly assigns N districts to different groups. Next, it randomly expands them, i.e. adds a district to a randomly selected group, ensuring that the district is next to a district already belonging to that group. In the expansion process, it gives precedence to a district with a 1 majority, if the district group is not yet a full 1 majority; if the group is already a certain 1 majority, then it gives precedence to a 0 district. It continues until all districts have been assigned.

Every group where there is a majority for the 1 party is stored, and its districts are locked. If there are at least M groups with a majority of 1, then everything is good and we can print the result we can check whether there are at least 4 districts in each group. If the cutoff of 4 districts is met, then we can happily print the result. Otherwise, the code tries to reassign the districts that are not locked to as many groups as available, i.e. N - #stored-groups.

The codes tries a few times (9 times). If it fails, it resets everything and starts again. It does so for other 9 times before giving up and printing "we tried...".

If the code does not succeed at first, try again a few times. I tuned the number of repetitions such that it can run in TIO under a minute. However if there is a solution, this code can (eventually) find it. The randomness part of the algorithm gives a non-zero probability that, if there is a solution, it can find it. The limited number of trials is the only limiting factor to success.

EDIT: added the control that no district group can be fully surrounded by just another one, unless the district group has districts on the edge of the given square. I think I missed it at first.


Write a program that outputs the number of times it has been run In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.
For example, this (ungolfed) Python 3 program satisfies this behavior:
N = 1
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)

Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.
If the file were named incr.py, running it on the command line would look something like this:
C:\somepath> python incr.py
1
C:\somepath> python incr.py
2
C:\somepath> python incr.py
3
C:\somepath> python incr.py
4

At this point, incr.py would read:
N = 5
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)

Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)
Give the program that prints 1 in your answer. Programs for all higher N can then be inferred. The shortest 1-printing program in bytes wins.
Notes

The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.

Your program must actually rewrite its own source code file, not simply output its modified source like a quine.

The file name and/or path of the source file may be hardcoded into your program (e.g. 'incr.py' could have replaced __file__ in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.

The source file's name and path should not change during execution.

Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:

Printing N to stdout.

Changing the source file so it will print N+1 when next run.

bash (+ wc + id), 16 bytes

wc -l<$0;id>>$0

Counts its lines, then appends a line of garbage to itself.

Needs a trailing newline.

Crashes on line 2 with a syntax error, which thankfully prints to STDERR and exits.

After three invocations, the script looks like this for me:

wc -l<$0;id>>$0
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)


How fast am I vrooooming? Introduction
My car speedometer was hacked! Instead of showing me how fast i'm driving, it just shows: "Vroooom!" Please help me know how fast i'm going.
Challenge
Take a string as input, and check if it matches the regex /^[Vv]ro*m!$/m. In English that means any line of the string must start with a capital or lowercase v, then a lowercase r, then any amount (including zero) of the lowercase letter o, then the exact string m!. There may be other lines, but the Vroom string must be on it's own line.
If you find a match, then you must count the amount of o's in the Vroom string and output it. If you don't find a match however, you should output any default value that can't be outputted otherwise (like -1 or an empty string)
Reminders

I/O is in any reasonable format
Standard loopholes are banned
Submission may be a full program or function
Input is guaranteed to only have 1 Vroom string

Scoring
This is code-golf, so the shortest code in bytes wins. However, I will not mark any answer as accepted.
Test cases
Input
Vrom!

Output 1
Input
vrooooooom!

Output 7
Input
Hello, Vroom!

Output (none)
Input
Foo bar boo baz
Vrooom!
hi

Output 3
Input
Vrm!ooo

Output (none)
Input
PPCG puzzlers pie

Output (none)
Input
hallo
vROOOm!

Output (none)

sed 4.2.2, 20 bytes

-nr options required at the command-line.

s/^[Vv]r(o*)m!$/\1/p

This outputs the speed in unary as the number of os.

Try it online!


Calculate longest Stack Exchange streak Introduction
This challenge is inspired by the Meta Stack Exchange question The longest consecutive days streak; it turns out that the URL https://codegolf.stackexchange.com/users/daily-site-access/[user id], where the last number is your user ID (found in the URL of your profile) contains information about which days you visited the site, in the following format:
var visited = {2015:{6:{3:1,8:1,12:1,13:1,18:1,19:1,21:1,22:1,23:1,24:1,26:1},7:{7:1,8:1,9:1,10:1,11:1,12:1,14:1,16:1,19:1,21:1,23:1,27:1,28:1,29:1,30:1},8:{1:1,2:1,3:1,5:1,7:1,17:1,19:1,23:1,26:1,28:1,30:1},9:{5:1,6:1,7:1,14:1,22:1,25:1,29:1,30:1},10: ...

(When viewed in a browser, the document seems empty; try viewing the source instead. Unless you are a ♦ moderator, you can only see this information for your own account.)
The string has a rather peculiar format but presumably it's an easy way to populate the calendar:

The information can be used to calculate the longest consecutive days streak, i.e. the one that determines if you get the Fanatic badge. The linked question has a working JavaScript example by user @ShadowWizard.
Standard code-golf rules apply: the shortest code wins.
Input
A string with the exact format provided by Stack Exchange, e.g. {2015:{6:{3:1}}}. Top level keys are years, second level keys are months, third level keys are days. All values are 1. You may assume the dates are not earlier than July 31st, 2008, which is when the first Stack Overflow question was posted. You may also assume there's at least one day in the input; the information is only provided to registered users, who must have visited the site at least once.
Output
The length of the longest streak, i.e. consecutive days in the input. You may choose to return it as a number or a string.
Test cases
(besides your own streak on CGCC of course; you should be able to verify if you're eligible for the Enthusiast and Fanatic badges or not)

Input
Output

{2015:{6:{3:1}}}
1

{2015:{6:{3:1}},2016:{6:{3:1}}}
1

{2015:{6:{3:1},7:{3:1}}}
1

{2015:{6:{3:1,5:1}}}
1

{2015:{6:{3:1,4:1}}}
2

{2015:{2:{28:1},3:{1:1}}}
2

{2016:{2:{28:1},3:{1:1}}}
1

{2016:{1:{30:1},2:{1:1}}}
1

{2016:{4:{30:1},5:{1:1}}}
2

{2016:{4:{30:1},6:{1:1}}}
1

{2016:{12:{31:1}},2017:{1:{1:1}}}
2

{2016:{12:{31:1}},2018:{1:{1:1}}}
1

{2016:{11:{29:1},12:{30:1,31:1}},2017:{1:{1:1,2:1,4:1}}}
4

{2100:{2:{28:1},3:{1:1}}}
2

{2400:{2:{28:1},3:{1:1}}}
1

Python 2,  186 184 179 177 173 172  162 bytes
-10 thanks to ovs! (avoiding use of .items)

x=input()
from datetime import*
a=sorted(date(y,m,d)for y in x for m in x[y]for d in x[y][m])
print max(map(len,`[d+timedelta(1)in a for d in a*2]`.split('s')))/6

Try it online! Or see the test-suite.
Huh, how?
In Python 2 input implicitly attempts an eval on the string which, in this case, will produce a nested dictionary.
a is then a list of the dates in order (sorted(...)), this is formed by inspecting the nested dictionaries in a nested for loop, and passing the resulting parts of the dates to date(year, month, day).
[d+timedelta(1)in a for d in a*2] forms a list of booleans which identify whether the next date is present for each date in the sorted dates repeated twice, a*2.
Note that the final value of a will always be False. The reason for repeating a is to avoid something later (see the final paragraph).
`[...]` gets the Python string representation (AKA repr) of that list - for example, something like "[False, True, True, False, False, False, True, True, False, False]" for an input with three consecutive dates between two others.
.split('s') splits the resulting string at occurrences of the 's' character - so for the above, that would be ['[Fal', 'e, True, True, Fal', 'e, Fal', 'e, Fal', 'e, True, True, Fal', 'e, Fal', 'e]'].
map(len,...) simply gives us a list of the lengths of the strings in the above list - so for the above, that would be [4, 18, 6, 6, 18, 6, 2].
max(...) gives the maximum value of that list - so for the above, that would be 18.
To find the number of consecutive days we want to count how many Trues there were in that longest section and then add one. In the above example, we can simply divide by six (the length of either 'True, ' or 'e, Fal'), hence the /6 at the end.
If the longest run of consecutive dates is at the left of the sorted dates we'd get something like '[True, True, Fal' (or '[Fal' when no dates at all are consecutive), which would be two shy of what we need, so if we were to perform all of this across a rather than a*2 we'd need to add two before performing the integer division (e.g. (...+2)/6). This wouldn't affect any other results but costs one more byte than simply repeating a with a*2, whereupon we'll get the longer string later on - this is guaranteed by the fact that d+timedelta(1) for the maximal d will give False.


Ellipsoid surface area Related: Ellipse circumference
Introduction
An ellipsoid (Wikipedia / MathWorld) is a 3D object analogous to an ellipse on 2D. Its shape is defined by three principal semi-axes \$a,b,c\$:
$$ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 $$
Just like an ellipse, the volume of an ellipsoid is easy, but its surface area does not have an elementary formula. Even Ramanujan won't save you here.
The basic formula is given as the following:
$$ S = 2\pi c^2 + \frac{2\pi ab}{\sin\varphi}
\left( E(\varphi,k) \sin^2\varphi + F(\varphi,k) \cos^2\varphi \right) \\
\text{where }\cos\varphi = \frac{c}{a},\quad k^2 = \frac{a^2(b^2-c^2)}{b^2(a^2-c^2)},\quad a \ge b \ge c $$
\$F\$ and \$E\$ are incomplete elliptic integral of the first kind and second kind respectively. Note that the formula does not work for a sphere.
A good approximation can be found on this archived page, where Knud Thomsen developed a symmetrical formula of
$$ S \approx 4\pi \left(\frac{a^p b^p + b^p c^p + c^p a^p}
{3 - k\left(1-27abc/\left(a+b+c\right)^3\right)}\right)^{\frac{1}{p}} $$
with empirical values of \$p=\frac{\ln 2}{\ln (\pi/2)}\$ and \$k=3/32\$.
Challenge
Given the three principal semi-axes \$a,b,c\$ of an ellipsoid, compute its surface area.
All three input values are guaranteed to be positive, and you can use any reasonable representation of a real number for input. Also, you may assume the three values are given in a certain order (increasing or decreasing).
The result must be within 0.1% (=10-3) relative error for the given test cases. You can go for the exact formula (if your language has the necessary built-ins) or Thomsen's approximation, or you can go for numerical integration (extra brownie points if you succeed in this way).
Test cases
The true answer was calculated by feeding the corresponding ellipsoid equation into WolframAlpha.
a  b  c  => answer
------------------
1  1  1  => 12.5664
1  1  2  => 21.4784
1  2  2  => 34.6875
1  1  10 => 99.151
1  2  3  => 48.8821
1  10 10 => 647.22
1  3  10 => 212.00

JavaScript (ES7),  86 83  82 bytes
Saved 3 bytes thanks to @xnor
Saved 1 byte thanks to @VarunVejalla
An approximation of Thomsen's approximation.

(a,b,c)=>(519*((a*b)**(p=1.535)+c**p*(b**p+a**p))/(31+27*a*b*c/(a+b+c)**3))**(1/p)

Try it online!


Generate all combinations of given list of elements, sorted Make a code that takes a list and a number as input, and generates all possible combinations with the length of the number. For example, with the list {0,1} and the number 2:

00
01
10
11

Your program doesn't have to expect characters twice or more often in the list, such as {0,0,0,0,0,1,1,5,5}

Make sure you print the combinations out sorted, in the order of the list:

With the list {0,1} and the number 5 (generated by some of my code, which is a way too long to win):

00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111

But with the list {1,0} and the number 2:

11
10
01
00

As you can see, reversed list means reversed order.

Take a look at the structure, it's like a tree.

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

Jelly, 1 byte

ṗ

TryItOnline

Cartesian power built-in atom, as a dyadic link with left argument the items and right argument the count, or as a full program with first argument the items and second argument the count.


Drawing Lewis Structures of Alkanes I just had a lesson in school about alkanes and figured it would probably make for a great code golf challenge! Don't worry, it isn't as complicated as it may look!

A Quick Rehash

(Please Note: To keep this brief, not all information is 100% accurate.)

Alkanes are strings of carbon and hydrogen. Every carbon atom has 4 bonds, and every hydrogen atom 1 bond. All the carbon atoms of the alkane form a string where each C-atom is connected to 2 other C-atoms (left and right in the Lewis structure) and 2 H-atoms (up and down), except for the ends of the string, where the C-atom is connected to only 1 other C but 3 Hs. Here's a basic example for pentane (an alkane with 5 C-atoms and 12 H-atoms):

  H H H H H
  | | | | |
H-C-C-C-C-C-H
  | | | | |
  H H H H H

Alkanes also can have branches. But don't worry, all alkanes in this challenge can be expressed with only 1 level of branching. Example:

        H
        |
      H-C-H
  H H H | H
  | | | | |
H-C-C-C-C-C-H
  | | | | |
  H H H H H

For completing this challenge you also must understand the IUPAC naming convention for branched alkanes. First of there's the root alkane. In our previous example, this would be the "C-C-C-C-C" part. Depending on how long this chain is, it has a different name. 1 C is called methane, 2 C ethane, 3 C propane, then butane, pentane, hexane, heptane, octane, nonane and decane (10 C). Then, for each branch, there's a certain prefix to that: First of, there's the index (offset) of the C-atom the branch is appended to (count from the left). In the example, this would be 4 (aka it's the 4th C-atom from the left). Then there's a hyphen (this symbol: "-") and after that another name indicating the size of the branch. The naming of the size of the branch is almost same like the naming of the  size of the root, just that instead of "ane" you append "yl". With that the full name of the example would be

4-methylpentane

If you have multiple branches, then they are prepended as well, separated by another hyphen. Example:

2-butyl-5-methylhexane

One last thing: if you have multiple branches of the same size, they get grouped; their offsets are separated by comma and they share the same size-name, which gets prepended by an extra syllable depending on how many branches are grouped: "di" for 2 branches, "tri" for 3, "tetra" for 4 (you don't need more for this challenge). Example:

2-ethyl-2,4,6-trimethyldecane

FYI, this could look somewhat like this: (Omitted H-atoms)

   |
  -C-
   |       |
  -C-     -C-
 | | | | | | | | | |
-C-C-C-C-C-C-C-C-C-C-
 | | | | | | | | | |
  -C- -C-
   |   |

Nomenclature Cheatsheet

Prefixes indicating numbers:
| Num  | Prefix |
|------|--------|
| 1    | meth   |
| 2    | eth    |
| 3    | prop   |
| 4    | but    |
| 5    | pent   |
| 6    | hex    |
| 7    | hept   |
| 8    | oct    |
| 9    | non    |
| 10   | dec    |
Suffix root:   ane
Suffix branch: yl
Prefixes grouping: di, tri, tetra

The Rules

Write a program that reads in such an IUPAC name from STDIN, program arguments or equivalent and draws it as an ASCII-art lewis structure to STDOUT (or equivalent).

For simplicity, you DO NOT have to draw the H-atoms (Else you will run into spacing issues)
You are NOT allowed to print any empty leading or trailing horizontal lines
The chains you have to parse won't be any longer than 10, and the maximum of branches in a "group" is limited to 4.
The maximum "offset" of a branch is 9 (meaning that you don't have to parse more than 1 digit)
Your branches have to alternate between going up and down after every new branch. In case this space is already taken by another branch at the same offset, you have to draw it on the other side of the root. (up->down, down->up)
On corrupt, not-correctly-formatted or otherwise not-drawable input, your program may behave unspecified.

This is code golf, shortest code in bytes wins!

Happy golfing! :)

Python 2, 620 bytes
import re
i=input()
s='m|e|pr|b|p|hex|h|o|n|de';d=dict(zip(s.split('|'),range(1,11)))
z=[[eval('['+a+']'),d[b]]for a,b in re.findall('(?:(\d[,\d]*).*?[\-ia]|l)('+s+')',i[:-3])]
v=z[-1][1]
l=[[0,0]for _ in range(v)]
c=0
for a,b in sorted([(i,b)for a,b in z[:-1]for i in a]):l[a-1][c]=b;c=~c
m=[max(x) for x in zip(*l)]
L,R=[[[' 'for _ in '_'*2*i]for _ in '_'*(2*v+1)]for i in m]
c=[' |'*v+' ']
C=c+['-C'*v+'-']+c
for i in range(len(l)):
 X=L;q=2*i+1
 for a in l[i]:
  if a>0:
   for j in range(0,2*a,2):
    X[q][j]='C'
    X[q-1][j]=X[q+1][j]='-'
    X[q][j+1]='|'
  X=R
for l in zip(*L)[::-1]+C+zip(*R):print ''.join(l)

Explanation
Input:
'2-ethyl-2,4,6-trimethyldecane'
First parses to string with regex (last group is root):
[[[2], 2], [[2, 4, 6], 1], [[], 10]]
Each branch is written in an array of length len(root) (Alternating up/down is handled here):
[[0, 0], [1, 2], [0, 0], [1, 0], [0, 0], [0, 1], [0, 0], [0, 0], [0, 0], [0, 0]]
'Left' and 'Right'(L,R) and 'root' (C) string branches are initialized.
Each branch is then added to the corresponding 'string' branch (big loop).
The two sides and center are printed at the end:
   |   |
  -C- -C-
 | | | | | | | | | |
-C-C-C-C-C-C-C-C-C-C-
 | | | | | | | | | |
  -C-     -C-
   |       |
  -C-
   |


Fermat's polygonal number theorem Fermat's polygonal number theorem states that every positive integer can be expressed as the sum of at most \$n\$ \$n\$-gonal numbers. This means that every positive integer can be expressed as the sum of up to three triangle numbers, four square numbers, five pentagonal numbers etc. Your task is to take a positive integer \$x\$, and an integer \$s \ge 3\$, and to output the \$s\$-gonal integers which sum to \$x\$.

The \$n\$-th \$s\$-gonal integer, where \$n \ge 1\$ and \$s \ge 3\$, can be defined in a couple of ways. The non-math-y way is that the \$n\$th \$s\$-gonal number can be constructed as a regular polygon with \$s\$ sides, each of length \$n\$. For example, for \$s = 3\$ (triangular numbers):

See here for examples with a larger \$s\$.

The math-y definition is by using the formula for \$P(n, s)\$, which yields the \$n\$-th \$s\$-gonal number:

$$P(n, s) = \frac{n^2(s-2) - n(s-4)}{2}$$

which is given in the Wikipedia page here.

Input

Two positive integers, \$s\$ and \$x\$, with the condition \$s \ge 3\$. You may input these integers in the most natural representation in your language (decimal, unary, Church numerals, integer-valued floating point numbers etc.).

Output

A list of integers, \$L\$, with a maximum length of \$s\$, where the sum of \$L\$ is equal to \$x\$ and all integers in \$L\$ are \$s\$-gonal integers. Again, the integers may be outputted in the natural representation in your language, with any distinct, consistent separator (so non-decimal character(s) for decimal output, a character different from that used for unary output etc.)

Rules

The inputs or outputs will never exceed the integer limit for your language
\$L\$ does not have to be ordered
In case of multiple possible outputs, any or all are acceptable
This is code-golf so the shortest code in bytes wins

Test cases

   x,  s => L
   1,  s => 1
   2,  s => 1, 1
   5,  6 => 1, 1, 1, 1, 1
  17,  3 => 1, 6, 10
  17,  4 => 1, 16
  17,  5 => 5, 12
  36,  3 => 36
  43,  6 => 15, 28
 879, 17 => 17, 48, 155, 231, 428
4856, 23 => 130, 448, 955, 1398, 1925

Haskell, 78 80 77 bytes

We compute the cartesian product of the first \$n\$ s-gonal numbers, and then find the first entry that sums to \$n\$.

s#n=[x|x<-mapM(map(\n->s*(n^2-n)`div`2+n*(2-n)))([0..n]<$[1..s]),sum x==n]!!0

Try it online!


Uni-Dimensional String Golf Introduction

You have to simulate playing golf over an input string that represents the green. The 2-character substring () represents the hole, and is guaranteed to appear only once in the string.

This is a sample green:

ABCDEFGHIJKLM()NOPQRSTUVWXYZ

The simulation consists of outputting the characters that the ball falls on after a series of hits that are also passed to your function.

Each hit is represented by a positive integer indicating how many characters the ball will travel, relative to previous position.

Example

The following input results in the output G(o).

7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ

Explanation

The input represents two hits of length 7. The output is a string of characters, showing the intermediate positions of the ball. The ball starts to the left of the string, and travels 7 characters to the right, landing on the G. As such, that character is the first part of the output.

Then the ball is hit for the second time, and it lands in the hole. In this case, the hole is output with the ball inside, like this: (o).

9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

The output represents the characters the ball has landed on in the same order as in the string.

Notes

The width of the hole is 2. If the ball lands on either parenthesis, the hole is hit.
The direction of the hit is always towards the hole, so when the ball ends up to the right of the hole, the next hit will cause the ball to move to the left (and vice versa).
The ball might not reach the hole, in which case the position of the ball after the last hit must be output next to the character (in the direction of the hole) the ball is on at the end of the hits. The hole is still included in the output.

  example:

28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
B12()Z

  First 28 hit lands on Z at the right of the hole , next 26 hit is as
  always thowards the hole (left) and lands on B. No more hits left so
  the distance to the hole (12 characters) is shown next to B

If the hits cause the ball to leave the green at some point, discard all remaining hits, and prepend ^ if the ball exits the green to the left, and append $ if the ball leaves the green via the right side.
There might be hits after the putt, in which case those should be discarded, and the hole in the output should not contain an o, but an X.

Test cases

15,10,3,TOURING()MACHINE
I(o)N

7,HOLEIN()NE
(o)

9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
G(o)

28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
B12()Z

2,25,26,27,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
AB()Y13Z

1,1,6,SH()RT
SH()$

2,4,6,TOO()HARD
^O()H

4,8,1,3,3,3,3,3,TAKEIT()ASITCOMES
E(X)IT

You have to write a program or function wich accepts a series of positive numbres representing the hits and a [A..Z] string with one hole "()" representig the green. Make clear if your input format is different form 7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ

This is code golf, so the submission with the smallest amount of bytes per language wins!

Python 2 - 380 bytes

Try it online

Shorter answer, thanks to @ovs. This one requires list of integers and string as input. Example: 28,26,"ABCDEFGHIJKLM()NOPQRSTUVWXYZ".
Check edits for older version, that accepts plain string like "28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ"

I=input()
c=-1
G=I[c]
I=map(int,I[:c])
u=r=""
L=[u]*len(G)
H=len(G.split('(')[0])
L[H:H+1]='()'
d=1
s=0
f="".join
for h in I:
 s+=1;c+=h*d;d=(1,-1)[H-c<0];T=f(L)
 if H<=c<H+2:u='o'if s==len(I)else'X';break
 if c<0:r="^"+T;break
 if c>len(G):r=T+"$";break
 L[c]=G[c]
else:
 m=H-c if~d else c-H-1
 if d>0:c+=1
 L=L[:c]+[str(m)]+L[c:];r=f(L)
print r or("%s)"%u).join(f(L).split(')'))

Explanation (for older version, but approach is same):

I=input().split(',')             # split input
G=I[-1]                          # last element - Green
I=map(int,I[:-1])                # convert all other (hits) to int
L=[""]*len(G)                    # empty list of same length as Green, used to ouput
H=len(G.split('(')[0])           # index of hole
L[H]='('                         # hole is always printed
L[H+1]=')'
c=-1                             # current index on Green
d=1                              # direction of hit
u=r=""                           # strings for output and in-hole marker (X)/(o)
s=0                              # number of current hit
for h in I:
    s+=1
    c+=h*d                       # move current by hit * direction
    d=(1,-1)[H-c<0]              # calculate new direction
    T="".join(L)                 # used to remove code duplication
    if H<=c<H+2:                 # if in hole
        u='o'if s==len(I)else'X' # check whether it is last hit or not
        break
    if c<0:                      # if out of Green on the left
        r="^"+T                  # add '^' and join all visited indices
        break
    if c>len(G):                 # if out of Green on the right
        r=T+"$"                  # add '&' after join all visited indices
        break
    L[c]=G[c]                    # mark visited index
else:                            # rare occasion of for-else construction - executes if never break out of loop
                                 # which means, that we are out of hits and not in hole
    m=H-c if~d else c-H-1        # calculate distance to hole
    if d>0:
        c+=1
    L=L[:c]+[str(m)]+L[c:]       # expand L list with distance
    r="".join(L)                 # join list
t="".join(L).split(')')
if r:
    print r                      # ouput r in all cases exept in-hole
else:
    print t[0]+"%s)"%u+t[1]      # output for in-hole cases


Find the next number in the pattern Write a program, that takes 5 numbers as input and outputs the next number in the pattern.

Heres a text file with 1835 test patterns, containing 6 numbers separated by commas each line. Using the first 5 numbers calculate the 6th number and then check if it matches. You must get all the test cases correct.

There are 3 types of patterns:

xn = xn-1+k
xn = xn-1*k
xn = xn-1^2

The first x value and k were chosen randomly between a set range to create the pattern sample file.

This is code-golf, lowest number of bytes to get all of the test cases correct wins.

Python 2: 55 bytes

f=lambda a,b,c,d,e:e+c-d*2and e*e/d**(d*d==e*c)or e*2-d

We check for the three cases as follows:

Check for arithmetic sequence: If e+c==d+d, output e+e-d
Check for geometric sequence: If e*c==d*d, output e*e/d
Otherwise, squared sequence: Output e*e.

Case 3 is used as the else-case to avoid the more-lengthy checking for successive squaring.

Case 1 is checked first, with Boolean short-circuiting to avoid checking Case 2 after a success, as this causes an error when d=0. There's a test case of all zeroes, so we can't cheat this by picking another position in place of d.

Afterwards, we can treat both Cases 2 and 3, since there's no risk of a divide-by-0 error. Noting that the choices are similar (e*e vs e*e/d), we combine them with an arithmetic expression by dividing by either d**1 for Case 3 or d**0 for Case 2. Although this division produces an integer value, we must use Python 2 (or //) to avoid float errors that case the largest-output test case to fail.

Thanks to @Will for inspiration on the code structure and a very-helpful test framework.


Enumerating N-Dimensional Vectors Given a positive integer k > 1 and a non-negative integer i, generate a k-tuple (or k-dimensional vector) of non-negative integers. For every k, the map from ℕ to ℕk, must be bijective. That is, every input i should produce a different tuple, and every possible tuple must be produced by some input i.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may use any convenient, unambiguous, flat list format for the output.

Your solution should impose no artificial limits on k and i but you may assume that they fit into your language's native integer size. At the very least, you must support values up to 255, though, even your native integer size is smaller than that.

For any 1 < k < 32, i < 231, your code should produce a result in a matter of seconds (of course, if your answer doesn't support i that large due to the previous rule, the limit is adjusted accordingly). This should be no issue: it's possible to solve this challenge such that it works up to 2128 in a few seconds, but the limit is there to avoid answers which actually iterate from 0 to i to find the result.

Please include in your answer a description of your chosen mapping and a justification for why it's bijective (this doesn't need to be a formal proof).

This is code golf, the shortest answer (in bytes) wins.

Related Challenges

Generate a pair of integers from a non-negative one
Output a list of all rational numbers

Pyth, 15 12 bytes

ms+0_%Q>_zdQ

Test suite

My transformation is similar to one of xnor's, but in base 10. It works by unzipping the input into k separate numbers:

n = 21003034
k = 3

21003034
 1  3  4    134
2  0  3     203
  0  0        0

The numbers are ordered in decreasing position of the rightmost digit, so that all orderings of any group of numbers are possible.

The way the code works is we reverse the input, then slice off the last 0, 1, ... k-1 digits, then take every kth digit, reverse again, stick a 0 at the begining, and convert to int.


Sort with a neural network The previous neural net golfing challenges (this and that) inspired me to pose a new challenge:

The challenge

Find the smallest feedforward neural network such that, given any 4-dimensional input vector \$(a,b,c,d)\$ with integer entries in \$[-10,10]\$, the network outputs \$\textrm{sort}(a,b,c,d)\$ with a coordinate-wise error strictly smaller than \$0.5\$.

Admissibility

For this challenge, a feedforward neural network is defined as a composition of layers. A layer is a function \$L\colon\mathbf{R}^n\to\mathbf{R}^m\$ that is specified by a matrix \$A\in\mathbf{R}^{m\times n}\$ of weights, a vector \$b\in\mathbf{R}^m\$ of biases, and an activation function \$f\colon\mathbf{R}\to\mathbf{R}\$ that is applied coordinate-wise:

$$ L(x) := f(Ax+b), \qquad x\in\mathbf{R}^n. $$

Since activation functions can be tuned for any given task, we need to restrict the class of activation functions to keep this challenge interesting. The following activation functions are permitted:

Identity. \$f(t)=t\$
ReLU. \$f(t)=\operatorname{max}(t,0)\$
Softplus. \$f(t)=\ln(e^t+1)\$
Hyperbolic tangent. \$f(t)=\tanh(t)\$
Sigmoid. \$f(t)=\frac{e^t}{e^t+1}\$

Overall, an admissible neural net takes the form \$L_k\circ L_{k-1}\circ\cdots \circ L_2\circ L_1\$ for some \$k\$, where each layer \$L_i\$ is specified by weights \$A_i\$, biases \$b_i\$, and an activation function \$f_i\$ from the above list. For example, the following neural net is admissible (while it doesn't satisfy the performance goal of this challenge, it may be a useful gadget):

$$\left[\begin{array}{c}\min(a,b)\\\max(a,b)\end{array}\right]=\left[\begin{array}{rrrr}1&-1&-\frac{1}{2}&-\frac{1}{2}\\1&-1&\frac{1}{2}&\frac{1}{2}\end{array}\right]\mathrm{ReLU}\left[\begin{array}{rr}\frac{1}{2}&\frac{1}{2}\\-\frac{1}{2}&-\frac{1}{2}\\1&-1\\-1&1\end{array}\right]\left[\begin{array}{c}a\\b\end{array}\right]$$

This example exhibits two layers. Both layers have zero bias. The first layer uses ReLU activation, while the second uses identity activation.

Scoring

Your score is the total number of nonzero weights and biases.

(E.g., the above example has a score of 16 since the bias vectors are zero.)

Octave, 96 88 87 84 76 54 50 weights & biases

This 6-layer neural net is essentially a 3-step sorting network built from a very simple min/max  network as a component. It is basically the example network from wikipedia as shown below, with a small modification: The first two comparisons are done in parallel. To bypass negative numbers though the ReLU, we just add 100 first, and then subtract 100 again at the end.

So this should just be considered as a baseline as it is a naive implementation. It does however sort all possible numbers that do not have a too large magnitude perfectly. (We can adjust the range by replacing 100 with another number.)

Try it online!

max/min-component

There is a (considerably less elegant way more elegant now, thanks @xnor!) way to find the minimum and maximum of two numbers using less parameters:

$$\begin{align} \min &= a - ReLU(a-b) \\ \max &= b + ReLU(a-b) \end{align}$$

This means we have to use a lot less weights and biases.

Thanks @Joel for pointing out that it is sufficient to make all numbers positive in the first step and reversing it in the last one, which makes -8 weights. Thanks @xnor for pointing out an even shorter max/min method which makes -22 weights! Thanks @DustinG.Mixon for the tip of combining certain matrices which result in another -4 weights!

function z = net(u)
a1 = [100;100;0;100;100;0];
A1 = [1 0 0 0;0 0 1 0;1 0 -1 0;0 1 0 0;0 0 0 1;0 1 0 -1];
B1 = [1 0 -1 0 0 0;0 0 0 1 0 -1;0 1 1 0 0 0;0 0 0 0 1 1];
A2 = [1 0 0 0;0 1 0 0;1 -1 0 0;0 0 1 0;0 0 0 1;0 0 1 -1];
A3 = [1 0 -1 0 0 0;0 1 1 0 0 0;0 0 0 1 0 -1;0 1 1 -1 0 1;0 0 0 0 1 1];
B3 = [1 0 0 0 0;0 1 0 -1 0;0 0 1 1 0;0 0 0 0 1];
b3 = -[100;100;100;100];
relu = @(x)x .* (x>0);
id = @(x)x;
v = relu(A1 * u + a1);
w = id(B1 * v) ;
x = relu(A2 * w);
y = relu(A3 * x);
z = id(B3 * y + b3);
% disp(nnz(a1)+nnz(A1)+nnz(B1)+nnz(A2)+nnz(A3)+nnz(B3)+nnz(b3)); %uncomment to count the total number of weights
end

Try it online!


Injection from two strings to one string Challenge

Write a program that applies an injective function which takes an ordered pair of strings as input and one string as output. In other words, each input must map to a unique output.

Specifics

The input may be any two strings of arbitrary length, but will consist only of printable ASCII characters (codes \$[32, 126]\$).
Similarly, the output string has no length restriction, but it must consist only of printable ASCII characters.
If your language can't handle arbitrary-length strings, the program may merely work theoretically for strings of any size.
The mapping from inputs to outputs should be consistent between executions of the program. Otherwise, the mapping you use is completely up to you, as long as it is an injection.
The input is ordered. If the two input strings are different, they should produce a different output than if they were swapped. \$s \neq t \implies f(s, t) \neq f(t, s)\$
Not every string needs to be a possible output.
The shortest answer in each language wins!

Test cases

The following inputs should all result in different outputs. To avoid confusion, strings are surrounded by guillemets («») and separated by single spaces.

«hello» «world»
«lelho» «drowl»
«diffe» «_rent»
«notth» «esame»

«Code» «Golf»
«Co» «deGolf»
«CodeGolf» «»

«» «»
«» « »
« » «»
« » «  »
«  » « »

«abc", » «def»
«abc» «, "def»
«abc' » «'def»
«abc'» « 'def»

«\» «"»
«\\» «\"»

brainfuck, 30 29 27 23 bytes

,[-[+.>]-[>+<---]>.-.,]

Try it online!

Inputs are separated by a 0x01 byte.

This turns ["foo", "bar"] into fUToUToUTUTbUTaUTrUT. To recover the original two strings, take groups of 3 characters, find the one where the second letter isn't U, and split there.


Draw a trololologram Your challenge here is to draw a trololologram.

You can choose any language.

The answer with more upvotes and the one that exploits more holes wins.

Rules for valid answers:

You can't use any network resource or external file (except the source-code)
You can't post someone else's answer
You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).
You can't store the image in any database.
You can't simply print/echo 'trololologram' (case insensitive)
Explain your answers and what holes you exploited.
The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background. The rendered version can't "be invisible" or "hidden behind the screen" or similar.
The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count).

The main goal is to twist the rules and bend them at your own will and stil render a trololologram on screen.

Have fun!

For this challenge, I am posting five programs in this answer, all in Java.
Program 1

You can't simply print/echo 'trololologram' (case insensitive)

public class JustPrintIt {
    public static void main(String[] args) {
        System.out.println("trololologram");
    }
}

Program 2

You can't [...] pre-rendered ([...] and any form of ascii art).

public class AsciiArt {
    public static void main(String[] args) {
        System.out.println(
            "    ########################       \n" +
            "  ##                        #      \n" +
            "  #                          #     \n" +
            " #                            ##   \n" +
            " #                              #  \n" +
            " #                              #  \n" +
            "  #                            #   \n" +
            "  #                          ##    \n" +
            "  #                     #####      \n" +
            "  #            #########           \n" +
            "   ############                    \n");
    }
}

Program 3

You can't use any network resource or external file (except the source-code)
You can't have it stored in any image format or pre-rendered (including base64 data:// uri's [...]).
You can't store the image in any database.
The code must render the trolologram on the screen [...].
The image must show in the screen. It can't output the code to a file [...].

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class DownloadAndStore {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        String url = "http://img171.imageshack.us/img171/8555/trolologramw400.jpg";
        BufferedImage im = ImageIO.read(new URL(url));
        ImageIO.write(im, "png", new File("trolologram.png"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(im, "png", baos);

        String d = "data://" + new String(Base64.getEncoder().encode(baos.toByteArray()));
        Class.forName("com.mysql.jdbc.Driver");
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) {
            try (PreparedStatement ps = con.prepareStatement("CREATE DATABASE troll")) {
                ps.executeUpdate();
            } catch (SQLException e) {
                if (!e.getMessage().contains("database exists")) throw e;
            }
            try (PreparedStatement ps = con.prepareStatement("CREATE TABLE troll.image (imagedata text not null)")) {
                ps.executeUpdate();
            } catch (SQLException e) {
                if (!e.getMessage().contains("already exists")) throw e;
            }
            try (PreparedStatement ps = con.prepareStatement("INSERT INTO troll.image (imagedata) VALUES (?)")) {
                ps.setString(1, d);
                ps.executeUpdate();
            }
        }
    }
}

Program 4

Your challenge here is to draw a trololologram.
You can't use any network resource or external file (except the source-code)
You can't post someone else's answer
You can't have it stored in any image format or pre-rendered [...].
[...] (minimum size of 90x90) and must be with a black border and white background. [...].

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ShowTheAnswerOfSomebodyElse {
    public static void main(String[] args) throws IOException {

        // See this: http://codegolf.stackexchange.com/a/20085/3755
        String url = "http://placehold.it/99/png&text=Hello+world!";

        BufferedImage im = ImageIO.read(new URL(url));
        BufferedImage im2 = new BufferedImage(89, 89, BufferedImage.TYPE_INT_ARGB);
        im2.createGraphics().drawImage(im, 0, 0, null);
        SwingUtilities.invokeLater(() -> createAndShowGUI(im2));
    }

    private static void createAndShowGUI(BufferedImage im) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent panel = new JComponent() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMinimumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public void paintComponent(Graphics g) {
                g.drawImage(im, 0, 0, null);
            }
        };
        frame.add(panel);

        frame.pack();
        frame.setVisible(true);
    }
}

Program 5

You can't use any network resource or external file (except the source-code)
You can't have it stored in any image format or pre-rendered [...].
The code must render the trolologram on the screen [...] and must be with a black border and white background. The rendered version can't "be invisible" or [...].
The image must show in the screen. [...].

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ShowTheTrolologramOnScreenButNot {
    public static void main(String[] args) throws IOException {
        String url = "http://img171.imageshack.us/img171/8555/trolologramw400.jpg";
        BufferedImage im = ImageIO.read(new URL(url));
        for (int i = 0; i < im.getHeight(); i++) {
            for (int j = 0; j < im.getWidth(); j++) {
                int rgb = im.getRGB(j, i);
                int r = 255 - (rgb >> 16 & 0xff);
                int g = 255 - (rgb >> 8 & 0xff);
                int b = 255 - rgb & 0xff;
                im.setRGB(j, i, 0xFF000000 + (r << 16) + (g << 8) + b);
            }
        }
        SwingUtilities.invokeLater(() -> createAndShowGUI(im));
    }

    private static void createAndShowGUI(BufferedImage im) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent panel = new JComponent() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMinimumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public void paintComponent(Graphics g) {
                g.drawImage(im, 0, 0, null);
            }
        };
        frame.add(panel);
        panel.setVisible(false); // :)

        frame.pack();
        frame.setVisible(true);
    }
}

And finally...

Explain your answers and what holes you exploited.

So here it is:

The answer with more upvotes and the one that exploits more holes wins.

There is hole in this: you did not said that it must be a valid answer to be accepted!


Fewest (distinct) characters for Turing Completeness Summary:
For any given language, what is the smallest amount of unique characters for your language to be Turing-Complete?
Challenge:
For any language of your choice, find the smallest subset of characters that allows your language to be Turing-Complete. You may reuse your set of characters as many times as you want.

Examples:

JavaScript: +!()[] (http://www.jsfuck.com)

Brainfuck: +<>[] (assumes a wrapping cell size)

Python 2: ()+1cehrx (made from scripts like exec(chr(1+1+1)+chr(1)))

Scoring:
This challenge is scored in characters, not bytes.  For example, The scores for the examples are 6, 5, and 9.

Notes:

This challenge differentiates from others in the sense that you only your language to be Turing-Complete (not necessarily being able to use every feature of the language.)

Although you can, please do not post answers without reducing the characters used. Example: Brainfuck with 8 characters (since every other character is a comment by default.)

You MUST provide at least a brief explanation as to why your subset is Turing-Complete.

Haskell, 4 chars

()=;

With ()= we are able to define S, K and I. The definitions must be separated by either ; or a NL.

We define (==) as S (the second line shows a more readable version):

((=====)==(======))(=======)=(=====)(=======)((======)(=======))
( a     == b      ) c       = a      c       ( b       c       )

(===) as K:

(=====)===(======)=(=====)
 a     === b      = a

and (====) as I:

(====)(=====)=(=====)
(====) a     = a

Luckily (==), (===), (====), etc. are valid function/parameter names.

As @ais523 points out, SKI isn't enough in a strongly typed language like Haskell, so we need to add a fixpoint combinator (=====):

(=====)(======)=(======)((=====)(======))
(=====) f      = f      ((=====) f      )


0-1 Maximal Phase Counter Consider an array of bits, say

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0

We call a contiguous subarray of length ≥ 5 a phase if at least 85% of the bits are the same and the first/last bits are both equal to the majority bit. Furthermore, we call a phase maximal if it is not a strict subarray of some other phase.

Here are the maximal phases of the above example:

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
      -------------
                    -------------
                        -------------

As you can see, there are 3 maximal phases. On the other hand, this

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
                        ---------

is not a maximal phase as it is a strict subarray of at least one other phase.

The challenge

Input is a sequence of ≥ 5 bits via STDIN, command line or function argument. The bits may come in as a string or an array.

You are to output a single integer, the number of maximal phases for the array, either printed via STDOUT or returned from a function.

Scoring

This is code-golf so the program in the fewest bytes wins.

Test cases

0 1 0 1 0 -> 0
0 0 0 0 0 -> 1
0 0 0 0 1 0 1 1 1 1 -> 0
0 0 0 0 0 1 0 1 1 1 1 1 -> 2
1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 -> 1
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 -> 2
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 -> 1
0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 0 -> 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 1 0 1 -> 4
0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 -> 5

Here's the explanation for the last case:

0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0
---------------------------
      -------------------------
                            -----------------
                                -----------------
                                              -------------

Fun fact: This challenge came about from a data mining problem with the goal of detecting change in temporal data.

Python 2, 149 bytes

a=input()
l=len(a)
n=p=0
for i in range(l):
 for j in range(l-1,i+3,-1):
  if(j>p)>(.15<sum(a[i:j+1])/(j+1.-i)+a[i]+a[j]<2.85):n+=1;p=j;break
print n

The first loop scans across the array from left to right. Each bit, indexed by i, is checked to see if it could be the first bit in a maximal phase.

This is done by the inner loop, which scans from right to left. If the subarray between i and j is a phase, we increase the counter and move on. Otherwise, we keep going until the subarray becomes too small or j reaches the end of the previous maximal phase.

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
i ->                               <- j

Example:

$ python phase.py
[1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
3


Old C Code Transmogrifier* *What is a transmogrifier?
In the C programming language, there are formations called digraphs and trigraphs that are two and three characters sequences that evaluate to less common characters. For example, you can use ??- if your keyboard doesn't have ~.
Given text, replace all instances of the following digraphs and trigraphs (left side) with the correct, shorter, golfed character (right side).
??=  #
??/  \
??'  ^
??(  [
??)  ]
??!  |
??<  {
??>  }
??-  ~
<:   [
:>   ]
<%   {
%>   }
%:   #

Source
Input
Input is ASCII text. Trailing newline allowed. Does not need to be valid C code.
Output
Output is the same text, with all instances of the above digraphs and trigraphs replaced with the shortened version, evaluated left to right. Trailing newline allowed. Does not need to be valid C code.
Test Cases
=> separates input and output.
if (true ??!??! false) { => if (true || false) {

??-arr.indexOf(n) => ~arr.indexOf(n)

function f(??) { console.log('test??'); } => function f(] { console.log('test^); }

/* comment :> :) *??/ => /* comment ] :) *\

%:What am I doing??!!??` => `#What am I doing|!??

??(??)??(??) <:-- not a palindrome => [][] [-- not a palindrome

?????????? => ??????????

int f(int??(??) a) ??< return a??(0??)??'a??(1??) + "??/n"; ??> => int f(int[] a) { return a[0]^a[1] + "\n"; }

??<:>??<% => {]{%

<:> => [>

<::> => []

:>> => ]>

#\^[]|{}~ => #\^[]|{}~

: > => : >

??=%: => ##

C, 206 205 bytes

(-1 thanks to ceilingcat)

The newlines are just here for readability.

c,d,q;f(char*s){for(char*S,*T,*t=s;c-63?q=0:q++,d=c<<8|*s,*s?
q>1&&(T=index(S="=/'()!<>-",*s))?t-=2,*s="#\\^[]|{}~"[T-S]:
d>*s&&(T=strstr(S=">:<>%<:%",&d))&&(c="][ }{ # "[T-S])&1?--t,*s=c:0:
0,*t++=c=*s++;);}

Modifies s in place. Tested with GCC and clang on Fedora Workstation, x86, in 32-bit and 64-bit mode.

C is not exactly the best language for golfing here.


Help me figure out what TeX I can use! On TeX.SE the Help Centre says that the following is on topic:

Formats like LaTeX, ConTeXt and plain TeX
Engines like pdfTeX, LuaTeX and XeTeX
Distributions like TeX Live, MiKTeX, and MacTeX
Related software and tools, BibTeX, MakeIndex, Lyx, etc.

I wanted you to write a program to tell me whether my TeX is in the on-topic types of TeX.

An explicit list of the valid TeX-s is as follows:

MetaPost
PostScript
MetaFUN
TeX
LaTeX
LuaLaTeX
LuaTeX
ConTeXt
BibTeX
pdfTeX
Lyx
MakeIndex
TeX Live
XeLaTeX
XeTeX
MacTeX
MiKTeX

Rules

You may use any language.
This is code-golf, to the shortest answer wins.
If you use Regex, you can just match correct ones.
You only need to match one at a time: no

Lyx
BibTeX
You must check with capitalization listed here.

Tests

TeX -> True/1/<match>
pTeX -> False/0/<not-match>
ConTeXt -> True/1/<match>
context -> False/0/<not-match>
MetaFun -> False/0/<not-match>
MetaFUN -> True/1/<match>

P.S. Bonus points for an on-topic TeX answer!

JavaScript Regex, 99 101 99 97 + 1 for g flag = 98 bytes

^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$

Test it here. Type into the Text box. Alternatively, test it here.

var j = $("#dos");
var text;
function abc(){
  text = $('#uno').val();
  j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!");
};

<input id='uno' />

<button id='tres' onclick="javascript:abc()">Test!</button>

<input id='dos' />

Test all cases:

var j = $("#dos");
var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"];
function abc(e){
  j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n");
};

function def(){
  tests.forEach(abc);
}

<button id='tres' onclick="javascript:def()">Test!</button>

<textarea rows=50 cols=200 id='dos'>
</textarea>


Crown hundred crownty crown I noticed a certain game had a peculiar life counter, which instead of stopping at 999, gained a new digit – the next number was crown hundred or 00. After 99 came crown hundred crownty (0) and the last number, after 9, was crown hundred crownty crown or , which would be 1110 in decimal.

Your task is to write a program or a function that outputs this counter.

Given an integer from the range [0,1110] (inclusive on both ends), output a three character string where

every character is from the list 0123456789
the crown () can only appear as the leftmost character or when there's a crown to the left of it
when this number is read as a decimal number but with the crown counting as 10, you get back the original number

Test cases

   0 → "000"
  15 → "015"
 179 → "179"
 999 → "999"
1000 → "00"
1097 → "97"
1100 → "0"
1108 → "8"
1110 → ""

You may use any non-decimal character instead of the crown. To encourage pretty printing, the crown character (UTF8 byte sequence "\240\159\145\145") counts as one byte instead of four. Your program doesn't have to work for numbers outside the valid range.

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

JavaScript (Node.js), 50 bytes

f=(n,p=1e3)=>n<p?(n+p+'').slice(1):'#'+f(n-p,p/10)

Try it online!

TIO was based on Arnauld's answer. Show  as #.


Data theft via remote desktop connection A software vendor friend of mine wants to clamp down the development environment by limiting access to the software's source code to only Remote Desktop access, disallowing any digital communication including clipboard, printer, network shares, and internet access from that environment.

The reasoning is that they are contractually obligated to provide a company-standard-issue development environment to an overseas partner and there is a concern of theft.

I want to convince them that this is a futile effort and vain burden on good developers since the otherwise unsupervised access to the source code will provide ample opportunity to steal the data.  No matter how many firewall rules and group policies are in place, one channel remains that cannot be removed - the screen.

Assuming the development environment has Visual Studio 2010, data compression software, and other common development environment tools, what is the slickest way to use the Remote Desktop screen to steal the data?  Keep in mind any limitations of the screen refresh rate.

Candidate approach: a monochrome bitmap of the screen can hold over 200KB of an archive of such source code.  Without error correction, that's just over 500 screenshots of monochrome data for 100MB of compressed source code.  The data must be encoded, decoded, and I'm entirely too lazy to save 500 screenshots into paint.  Existing free software can be involved, but not installed on the environment.

Other ideas?  Implementations?

Use FRAPS to capture video from your local machine.  Then you can flash stuff up on the remote desktop at up to the frame rate and it will all get recorded to a local video file.

I don't see a way to sync to exactly to the frame rate, so you'll need some error detection to make sure you're not getting data mid-draw.  Here's a simple scheme using text and a python script:

framerate = 30  # fps of viewer
numlines = 24   # lines of text you can see at once
import sys,time,md5,base64
lineno = 0
while 1:
  lines = 'chunk starting at line %d\n' % lineno
  for i in xrange(numlines - 2):
    lines += sys.stdin.readline()
    lineno += 1
  print 'md5:', base64.encodestring(md5.new(lines).digest()),
  print lines
  time.sleep(1.0/framerate)

Run this script in the RemoteDesktop window and pipe in the text you wish to capture.  When it is done, OCR each frame of your FRAPS output (that's the hard part, I'm not sure what you'd use for that).  Throw away any duplicate frames and frames where the md5 isn't right.

You probably want to base64 encode your input, as OCR doesn't do well with nonprinting characters like tabs and spaces.


Syllabify English words - kind of You're tasked with writing a program that syllabifies words in a string of text, by separating them with a hyphen. That would be a lot of work, so you want to skip some parts, mainly because you don't want to have a table of the pronunciations required for perfect algorithm. You also want to make it as short (and thus unreadable and unmaintainable) as possible as a revenge for being given this assignment.
You have two choices:

Write a program that takes the string from STDIN and outputs the result to STDOUT.
Write a function that takes the string as a single parameter, and returns the result.

Specification

In this case, string means any string-like construct in your language of choice (byte arrays, character arrays, strings...).
Vowels are a, e, i, o, u
The string given has 1 <= n <= 10 words, where each has a length between 1 - 30 characters, inclusive.. Your output should be those words hyphenated.
All letters are lowercase and words are always separated with spaces. Thus, the input consists of characters [a-z ]
Apply rules in order of importance.
When a word is divided, start again with the right half of the word.

Rules for syllabification, in order of importance
Two consecutive same vowels count as one (ie. feet has only one vowel, but beat and finding have two). Every syllable has exactly one vowel, thus there is one syllable for each vowel.

If the whole word has only four letters, return it unchanged. (skip this for the rest of the word)
If the word has only one vowel, return the word unchanged.
If the word has two consecutive vowels, divide between them (ie. diaspora -> di-as-po-ra)
When two or more consonants come between two vowels (same or different), divide after the first consonant (ie. sis-ter) unless the consonant part is ck, in which case divide the word after it. (ie. nickel -> nick-el)
When a y comes between two vowels, divide the word after it (e.g. paying -> pay-ing).
When one consonant comes between two vowels (same or different), divide before the consonant (ie. dra-gon)
Return the word unchanged if no division could be done.

I chose these rules, because they can be applied recursively without problems and require no pronunciation tables. Thus, they are not accurate, and for example rule #5 is often not correct. In general case though, it is.
Example
In:  hello world
Out: hel-lo world

In:  have a nice day
Out: have a nice day

In:  pour some nickel and xenon there
Out: pour some nick-el and xe-non the-re

Lua, 292

Lua might not have been the best language to do this in, but it works. It pretty much flows like the question asked. The rules are mainly in order with some optimizations: #2 is skipped (it isn't needed unless there is a one vowel word with "ck" at the beginning), and the ck and y rules are gone through before the rest of #4 and #6, which are combined. Since some vowels in the word need to be captured twice (after one hyphen and before another), that search is performed twice.

i=io.read()v="([aeiou])"for s in i:gfind("%l+ ?")do
if s:len()~=4 then
s=s:gsub(v..v,function(x,y)if x==y then return x..y;end;return x.."-"..y;end)s=s:gsub("ck"..v,"ck-%1")s=s:gsub(v.."y"..v,"%1y-%2")for b=1,2 do
s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4")end
end
io.write(s)end

Ungolfed

function checkEquals(x,y)
    if x==y then
        return x..y
    end
    return x.."-"..y
end
i=io.read()
v="([aeiou])"
for s in i:gfind("%l+ ?") do
    if s:len()~=4 then
        s=s:gsub(v..v,checkEquals)
        s=s:gsub("ck"..v,"ck-%1")
        s=s:gsub(v.."y"..v,"%1y-%2")
        for b=1,2 do
            s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4")
        end
    end
    io.write(s)
end

Test it here: http://ideone.com/g57TzA


Convert xxd output to shellcode Taking some output from xxd and turning it into usable shellcode by hand is no fun, so your job is to automate the process.

Rules

Your submission can be a function, lambda, script, or any reasonable equivalent of those. You may print the result, or if your submission is a function/lambda then you may also return it.

You program must take three arguments, the first being a string containing the output of xxd, ran with no arguments other than a filename, like this: xxd some_file. Here's an example of what the the first argument will look like:

00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Your need to take that middle section containing the bytes (the first 8 columns after the :) and turn it into shellcode by removing any whitespace, then putting a \x before each byte.

Here's what the output should be for the input above (ignoring any other arguments):

\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59

You can assume the first argument will always be a valid xxd output, ran with no arguments other than the filename.

Your output should also be a string where the backslashes are literal backslashes, not used as escape characters. So when I say "\x65", I'm not talking about the byte 0x65, or even the letter "A". In code, it would be the string "\x65".

The second argument specifies where in the xxd output the shellcode should start, and the third specifies where it should end. If the third argument is -1, it will end at the end of xxd output. The second and third argument will also always be non negative, except for when the third is -1

Here are some test cases:

Argument 1:

00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: 7, Argument 3: e (these are both strings representing hexadecimal numbers)

Output: \xc9\xcd\x80\xeb\x16\x5b\x31\xc0

Argument 1:

00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: 0, Argument 3: 2e

Output: \x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e

Argument 1:

00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: a, Argument 3: -1

Output: \xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59

The code with the least bytes wins. The winner will be announced in seven days, on August 15, 2016 (but submissions after then are still appreciated).

Update

Congrats to @Adnan to winning the challenge!

Bash + coreutils + xxd, 73 71 69 bytes

printf \\x%s `xxd -r|xxd -p -s0x$1 -l$[(e=1+0x$2)?e-0x$1:-1]|fold -2`

Expects the hexdump on STDIN and start/end as command-line arguments.

This prints some warnings to STDERR, which is allowed by default.