Quine Relay! Quine Relay!

A quine relay of order \$n\$ is a series of programs \$P_1\dots P_n\$ in distinct languages such that each program \$P_i\$ outputs \$P_{i+1}\$ and \$P_n\$ outputs \$P_1\$.

For example, a 2-quine relay can be seen here:

Ruby → Perl 6:

This Ruby program:

$><<"print ("
p (DATA.read*2).chars.map(&:ord)
$><<".map: &chr).join"

__END__
$><<"print ("
p (DATA.read*2).chars.map(&:ord)
$><<".map: &chr).join"

__END__

outputs this Perl 6 program:

print ([36, 62, 60, 60, 34, 112, 114, 105, 110, 116, 32, 40, 34, 10, 112, 32, 40, 68, 65, 84, 65, 46, 114, 101, 97, 100, 42, 50, 41, 46, 99, 104, 97, 114, 115, 46, 109, 97, 112, 40, 38, 58, 111, 114, 100, 41, 10, 36, 62, 60, 60, 34, 46, 109, 97, 112, 58, 32, 38, 99, 104, 114, 41, 46, 106, 111, 105, 110, 34, 10, 10, 95, 95, 69, 78, 68, 95, 95, 10, 36, 62, 60, 60, 34, 112, 114, 105, 110, 116, 32, 40, 34, 10, 112, 32, 40, 68, 65, 84, 65, 46, 114, 101, 97, 100, 42, 50, 41, 46, 99, 104, 97, 114, 115, 46, 109, 97, 112, 40, 38, 58, 111, 114, 100, 41, 10, 36, 62, 60, 60, 34, 46, 109, 97, 112, 58, 32, 38, 99, 104, 114, 41, 46, 106, 111, 105, 110, 34, 10, 10, 95, 95, 69, 78, 68, 95, 95, 10]
.map: &chr).join

which in turn outputs the original Ruby program.

The challenge

The first answer will be an order \$1\$ quine relay: a normal quine. It can be in any language.

The next answer will choose a different language and create an order \$2\$ quine relay using those two languages.

And so on. The \$k\$-th answer will create an order \$k\$ quine relay using the previous \$k - 1\$ languages and a new, different language.

Winning

If, after 2 weeks, no more answers have been added, the winner is the person who answered with the highest-order quine relay.

More rules

No person may answer twice in a row.
No person may answer within an hour of their most recent post.
Languages which differ by version are considered distinct. Thus, Python 2 and Python 3 can both be part of the chain.
Languages which differ by compiler or interpreter are not considered distinct. So, Python 3 (Cython) and Python 3 are considered interchangeable but not distinct.
Each answer may order the languages in any way. If the third answer has an order of Ruby → Perl 6 → JavaScript, you are not restricted to appending a language to the end. If you were adding Java to the mix, then you could write JavaScript → Ruby → Java → Perl 6 if you so desired.

Format for answers

  n. Language1 → Language2 → … → Languagen

  Language1

language 1 code

  Language2

language 2 code

  Language3

language 3 code

  …

  Languagen

language n code

Feel free to add explanations anywhere in your answers.

3. JavaScript → Python 2 → Foo

JavaScript

Classic JS quine. This is a full program which outputs to console:

(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()

Try it online!

Python 2

Python code basically prints out the JS code with quotes:

print('"(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()"')

Try it online!

Foo

Foo code is JS code with quotes:

"(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()"

Try it online!


Mutually fill in the blanks Given an input of two strings with sequences of underscores representing
corresponding words, output the sentences with the "blanks" filled in.

The best way to describe this challenge is by example. Here is an example
input:

programming _____________ and code golf
programming puzzles ______ code ____

And here is the corresponding output:

programming ___puzzles___ and code golf
programming puzzles _and__ code golf

For the purposes of this challenge, a "word" is defined as a sequence of one or
more lowercase letters, and a "blank" is defined as one or more underscores
(the input will always contain only lowercase letters, spaces, and
underscores). Words and blanks in the input strings are separated by single
spaces, and the sum of the number of words and blanks in the sentences will
always be equal.

The objective of the challenge is to fill all of the blanks with the correct
words, which are the words that occupy the same index in the other string
when split by spaces.

The word must be centered in the blank, as shown with the word "puzzles" in
the example above—an equal number of underscores remain on either side.
If the word cannot be exactly centered, the extra underscore may go either on
the left or the right (ex. the word "and" in the example above).
There will always be enough underscores for the word to fit, but there may be
exactly as many as the length of the word (ex. the word "golf" in the example
above).
There will never be a blank in the same position in both strings.

Input/output may be any of the following (input/output do not necessarily have
to be via the same method):

single string separated by any character
that is not alphabetic, a space, or an underscore (ex. newline or comma
separated string)
an array/list/etc. of two strings
two function/command line arguments (input only)

Since this is code-golf, the shortest code in bytes will win.

The example above can be used as a test case. Here is a larger test case
(second string in output may vary slightly due to different centering behavior):

lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum
lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum

lorem ipsum dolor _sit_ amet __consectetur__ adipiscing elit mauris dapibus tincidunt ____________metus____________ accumsan fringilla proin vulputate viverra lorem fermentum dictum
lorem ipsum dolor_ sit _amet__ consectetur __adipiscing___ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem _________fermentum__________ dictum

Retina, 102 100 93 88 bytes

Byte count assumes ISO 8859-1 encoding.

$
!¶$`
m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+))
$2
(([a-z])+)(?<-2>_)*(_*)\3|!\D+
$3$1$3

The strings will are separated by a linefeed. If there is an odd number of underscores left, the extraneous one will be after the word.

Try it online!

Explanation

I guess this is the "duplicate-append-lookback-match-add-centre approach", or something close...

$
!¶$`

We start by duplicating the input (separated with a ! and a linefeed). The purpose of this is that we can then process both lines by fetching words from the next line (instead of having to treat the second line separately).

m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+))
$2

This prepends the correct word to each gap. We start by counting the current word position with the lookbehind (?<=^(\w+ )*) (the position is stored as the depth of group 1). Then the lookahead a) ensures that we're at the beginning of a gap by matching _, then skips to the next line with .*¶, matches the correct number of words with (?<-1>\w+ )* to get to the right position, and then matches the word found there with (\w+) into group 2.

(([a-z])+)(?<-2>_)*(_*)\3|!\D+
$3$1$3

This stage does three things:

It removes the underscores corresponding to each word length. This is done by counting the word length into group 2 with ([a-z])+ and then matching that many underscores (which are never written back).
It shifts the word to the centre of the gap by capturing half of the remaining underscores with (_*)\3 and writing $3$1$3 back.
It removes the duplicated input by matching !\D+ and replacing it with nothing.


Make the Matrix Digital Rain using the shortest amount of code Rules:

Any language you choose (Standard Libraries).
Output displayed in Terminal or Windows Command Processor or any other way you prefer.(width buffer = 80)
ASCII Characters are enough. (may add Unicode)
Shouldn't fill up the entire screen at start-up (Should look like a rain, duh!).
Colors gets bonus points (+5).
Effects : Random characters, different fall sizes, regenerates periodically.

Points: (update)

+32 points to start with.
-1 point for every byte (not chars) in the code after the **1024***th* byte.
Points could reach zero and negative.
Note: Languages using multibyte characters should count bytes not characters.
+5 for every new effect. (not posted by others)
+15 for any of these effects:

Wind(blows characters to the side)
Number Matching(user input, eg:90210):
Number is randomly located within the matrix

Sound
Encrypted msg(user input):
Characters represent a secret encrypted message
Galaga mode:
Fires ^ to destroy characters

Scoreboard:

┌-----┬------------┬------------┬-------------┬---------------┬--------------┐
| pos |    name    |    type    |    bytes    |    effects    |    points  ^ |
|-----|------------|------------|-------------|---------------|--------------|
|1    |nitro2k01   |QBasic      |913          |Colours        |+57           |
|     |            |            |             |Colour Fade    |              |
|     |            |            |             |Sound (+15)    |              |
|-----|------------|------------|-------------|---------------|--------------|
|2    |squeamish   |HTML, Java- |1024         |Colours        |+47           |
|     |ossifrage   |Script, CSS |             |Transition     |              |
|     |            |            |             |Size Variation |              |
|-----|------------|------------|-------------|---------------|--------------|
|3    |manatwork   |Ruby        |374          |Colours        |+47           |
|     |            |            |             |Actual Words   |              |
|     |            |            |             |Character -    |              |
|     |            |            |             |      Disperse |              |
|-----|------------|------------|-------------|---------------|--------------|
|4    |plg         |Bash        |1024         |Colours        |+42           |
|     |            |            |             |Random Pause   |              |
|-----|------------|------------|-------------|---------------|--------------|
|5    |Timtech     |TI-84 calc  |120          |Umbrella       |+42           |
|     |            |            |             |Run Inside     |              |
|-----|------------|------------|-------------|---------------|--------------|
|6    |Samuel Cook |JavaScript  |830          |Colours        |+42           |
|     |            |            |             |Transition     |              |
└-----┴------------┴------------┴-------------┴---------------┴--------------┘

Note : Scoreboard will/could be updated by anyone after posting a valid answer. Do not exceed top ten positions. Add more effects to your code and beat your own score! Clearing initial screen, cleanup, bugs, third party libraries etc. would not count towards the points
Remember to include details about no. of bytes used and the name of language or program.

  Neo: What are you trying to tell me? That I can dodge bullets?

  Morpheus: No, Neo. I'm trying to tell you that when you're ready, you
  won't have to.

HTML, Javascript and CSS: 1024 bytes, 47 points

Features:

Uses Unicode characters (don't think this scores any points though)
Trails fade from bright to dark green while they are being drawn (*)
Trails also fade from dark green to black after the drawing has finished (*)
Random text size in each trail (*)
Trails are randomly repositioned and resized each time they are drawn

(*) I'll claim +5 points for each of these, but let me know if you disagree :-)
Demo:
http://ruletheweb.co.uk/matrix.html
Source code:
Exactly 1024 bytes. It's a bit ugly, I'm afraid.
<head><style>*{margin:0;padding:0;line-height:1;overflow:hidden;}div{width:1em;position:absolute;}</style><script>
w=window;n=w.innerWidth;m=w.innerHeight;d=document;q="px";function z(a,b){return Math.floor(Math.random()*(b-a)+a)}f=" 0123456789";for(i=0;i<45;i++)f+=String.fromCharCode(i+65393);function g(){for(i=0;i<90;i++){r=d.createElement("div");for(j=z(20,50);j;j--){x=d.createElement("pre");y=d.createTextNode(f[z(0,56)]);x.appendChild(y);x.style.opacity=0;r.appendChild(x)}r.id="r"+i;r.t=z(-99,0);with(r.style){left=z(0,n)+q;top=z(-m,0)+q;fontSize=z(10,25)+q}d.body.appendChild(r);setInterval("u("+i+")",z(60,120))}}function u(j){e=d.getElementById("r"+j);c=e.childNodes;t=e.t+1;if((v=t-c.length-50)>0){if((e.style.opacity=1-v/32)==0){for(f in c)if(c[f].style)c[f].style.opacity=0;with(e.style){left=z(0,n)+q;top=z(-m/2,m/2)+q;opacity=1}t=-50}}e.t=t;if(t<0||t>c.length+12)return;for(f=t;f&&f>t-12;f--){s=1-(t-f)/16;if(f<c.length&&c[f].style){c[f].style.opacity=s;}}}
</script><body text=#0f0 bgcolor=#000 onload=g()>


Spiral Permutation Sequence We can roll up the natural numbers in a rectangular spiral:

 17--16--15--14--13
  |               |
 18   5---4---3  12
  |   |       |   |
 19   6   1---2  11
  |   |           |
 20   7---8---9--10
  |
 21--22--23--24--25

But now that we have them on a rectangular grid we can unwind the spiral in a different order, e.g. going clockwise, starting north:

 17  16--15--14--13
  |   |           |
 18   5   4---3  12
  |   |   |   |   |
 19   6   1   2  11
  |   |       |   |
 20   7---8---9  10
  |               |
 21--22--23--24--25

The resulting sequence is clearly a permutation of the natural numbers:

1, 4, 3, 2, 9, 8, 7, 6, 5, 16, 15, 14, 13, 12, 11, 10, 25, 24, 23, 22, 21, 20, 19, 18, 17, ...

Your task is to compute this sequence. (OEIS A020703, but spoiler warning: it contains another interesting definition and several formulae that you might want to figure out yourself.)

Fun fact: all 8 possible unwinding orders have their own OEIS entry.

The Challenge

Given a positive integer n, return the nth element of the above sequence.

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.

Standard code-golf rules apply.

Test Cases

1       1
2       4
3       3
4       2
5       9
6       8
7       7
8       6
9       5
100     82
111     111
633     669
1000    986
5000    4942
9802    10000
10000   9802

For a complete list up to and including n = 11131 see the b-file on OEIS.

Japt, 20 19 16 bytes
V=U¬c)²-V *2-U+2

Test it online!
Based on the observation that

 F(N) = ceil(N^.5) * (ceil(N^.5)-1) - N + 2

Or, rather, that

 F(N) = the first square greater than or equal to N, minus its square root, minus N, plus 2.

I don't know if this explanation is on the OEIS page, as I haven't looked at it yet.


A Multipurpose Quine I personally love quines, but they all seem to be so... static. So why not create a quine that can do more.

Challenge

The challenge here is to create a quine that without any sort of input is a normal quine. Then if it receives a different input, it outputs a different quine in a different language. (basically like a polyglot, but it doesn't have to return to the original source code)

EX:

Starting program:

James

Given no input or 0 as input, the code above outputs:

James

Given 1 as input, the code outputs:

Kendra

Given 2 as input, the code outputs:

Alexander

And so on...

Requirements

Like with any other quine challenge, no examining source code directly!

Inputs are either nothing, or a positive integer.

Each quine must not be less than \$\lceil(n/4)\rceil\$ levenshtein distance from all other quines, where \$n\$ is the length of the original quine. Look at this example program:

Bobb  //original quine
Bobby //output (when given an input), we'll name him bobby
Bob   //output (when given a different input), we'll name him bob

The above is not valid, because Bob is only one levenshtein distance from Bobb.

However, this one is valid:

Bob      //original quine
Alice    //bob's output when given 1 as input
Geronimo //bob's output when given 2 as an input

Because \$ ceil(len(bob)/4)=1 \$, and Alice, Geronimo, and Bob are all at more than one levenshtein distance away from each other.

There has to be a minimum of one extra quine to be outputted.

The quine must output itself when given no input or 0, and output a different quine if given a different integer input!

Points

Points are based on this equation (courtesy of Luis felipe De jesus Munoz)
$${\frac{100}{\text{bytes}} \cdot 2^{\text{extra quines} - 1}}$$

(100 divided by the number of bytes multiplied by 2 to the power of every different quine that your program can output, minus one to make sure the program at least outputs one different quine)

Befunge-98, ><>, Fission, Wumpus, Cardinal, Gol><> and Beeswax, Score: \$(100/103)*2^6 = 62.136\$
"[0#34o+]l2:)&o@.0*74#!,!?:o#_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

Try it online!
Verification!
When given an input of 0, this program produces itself. When given a different number, it produces the quines in the format
"[0#34o+]l2:)&o@.0*74#!,!?:o1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 #_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

Where the 1s are the input number. Since there are 26 copies of the 1, this makes each quine distinct at least \$bytes/4\$ Levenshtein distance. The quines are entirely interchangeable as no program actually cares about the number part. I might see if I can add some more 2D languages to this (I'm thinking Cardinal Gol><> next) Don't have one in mind right now.


J, 15 bytes

p:@i.+/ .*i.!<:

Explanation:

Basically the same as my Mathematica answer.

p:@i.+/ .*i.!<:
          i.!<:    binomial coefficients
p:@i.              first n primes
     +/ .*         dot product


Implement a whitespace golfer Some two-dimensional esolangs, such as Forked, and some non-esolangs, such as Python, can sometimes require spaces before lines of code. This isn't very golfy. Also, I'm lazy and writing a 2d lang that needs lots of spaces before code. Your task is to write a tool that makes these languages golfier.

Of course, this will not be perfect; it cannot be used, for instance, when a number is the first character on a line of source. However, it will generally be useful.

Challenge

You will write a program or function that either...

...takes one argument, a filename or a string, or...
...reads from standard input.

Your program will act like cat, except:

If the first character on any line is a number, your code will print x spaces, where x is that number.
Otherwise, it will simply be printed.
As will every other character in the input.

Test cases

Input:

foo bar foo bar
1foo bar foo bar foo bar
2foo bar foo bar foo bar foo bar

Output:

foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

Input:

--------v
8|
8|
80
8,
7&

Output:

--------v
        |
        |
        0
        ,
       &

Input:

foo bar
bar foo
foo bar

Output:

foo bar
bar foo
foo bar

Input:

0123456789
1234567890
2345678901
3456789012
4567890123

Output:

123456789
 234567890
  345678901
   456789012
    567890123

Rules

Output must be exactly as input, except for lines where the first character is a number.
Your program cannot append/prepend anything to the file, except one trailing newline if you desire.
Your program may make no assumptions about the input. It may contain empty lines, no numbers, Unicode characters, whatever.
If a number with more than one digit starts a line (e.g. 523abcdefg), only the first digit (in the example, 5) should turn into spaces.

Winner

Shortest code in each language wins. Have fun and good luck!

Retina, 9 bytes

m`^\d
$*

Try it online! Note: Trailing space on last line.


Show the Top Five Comment Scores on a SE Post A Stack Exchange script determines which five comments on questions or answers are initially seen on the main page of sites through the number of upvotes on them; the five comments with the highest number of votes are displayed. Your task is to recreate this behavior.

Write a full program or function taking input through STDIN, command-line args, or function arguments and prints or returns the top five comment scores. Input will be an array of integers representing the number of upvotes on the comments of some post. For instance, an input of

0, 2, 5, 4, 0, 1, 0

means that the first comment has no votes, the second one has two votes, the third has five, the fourth had four, etc. The order of the comment scores should remain the same in the output.

If the input contains five or fewer comment scores, then the output should contain nothing more than the ones given. If two or more comment scores are the same, the first score(s) should be displayed. You may assume that the input array will contain at least one comment score.

The numbers in the output should be easily distinguished (so 02541 for case 1 is invalid). Otherwise there are no restrictions on output format; the numbers may be separated by a space or newline, or they may be in list format, etc.

Test cases:

[0, 2, 5, 4, 0, 1, 0] -> [0, 2, 5, 4, 1]
[2, 1, 1, 5, 3, 6] -> [2, 1, 5, 3, 6]
[0, 4, 5] -> [0, 4, 5]
[1, 1, 5, 1, 1, 5] -> [1, 1, 5, 1, 5]
[0, 2, 0, 0, 0, 0, 0, 0] -> [0, 2, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0] -> [0, 0, 0, 0, 1]
[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> [5, 8, 7, 6, 7]
[6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2] -> [6, 69, 22, 37, 5]

The last example was taken from this Stack Overflow question.

If possible, please provide a link in your post where your submission can be run online.

This is code golf, so the shortest code in bytes wins. Good luck!

Jelly, 6 bytes

NỤḣ5Ṣị

Try it online! or verify all test cases at once.

How it works

NỤḣ5Ṣị    Main link. Input: A (list)

N         Negate (multiply by -1) all elements of A.
 Ụ        Grade the result up.
          This consists in sorting the indices of A by their negated values.
          The first n indices will correspond to the n highest vote counts,
          tie-broken by order of appearance.
  ḣ5      Discard all but the first five items.
    Ṣ     Sort those indices.
          This is to preserve the comments' natural order.
     ị    Retrieve the elements of A at those indices.


Spoonerise words... in Finnish This challenge is based on, and contains test cases from, a programming course I took at Aalto University. The material is used with permission.
Two and a half years ago there was a challenge about spoonerisms in English. However, in Finnish spoonerisms are much more complicated.
Spoonerisms in Finnish
In Finnish, the vowels are aeiouyäö and the consonants are bcdfghjklmnpqrstvwxz. (å is technically part of Finnish, but is not considered here.)
The most basic spoonerisms only take the first vowel of each word, and any consonants preceding them, and exchange the parts:
henri kontinen -> konri hentinen
tarja halonen -> harja talonen
frakki kontti -> kokki frantti
ovi kello -> kevi ollo
Long vowels
Some words contain two of the same consecutive vowel. In those cases, the vowel pair must be swapped with the other word's first vowel, shortening or lengthening vowels to keep the length same.
haamu kontti -> koomu hantti
kisko kaappi -> kasko kiippi
In the case of two different consecutive vowels this does not apply:
hauva kontti -> kouva hantti
puoskari kontti -> kooskari puntti
Three or more of the same consecutive letter will not appear in the input.
Vowel harmony
Finnish has this lovely thing called vowel harmony. Basically, it means that the back vowels aou and front vowels äöy should not appear in the same word.
When swapping front or back vowels into a word, all vowels of the other kind in the rest of the word should be changed to match the new beginning of the word (a <-> ä, o <-> ö, u <-> y):
köyhä kontti -> kouha köntti
hauva läähättää -> läyvä haahattaa
e and i are neutral and may appear with all other letters; swapping them into a word must not cause changes to the rest of the word.
Special cases
Vowel harmony does not apply to some words, including many loan words and compound words. These cases are not required to be handled "correctly".
Challenge
Given two words, output the words spoonerised.
The input words will only contain the characters a-z and äö. You may choose to use uppercase or lowercase, but your choice must be consistent between both words and input/output.
I/O may be done in any convenient format. (Words should be considered strings or arrays of characters.)
This is code-golf, so the shortest solution in bytes wins.
Test cases

henri kontinen -> konri hentinen
tarja halonen -> harja talonen
frakki kontti -> kokki frantti
ovi kello -> kevi ollo
haamu kontti -> koomu hantti
hauva kontti -> kouva hantti
puoskari kontti -> kooskari puntti
köyhä kontti -> kouha köntti
hauva läähättää -> läyvä haahattaa
frakki stressi -> strekki frassi
äyskäri kontti -> kouskari äntti
hattu sfääri -> sfätty haari
ovi silmä -> sivi olma
haamu prätkä -> präämy hatka
puoskari sfääri -> sfäöskäri puuri
puoskari äyskäri -> äöskäri puuskari
uimapuku hajoa -> haimapuku ujoa
ihme baletti -> bahme iletti
uhka lima -> lihka uma
osuma makkara -> masuma okkara
makkara fakta -> fakkara makta
lapsi laiva -> lapsi laiva
firma hajoa -> harma fijoa
dimensio bitti -> bimensio ditti
flamingo joustava -> jomingo flaustava
globaali latomo -> labaali glotomo
trilogia fakta -> falogia trikta
printti maksa -> mantti priksa
riisi bitti -> biisi ritti
sini riisi -> rini siisi
aarre nyrkki -> nyyrre arkki
laavu laki -> laavu laki
kliininen parveke -> paaninen klirveke
priimus kahvi -> kaamus prihvi
spriinen lasta -> laanen sprista
kliimaksi mammona -> maamaksi klimmona
hylky hupsu -> hulku hypsy
kehys fiksu -> fihys keksu
levy huhu -> huvu lehu
tiheys guru -> guheus tiru
nyrkki heiluri -> herkki nyilyri
latomo hajoa -> hatomo lajoa
prisma lehti -> lesma prihti
viina baletti -> baana viletti

JavaScript (ES6), 196 175 bytes
Takes the words as two strings in currying syntax (a)(b). Returns an array of two arrays of characters.
a=>b=>[(e=/(.*?)([eiäaöoyu])(\2?)(.*)/,g=(a,[,c,v])=>[...c+v+(a[3]&&v)+a[4]].map(c=>(j=e.search(v),i=e.search(c))>9&j>9?e[i&~1|j&1]:c))(a=e.exec(a),b=e.exec(b),e+=e),g(b,a)]

Try it online!
How?
Each input word is passed through the regular expression e, which has 4 capturing groups:
e = /(.*?)([eiäaöoyu])(\2?)(.*)/    1: leading consonants (or empty)
     [ 1 ][     2    ][ 3 ][ 4]     2: first vowel
                                    3: doubled first vowel (or empty)
                                    4: all remaining characters

The helper function g() takes all capturing groups of the word to be updated as a[ ] and the first and second capturing groups of the other word as c and v.
We apply basic spoonerism and take care of long vowels with:
c + v + (a[3] && v) + a[4]

To apply vowel harmony, we first coerce the regular expression e to a string by adding it to itself, which gives:
e = "/(.*?)([eiäaöoyu])(\2?)(.*)//(.*?)([eiäaöoyu])(\2?)(.*)/"
     ^^^^^^^^^^^^^^^^
     0123456789ABCDEF (position as hexa)

Vowels that need to be harmonized have a position greater than 9 in the resulting string. Furthermore, the expression was arranged in such a way that front vowels äöy are located at even positions, while back vowels aou are located at odd positions, next to their counterparts.
Hence the following translation formula which is applied to each character c of the output word:
(j = e.search(v), i = e.search(c)) > 9 & j > 9 ? e[i & ~1 | j & 1] : c


Ambassadors and Translators Two ambassadors at a UN conference want to speak to each other, but unfortunately each one only speaks one language- and they're not the same language. Fortunately, they have access to several translators, who each understand and speak a few languages. Your task is to determine the shortest chain of translators (since you want as little to be lost in translation as possible) that allows the two ambassadors to speak with each other.

Coding

Input: two languages as 2-letter lowercase strings (each ambassador's language) and a list of lists of languages (one list per available translator)

You may alternatively take in integers instead of 2-letter codes.

Output: A sequence of translators either by index or value that is any one of the shortest chains of translators that allows the two ambassadors to communicate. If there is no valid chain of translators, the behavior is undefined. (You may crash, output any arbitrary value, or indicate an error)

A valid chain of translators is one where the first translator speaks one ambassador's language, the second and subsequent translators share at least one language with the previous translator, and the last translator speaks the other ambassador's language.

Examples

Using zero-based indexing:

es, en, [
    [es, en]
] ==> [0]

en, en, [] ==> []

en, jp, [
    [en, zh, ko, de],
    [jp, ko]
] ==> [0, 1]

es, ru, [
    [gu, en, py],
    [po, py, ru],
    [po, es]
] ==> [2, 1]

fr, gu, [
    [it, fr, de, es, po, jp],
    [en, ru, zh, ko],
    [jp, th, en],
    [th, gu]
] ==> [0, 2, 3]

fr, ru, [
    [fr, en],
    [en, ko, jp],
    [en, ru]
] ==> [0, 2]

de, jp, [
    [en, fr],
    [ko, jp, zh],
    [fr, po],
    [es, ko, zh],
    [de, en, th],
    [en, es],
    [de, fr]
] ==> [4, 5, 3, 1]

Rules and Assumptions

Standard IO rules (use any convenient I/O format) and banned loopholes apply.
You may assume that speaking and understanding languages is perfectly symmetric and that all possible translations between languages are equally efficient.
There is no concept of "close enough" languages. It is not good enough to use Portuguese on one end where Spanish is required, for instance.
If there are multiple shortest translator chains, any one of them will do.
If the ambassadors happen to speak the same language, the translator list should be empty
Which of the ambassadors is the first one doesn't matter; the translator list can be forward or reverse.
Ambassadors only speak one language for the sake of this challenge
Translators speak at least two languages
The 2-letter language codes do not need to correspond with real languages
You may assume there is a valid sequence of translators
If outputting the sequence by value, include the full set of available languages, not just the relevant ones.

Happy Golfing!

Jelly, 19 17 bytes

ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ

Try it online!

A dyadic link taking the list of translators as the left argument and list of ambassadors (each double-wrapped in a list) as the right argument. Returns a list of translators, each of which is a list of the languages they speak.

Thanks to @KevinCruijssen for saving 2 bytes!

Explanation

ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ | A dyadic link taking a list of translators as left argument and a list of ambassadors (double-wrapped in lists) as right argument

ŒP                | Power set of translators
  Œ!€             | Permutations of each
     Ẏ            | Tighten, i.e. create a single list of all permutations of any length
      j@€         | Join the ambassadors with each set of translators
            $Ƈ    | Filter those where:
           Ạ      |   all
         fƝ       |   the neighbouring pairs have at least one in common
              Ḣ   | Take the first
               Ḋ  | Drop the first ambassador from the start
                Ṗ | Drop the second ambassador from the end


Mutation-hardened quine Your task is to make a program that prints out its own source.

"Hey, we already have this challenge, and tons of variations of it! Why are you making another one?" you may ask, but this one is going to be one of the most difficult ones (hopefully, anyway).

Your quine must be "mutation-hardened", which means the quine, even when any one of its characters are duplicated in place, must output the source code of the original program.

For example, if you have a quine (the following example is not written in any language, it's just pseudocode):

abcd

These programs must all output abcd:

aabcd
abbcd
abccd
abcdd

(In each of those programs, a, b, c and d are each duplicated in-place, which means the duplicated character was placed directly after the original character.)

Rules:

Standard quine rules apply.
A multi-byte character counts as one character, and the character is not "split" into its respective bytes when duplicated.

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

><>, 56 bytes

^
.
+
8
f
0
o
a
o
~
:
?
~
:
?
:
-
*
4
8
:
^
^
}
*
3
d
'

Try it online! or verify all mutations.

How the original program works (outdated)

The interpreter starts in cell (0, 0). ^ sets the direction to upwards, so the instruction pointer (IP) wraps around to cell (0, 20).

' activates string mode: until the next ' is encountered, all characters under the IP are pushed on the stack. The same ' is found again after wrapping around, so we push

d3*}^^:84*=?~oao0f.^

The IP lands at (0, 19), still going upwards. Executing d3*} pushes 13 = 0xd, then 3, multiplies both values (39 / single quote), then rotates the stack to the right. This leaves the stack as follows.

'd3*}^^:84*=?~oao0f.^

The next two instructions (^) do nothing at this point.

:84*= duplicates the top of the stack, pushes 8 and 4, multiplies them (32 / space), then tests the duplicated character for equality with space. For the unaltered program, this will always push 0.

? skips the next instruction if the top of the stack is falsy. For the original program, it always is, so ~ is always skipped.

oao pops and prints the top of the stack, pushes a 10 / linefeed, then pops and prints linefeed.

Finally 0f. jumps to cell (0, 15) (the bottommost ^), starting over with the next character on the stack.

Once the stack is empty, the entire source code has been printed. : will fail and the program exits.

How the mutated programs work (outdated)

Duplicating any non-linefeed character will only extend the program horizontally. Since the program is executed vertically, these extra instructions will never get executed.

Duplicating any linefeed before the bottomost ^ will shift cells (0, 14) and (0, 15) to (0, 15) and (0, 16). 0f. will now jump to the cell before the bottommost ^, which is also a ^, so the program is not affected by the shift.

Finally, any duplicated linefeed character will also alter the string. Short lines are padded with spaces, so a 32 / space will be inserted at the linefeed's position. 84*= will push 1 for space, so ? doesn't skip the next instruction. In this case, ~ pops and discards space, so the following o will print the character above space instead.


Reliably Broken Sort Given a list of positive integers that contains at least 3 distinct entries, output a permutation of that list that isn't sorted in ascending or descending order.
Examples
1,2,3 -> 2,1,3 or 3,1,2 or 1,3,2 or 2,3,1
1,2,3,3 -> 2,1,3,3 or 3,1,2,3 or 1,3,2,3 etc..

Thanks @Arnauld and @NoOneIsHere for the title!

JavaScript (ES6), 39 34 bytes
a=>[a.sort((x,y)=>x-y).pop(),...a]

Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both sort and pop modify the original array).

Test it

o.innerText=(f=

a=>[a.sort((x,y)=>x-y).pop(),...a]

)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split`,`)
<input id=i><pre id=o>


Expand shorthand increasing integer sequences Given an input of a list of numbers in the format of a shorthand increasing
integer sequence, output the sequence in full.

Shorthand increasing integer sequence format works by finding every number n
with fewer digits than the number preceding it, m. With d as the number of
digits in n, the last d digits of m are replaced with all the digits of
n. Here's an example input:

123 45 6 7 89 200

Applying the replacement rule, we first turn 45 into 145 because 45 < 123:

123 145 6 7 89 200

Repeatedly applying the same rule, this becomes:

123 145 146 7 89 200
123 145 146 147 89 200
123 145 146 147 189 200

The sequence is now sorted (there are no numbers for which the rule applies),
so this is the final output.

You may assume that

shorthand notation is always used when possible. For example, input will be
12 3, never 12 13.
numbers will never decrease while remaining the same number of digits. For
example, input will never be 333 222.
applying the shorthand rule will never result in a number that is still less
than the previous number in the sequence. For example, input will never be
123 12.
numbers will always be positive integers and never contain leading 0s (if
using a string format).
the full, expanded sequence will never contain duplicate numbers. (However,
the shorthand sequence might; ex. 10 1 20 1 -> 10 11 20 21.)
there will be at least one number in the input.

Input and output can be either lists/arrays of numbers/strings or a single
string with elements separated by any non-digit.

Since this is code-golf, the shortest code in bytes will win.

Test cases, with input and output on alternating lines:

1 2 3 10 1 2 20 5 100 200 10 3 5 26 9 99 999 9999
1 2 3 10 11 12 20 25 100 200 210 213 215 226 229 299 999 9999
223 1184 334 441 5 927 2073 589 3022 82 390 5 9
223 1184 1334 1441 1445 1927 2073 2589 3022 3082 3390 3395 3399
5 10 5 20 5 30 5 40 5 50 5
5 10 15 20 25 30 35 40 45 50 55
7 8 9 70 80 90 700 800 900 7000 8000 9000
7 8 9 70 80 90 700 800 900 7000 8000 9000
42
42

Jelly, 7 bytes

DUṛ"\UḌ

Try it online! or verify all test cases.

How it works

DUṛ"\UḌ  Main link. Input: A (list of integers)

D        Convert each integer to a list of its base 10 digits.
 U       Reverse each digit list.
    \    Do a cumulative reduce, applying the dyadic link to the left:
   "       For each pair of corresponding digits:
  ṛ          Select the right one.
           Vectorization leaves digits that do not have a counterpart untouched.
     U   Reverse the resulting digit arrays.
      Ḍ  Convert from base 10 to integer.


Python 2, 1033 1007 924 879 829 787 713 699 692 691 688 687 672 670 664 659 654 648 643 642 630 625 623 620 570 560 554 545 518 514 513 510 505 492 476 454 451 443 bytes
6 bytes saved thanks to Riley
6 bytes saved thanks to Adnan

Since this question is over a year old and still has no answers I thought I'd give it a try.
n,i,o,u="\nI _";R=lambda x:range(1,x-1)
b=open(i).read()
s=b.split(n)
z=max(map(len,s))+3
a=[list(i+x.ljust(z,i))for x in[i]+s+[i]]
for x in R(len(a))*len(b):
 A=a[x];B=a[x+1];C=a[x-1]
 for y in R(z):
    D=A[y-1:y+2];k=B[y];j=A[y+1]
    if(i in[C[y],k]+D+(k==u)*B[y-1:y+2]or"V"==j)&(A[y]==o):A[y]=i
    if"|"==A[y]==C[y]:A[y]={i:"|",j:">",A[y-1]:"<"}[i]
    if[u]*3==D:A[y],B[y]={i:u+k,C[y]:"^"+k,k:" V"}[i]
print n.join(`y`[2::5]for y in a).replace(i,o)

Try it online!
The program reads the table a file named I and prints the table with its chairs to std::out.  I was not sure about a bunch of the edge cases so I took my best judgement (whatever took the least effort) but it seems to pass all the test cases.  Some of the outputs don't match exactly but they all have the same number of chairs.
Explanation
The first line pretty simply sets up some definitions that will save us bytes in the future:
(I will unpack these macros for readability in future lines)
n,i,o="\nI ";R=lambda x:range(1,x-1)

Then we will open a file named I because we already have a variable that is short for that so it saves a few bytes.
b=open("I").read().split("\n")

We split along newlines to create a list of strings (The rows of the image)
s=b.split(n)

I then find the length of the longest line so that I can pad all lines to that length.  (I also add 3 because we need a bit of additional padding)
 z=max(map(len,s))+3

Then we perform the actual padding and create a border of I characters around the edge.  This is because we will need to tell the difference between the inside and the outside of the shape later on.  We will also change the data type from a list of strings to a list of list of characters (length 1 strings).
a=[list("I"+x.ljust(z,"I"))for x in["I"]+s+["I"]]

The next line is just another byte saving definition.
(I will also unpack this one)
B=R(len(a))

Now we want to spread I characters to everywhere outside of the shape.  We can do this with a pseudo-cellular automaton.  Each I will spread to any adjacent   characters.  We could loop until the automaton stabilizes however this cannot take more iterations than there are characters so we just loop through every character in b (the original input)
for _ in b:

For each iteration we want to pass over every character in the 2D list (excluding the outermost padding)
 for x in range(1,len(a)-1):
    A=a[x]  #<--Another definition I will fill in for clarity
    for y in range(1,z-1):

For each position we run the following code:
if("I" in[a[x+1][y],a[x-1][y]]+a[x][y-1:y+2])&(a[x][y]==" "):a[x][y]=" "

Lets break this down.
We have an if with two conditions separated by a & (bitwise and)
The first one simply checks if there is an I in any of the adjacent cells and the second one just checks if the current cell is a " ".  If we pass those conditions we set the current cell to be an I.

Now that we have determined the outside and inside of the shape we can start to place the chairs around the table.
Once again we loop through all of the cells (and set some more shorthands)
for x in range(1,len(a)-1):
 A=a[x]
 for y in range(1,z-1):
        k=a[x+1][y]

Now here's my favorite part.  If you have trudged through my boring, mostly definition based, golfing so far I am going to reward you with a nice tidbit of clever golfing (if I do say so myself).
A little background in python:
In Python if you attempt to assign an dictionary key twice it asigns the latter one.  For example
>>> {1:"a",1:"b"}[1]
'b'

We will abuse this property to assign the current cell to a particular character.
The first condition is
if["_"]*3==a[x][y-1:y+2]:a[x][y],a[x+1][y]={"I":"_"+a[x+1][y],a[x-1][y]:"^ ",a[x+1][y]:" V"}["I"]

If the cell is in the middle of an edge of 3 _ characters we will reassign the current cell and the cell below it.  We will assign it to the result of indexing an overloaded dictionary by I.  We first set our default with the pair "I":"_"+a[x+1][y] this means if there is no change we will assign the two cells back to their original values.  Next we add the pair a[x-1][y]:"^ ".  This wont do anything (important) unless the cell above the current one (a[x-1][y]) is filled with an I.  If it has an I in it it will override the default telling us to place a chair at the current cell.  Next we move on to the cell below the current cell if that cell is I we again override to place an upwards facing chair below the current spot.
The next condition is a tad simpler
if"|"==a[x][y]==a[x-1][y]:a[x][y]={"I":"|",A[y+1]:">",A[y-1]:"<"}["I"]

We check if the current cell and the cell above it are both |.  If so we set up a dictionary.
The first pair in the dictionary "I":"|" sets the default.  Since we are going to access the key I if I does not get reassigned it will default back to | (the character it already is) and do nothing.
We the add the two keys A[y+1]:">",A[y-1]:"<" If either of the two cells to the left and right are I then it will reassign the current cell to a chair pointing in the direction of the outside.

Now we just have to output.  However we can't just print,  there are a couple of housekeeping things we have to do first.  We have to convert back to a string and remove all of the Is we created.  This is done in one line.
print "\n".join(`y`[2::5]for y in a).replace("I"," ")


Calculate the inverse of factorial Write the shortest code that will take any real number greater than 1 as input and will output its positive inverse factorial. In other words, it answers the question "what number factorial is equal to this number?". Use the Gamma function to extend the definition for factorial to any real number as described here.

For example:

input=6 output=3
input=10 output=3.390077654

because 3! = 6 and 3.390077654! = 10

Rules

It is forbidden to use built in factorial functions or gamma functions, or functions that rely on these functions.
The program should be able to calculate it to 5 decimal digits, with the theoretical ability to calculate it to any precision (It should contain a number that can be made arbitrary big or small to get arbitrary precision)
Any language is allowed, shortest code in characters wins.

I made a working example here. Have a look.

Javascript (116)

Black magics here ! Gives a result in few milliseconds.
Only elementary math functions used : ln, pow, exponential

x=9;n=prompt(M=Math);for(i=1e4;i--;)x+=(n/M.exp(-x)/M.pow(x,x-.5)/2.5066/(1+1/12/x+1/288/x/x)-1)/M.log(x);alert(x-1)

Too bad LaTeX is not supported on codegolf but basically, I coded a newton solver for f(y)=gamma(y)-n=0 and x=y-1 (because x! is gamma(x+1)) and approximations for gamma and digamma functions.

Gamma approximation is Stirling approximation
Digamma approximation use Euler Maclaurin formula
The digamma function is the derivative of gamma function divided by gamma function : f'(y)=gamma(y)*digamma(y)

Ungolfed :

n = parseInt(prompt());
x = 9; //first guess, whatever but not too high (<500 seems good)

//10000 iterations
for(i=0;i<10000;i++) {

  //approximation for digamma
  d=Math.log(x);

  //approximation for gamma
  g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x);

  //uncomment if more precision is needed
  //d=Math.log(x)-1/2/x-1/12/x/x+120/x/x/x/x;
  //g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x-139/51840/x/x/x);

  //classic newton, gamma derivative is gamma*digamma
  x-=(g-n)/(g*d);
}

alert(x-1);

Test cases :

10 => 3.390062988090518
120 => 4.99999939151027
720 => 6.00000187248195
40320 => 8.000003557030217
3628800 => 10.000003941731514


MATL, 16 bytes

&n:w:!XlX:GX:1XQ

Try it online! Or verify all test cases.

Explanation

Consider, as an example, the input

2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

The code &n:w:!Xl builds the column vector [1; 2; 3; 4] and the row vector [1 2 3 4 5]. Then Xl computes the minimum element-wise with broadcast, which gives the matrix

1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4

X: linearizes this matrix (in column-major order) into the column vector [1; 1; 1; 1; 1; 2; 2; ... ; 4]. This vector and the linearized input matrix, obtained as GX:, are passed as inputs to the accumarray(... @sum) function, or 1XQ. This computes the sum of the second input grouped by values of the first input.


The Most Useless Program EVER! Inspired by The Most Useless Machine Ever.

Write the shortest program that does the following:

create a graphical window, then immediately close the window and exit the program.
do this in some visually apparent manner. Like the "arm" that pushes the switch in the machine, the program must use some visual method in the GUI to close itself.
this visual method must be what causes the program to close; you cannot just show it as something on the side (though there may be other things off to the side)

Note:

The program does not have to be visible long enough for the visible activity to be seen by a human as long as the activity is the cause of the closing.
The window must be a GUI (must display a graphical window that contains the visible exit method).
The visual method needs to be something the user could do if it wasn't done automatically. Explain what needs to be changed in the code for the user to be able to do this (Thanks to Iszi).
The program must close if there is no interference from the user, but if the user interferes, then it does not need to close automatically.
Please include an explanation of what it is that causes the program to close.

Example: a window containing a button which is programmatically clicked, running a short snippet of code that closes the program.

Ruby with Shoes, 110

Shoes.app{button('Close'){exit}
p=para
t=Time.now
animate{u=(t-Time.now).to_i+10
exit if u<0
p.text=' '*u+?<}}

Makes a little arrow that pushes a "Close" button. (Pushing the close button manually also closes the window.)


Animated sound waveform Make an animated sound waveform using any programming language your prefer, the squares of the spectrum can be of a single color (no rainbow effect).
The animation must be infinite and not a loop sequence (must be a random animation).

You can use any kind of external library you prefer.

This is a code-golf so the shortest code will win.

Example of waveform:

(a screenshot of the result is appreciated)

Edit:
I thought was obvious,but the waveform must be horizontal.

APL (61)

{∇n⊣⎕DL.1⊣⎕SM←1 1,⍨⊂' '⍪⊖⍉↑⍴∘'▇'¨,0,⍪n←24⌊0⌈⍵+3-?5/⍨⍴⍵}?24/40

It starts with random-sized bars, and changes the height of each of the bars by a random number between -2 and 2 each frame.

Screenshot:


Distributing parliament seats Introduction
In a general election, one would like to calculate a constant price per parliament seat. This means that for N >= 0 seats to be distributed and a list ns of votes per party, we would like to find a number d such that
sum(floor(n/d) for n in ns) == N

To make things interesting (and more like the real world), we add two more facts:

Two parties can gather in a 'coalition', so that the seats are given to the 'coalition' by the sum of votes for all parties in it. Then the seats the 'coalition' got are split between parties in a similar fashion (find divisor, etc.)

A party that didn't pass a certain percentage of the votes (e.g. 3.25%) automatically gets 0 seats, and its votes don't count for a 'coalition'.

Challenge
You are given :

A list of lists, each of the nested lists contains integers (number of votes), and is of length 1 for a single party, or length 2 for a 'coalition'.
Minimal percentage of votes (a.k.a "bar" for "barrage") to get seats, as a fraction (so 3.25% is given as 0.0325)
Total number of seats to be distributed between all parties (integer)

You are to print out the same nested list structure, with the number of votes substituted with parliament seats.
Winner is the code with the smallest amount of bytes.
Corner cases:

There might (and usually will be) more than one possible divisor. Since it is not in the output, it doesn't really matter.
Imagine N=10 and ns = [[1]], so the divisor may be 0.1 (not an integer)
Some cases can't be solved, for example ns=[[30],[30],[100]], bar=0, N=20. There's a boundary with d=7.5 where the sum of floored values jumps from 19 to 21. You are not expected to solve these cases. (thanks to community member Arnauld for pointing this case out)

Example Input and Output

A very not-optimized Python3 example:
from math import floor

def main(_l, bar, N):
    # sum all votes to calculate bar in votes
    votes = sum(sum(_) for _ in _l)

    # nullify all parties that didn't pass the bar
    _l = [[__ if __ >= bar * votes else 0 for __ in _] for _ in _l]

    # find divisor for all parliament seats
    divisor = find_divisor([sum(_) for _ in _l], N)

    # find divisor for each 'coalition'
    divisors = [find_divisor(_, floor(sum(_)/divisor)) for _ in _l]

    # return final results
    return [[floor(___/_) for ___ in __] for _, __ in zip(divisors, _l)]

def find_divisor(_l, N, _min=0, _max=1):
    s = sum(floor(_ / _max) for _ in _l)
    if s == N:
            return _max
    elif s < N:
            return find_divisor(_l, N, _min, (_max + _min) / 2)
    else:
            return find_divisor(_l, N, _max, _max * 2)

print(main(l, bar, N))

Example input:
l = [[190970, 156473],
    [138598, 173004],
    [143666, 193442],
    [1140370, 159468],
    [258275, 249049],
    [624, 819],
    [1125881],
    [152756],
    [118031],
    [74701]]
bar = 0.0325
N = 120

And its output:
[[6, 4], [0, 5], [4, 6], [35, 5], [8, 8], [0, 0], [35], [4], [0], [0]]

Some more example outputs:
If bar=0.1 we get an interesting stand-off between two parties as none of the smaller parties are counted in:
[[0, 0], [0, 0], [0, 0], [60, 0], [0, 0], [0, 0], [60], [0], [0], [0]]

And if N=0 (corner case) then of course no one gets anything:
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0], [0], [0], [0]]

Python 2, 220 bytes

def d(l,n,a=0,b=1.):s=sum(x//b for x in l);return s-n and d(l,n,*[a,b,(a+b)/2,b*2][s>n::2])or b
def f(l,b,n):l=[[x*(x>=b*sum(sum(l,[])))for x in r]for r in l];return[[v//d(x,sum(x)//d(map(sum,l),n))for v in x]for x in l]

Try it online!

Basically just a golf of the reference implementation...


Hidden Inversions (Robbers' Thread) This is a cops-and-robbers puzzle, the cops' thread can be found here.

Your task will be to find an anagram of the provided programs in the cops' thread that performs its left inverse.

Once you crack an answer post the solution as an answer below and notify the original answerer.

You will be scored on the number of programs you are the first to crack.


Unrestricted Languages One of my favorite types of challenges on this site are restricted-source challenges.  These challenges impose a computer tractable restriction that the sources of potential answers must pass.  I like these challenges so much I have been working on a golfing language designed to win at these challenges for some time now.  Now I want to extend the challenge to you.  Your task is to design a language to solve a variety of restricted source tasks.  You will time to design and implement a language, at which point changes and new additions will be non-competing and all of the submissions will go head to head in a gauntlet of restricted-source challenges.

Scoring

Before the challenge is posted I will come up with a list of simple challenges to solve and a list of source restrictions to follow.  For each matching of challenge and source restrictions your language can earn between 0 and 2 points. (there will be 10 challenges and 10 restrictions leading to 100 total combinations) A language scores

1 point if it can complete the task with the restriction in under 150 bytes
2 points if the solution is the shortest solution of any language competing (both languages will score 2 points in the event of a tie)
0 points if they are unable to create a program that completes the task under the restriction in less than 150 bytes.

Your score will be the sum of all points earned in every possible match up. The goal is to get the highest score.  Other people may help you to golf your solutions to each challenge and improve your score.

I will reveal 4 items of each list at the time of posting and an additional 8 one week after the second answer. You will only be allowed to score 1 point (shortest submission does not count) in any matching that has both parts revealed before the the first week. This way you can get an idea of how well your language stacks up while you are working on it, but you can't design you language simply to build in all of the challenges and restrictions.

I will include a hash of the intended categories with the question so you can be sure I do not change them during the week to advantage any party.  In addition I will not tell anyone the hidden parameters until the week is up nor compete in the challenge myself.

Pre-existing languages

This challenge is open to all pre-existing languages however if you are not the author of the language, please make your answer a community wiki so that other members of our community can contribute to the score directly.  Command line flags need not obey any restrictions however every program should be run with the same command line arguments (i.e. you should pick one and stick with it).  These do not add to your byte count.

Challenges and restrictions

Restrictions are enforced on the ASCII encoding of your binaries regardless of the code-page you use.  Some of these link to an existing question on the site from which they inherit their io requirements for challenges and source restrictions for restrictions.  You can ignore anything "banning builtins" or overriding existing meta consensuses on any of the linked challenges.

As a word of warning: do not try to rule lawyer; I know it is a competition but because there are essentially 100 different sub-challenges challenges and I simply cannot guarantee that all of them will be entirely unproblematic.  Just try to have fun.

Challenges

Sort a list of integers
print Hello, world!
Determine if parentheses are balanced
Test Primality

Restrictions

Only odd bytes (every 8th bit must be odd)
Double bytes
Bytes are in ascending order (each byte is greater than the last)
Source code is a palindrome

The remaining criteria have a sha512 hash of:

4de5eca33c6270798606cf1412820c4ce112d8b927ef02877f36795b2b15ffacca51ea598fa89b8d6bc9f4cde53810e0e7ade30e536e52e28f40a6a13841dfc5  -

Width
The interpreter is still a work in progress (I have several unused command slots still). The repo, with more documentation, can be found here.
Dennis added Width to TIO less than a minute ago: Try It Online!
Width is an esoteric stack-based language I developed recently based on ideas I first dumped in this question. It is based entirely on how wide, more or less, a letter is in a "regular" font. The only characters that do anything are letters, uppercase and lowercase. All other characters are ignored. I split letters up into 10 different width categories, which form the 10 different actions possible in Width:
0: i j l                     # do while counter > 0
1: f r t I                   # end
2: c k s v x y z J           # 0 in commands
3: a b d e g h n o p q u L   # separator (no-op)
4: F T Z                     # push base 10 number, using left side row titles (width numbers); terminated with original char
5: A B E K P S V X Y         # 1 in commands
6: w C D H N R U             # 2 in commands
7: G O Q                     # push string literal; sets of 2 width numbers equate to index in printable ASCII; terminated with original char
8: m M                       # if top of stack
9: W                         # else

2, 5, and 6 provide access to the commands, most of which interact with the stack. More information can be found at the info.txt page in the Github repo.
This is the Python code of the interpreter. I still have several commands to add, and I'm considering how to work with error-handling, but otherwise it should be complete. (I'm also going to add a flag at some point to allow testing with a more abstract syntax, because otherwise this language is a giant pain to work with)
import sys
import math
import numbers
import functools

try:
    file = sys.argv[1]
except IndexError:
    file = "source.wide"

with open(file) as f:
    source = f.read()

translation = ("ijl", "frtI", "cksvxyzJ", "abdeghnopquL", "FTZ", "ABEKPSVXY", "wCDHNRU", "GOQ", "mM", "W")
chars = "".join(sorted("".join(translation)))
strings = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\t"""

def trans(letter):
    for each in translation:
        if letter in each:
            return translation.index(each)

COMMAND = "COMMAND"
COMMANDS = (2, 5, 6)
NUMBER = "NUMBER"
STRING = "STRING"
DO = "DO"
IF = "IF"
ELSE = "ELSE"
END = "END"
SEPARATOR = "SEPARATOR"

class Token:
    def __init__(self, val, type_):
        self.val = val
        self.type = type_

class Lexer:
    def __init__(self, src):
        self.src = src
        self.pos = 0
        self.char = self.src[self.pos]

    def read(self):
        if self.char is None:
            return None

        command = trans(self.char)

        if command == 0:
            self.advance()
            return Token(0, DO)
        elif command == 1:
            self.advance()
            return Token(1, END)
        elif command == 3:
            self.advance()
            return Token(3, SEPARATOR)
        elif command == 4:
            return self.read_num()
        elif command == 7:
            return self.read_str()
        elif command == 8:
            self.advance()
            return Token(8, IF)
        elif command == 9:
            self.advance()
            return Token(9, ELSE)
        else:
            return self.read_cmd()

    def advance(self):
        self.pos += 1

        try:
            self.char = self.src[self.pos]
        except IndexError:
            self.char = None

    def read_num(self):
        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += str(trans(self.char))
            self.advance()

        self.advance()

        return Token(int(res), NUMBER)

    def read_str(self):
        def read_char():
            res_ = str(trans(self.char))
            self.advance()
            res_ += str(trans(self.char))
            self.advance()
            try:
                return strings[int(res_)]
            except IndexError:
                return " "

        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += read_char()

        self.advance()

        return Token(res, STRING)

    def read_cmd(self):
        command = ""
        while self.char is not None and trans(self.char) in COMMANDS and len(command) <= 4:
            command += str(COMMANDS.index(trans(self.char)))
            self.advance()

        return Token(command, COMMAND)

source = "".join(filter(lambda c: c in chars, source))

stack = []
backburner = []
counter = 0

def set_counter(val):
    global counter
    counter = int(val)

    if counter < 0:
        counter = 0

def set_stack(val):
    global stack
    stack = val

def num_input():
    inp = input()
    try:
        stack.append(int(inp))
    except ValueError:
        try:
            stack.append(float(inp))
        except ValueError:
            pass

def flip_ends():
    if len(stack) > 1:
        stack[0], stack[-1] = stack[-1], stack[0]

def clear_stack():
    global stack
    stack = []

def reload_stack(is_top):
    global backburner, stack

    if is_top:
        stack.extend(backburner)
    else:
        stack = backburner + stack

    backburner = []

# https://stackoverflow.com/a/15285588/7605753
def is_prime(n):
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(math.sqrt(n))
    _f = 5
    while _f <= r:
        if n % _f == 0:
            return False
        if n % (_f + 2) == 0:
            return False
        _f += 6
    return True

def error():
    raise Exception

commands = {
    "0": lambda: stack.append(stack[-1]),
    "1": lambda: stack.append(stack.pop(-2)),
    "2": lambda: stack.pop(),
    "00": lambda: set_counter(stack[-1]),
    "01": lambda: stack.append(len(stack)),
    "02": lambda: stack.append(input()),
    "10": num_input,
    "11": lambda: stack.append(str(stack.pop())),
    "12": lambda: stack.append(int(stack.pop())),
    "20": lambda: set_counter(counter + 1),
    "21": lambda: set_counter(counter - 1),
    "22": lambda: print(stack.pop()),
    "000": lambda: stack.append(float(stack.pop())),
    "001": lambda: stack.append(-stack.pop()),
    "002": lambda: stack.append(not stack.pop()),
    "010": lambda: stack.append(stack.pop(-2) + stack.pop()),
    "011": lambda: stack.append(stack.pop(-2) - stack.pop()),
    "012": lambda: stack.append(stack.pop(-2) / stack.pop()),
    "020": lambda: stack.append(stack.pop(-2) // stack.pop()),
    "021": lambda: stack.append(stack.pop(-2) * stack.pop()),
    "022": lambda: stack.append(stack.pop(-2) % stack.pop()),
    "100": lambda: stack.append(math.factorial(stack.pop())),
    "101": lambda: stack.append(str(stack.pop(-2)) + str(stack.pop())),
    "102": lambda: stack.append(math.pow(stack.pop(-2), stack.pop())),
    "110": lambda: stack.append(math.sqrt(stack.pop())),
    "111": lambda: stack.append(math.log(stack.pop(-2), stack.pop())),
    "112": lambda: stack.append(~stack.pop()),
    "120": lambda: stack.append(stack.pop(-2) | stack.pop()),
    "121": lambda: stack.append(stack.pop(-2) & stack.pop()),
    "122": lambda: stack.append(stack.pop(-2) << stack.pop()),
    "200": lambda: stack.append(stack.pop(-2) >> stack.pop()),
    "201": lambda: stack.append(stack.pop(-2)[stack.pop()]),
    "202": lambda: stack.append(str(stack.pop(-2)) * stack.pop()),
    "210": lambda: stack.append(counter),
    "211": lambda: set_counter(stack.pop()),
    "212": lambda: stack.extend(list(str(stack.pop()))),
    "220": flip_ends,
    "221": lambda: stack.append(len(stack[-1])),
    "222": lambda: print(stack[-1]),
    "0000": lambda: stack.reverse(),
    "0001": lambda: stack.sort(),
    "0002": lambda: stack.append(stack[counter]),
    "0010": lambda: stack.append(stack[stack.pop()]),
    "0011": 0,
    "0012": 0,
    "0020": lambda: stack.append(sum(n for n in stack if isinstance(n, numbers.Number))),
    "0021": lambda: stack.append(functools.reduce(lambda x, y: x*y, [n for n in stack if isinstance(n, numbers.Number)], 1)),
    "0022": 0,
    "0100": lambda: (backburner.extend(stack), clear_stack()),
    "0101": lambda: reload_stack(True),
    "0102": lambda: reload_stack(False),
    "0110": lambda: backburner.append(stack.pop()),
    "0111": lambda: backburner.append(list(stack.pop())),
    "0112": lambda: stack.pop().split(stack.pop()),
    "0120": lambda: stack.append(backburner[-1]),
    "0121": lambda: (lambda depth=stack.pop(): (set_stack(stack[-depth:]), backburner.append(stack[:depth])))(),
    "0122": lambda: (lambda depth=stack.pop(): (set_stack(stack[:-depth]), backburner.append(stack[depth:])))(),
    "0200": lambda: set_stack([stack.pop().join(stack)]),
    "0201": lambda: set_stack(["".join(stack)]),
    "0202": lambda: (lambda depth=stack.pop(-2): set_stack(stack[-depth:] + [stack.pop().join(stack[:depth])]))(),
    "0210": lambda: (lambda depth=stack.pop(): set_stack(stack[-depth:] + ["".join(stack[:depth])]))(),
    "0211": 0,
    "0212": 0,
    "0220": lambda: stack.append(stack.pop().split(stack.pop())),
    "0221": lambda: stack.append(stack.pop().split(", ")),
    "0222": 0,
    "1000": lambda: stack.append(is_prime(stack[-1])),
    "1001": lambda: stack.append((lambda s=stack.pop(): s == s[::-1])()),
    "1002": lambda: stack.append(1 / stack.pop()),
    "1010": lambda: stack.append(stack.pop() - 1),
    "1011": lambda: stack.append(stack.pop() + 1),
    "1012": lambda: stack.append(stack.pop() * 2),
    "1020": lambda: stack.append(stack.pop() / 2),
    "1021": lambda: stack.append(stack.pop() ** 2),
    "1022": lambda: float("." + str(stack.pop())),
    "1100": lambda: stack.append(stack.pop() == stack.pop()),
    "1101": lambda: stack.append(stack.pop() != stack.pop()),
    "1102": lambda: stack.append(stack.pop() > stack.pop()),
    "1110": lambda: stack.append(stack.pop() < stack.pop()),
    "1111": lambda: stack.append(stack.pop() >= stack.pop()),
    "1112": lambda: stack.append(stack.pop() <= stack.pop()),
    "1120": lambda: stack.append(stack.pop() in stack),
    "1121": lambda: stack.append(stack.pop() in backburner),
    "1122": lambda: stack.append(stack.pop() == counter),
    "1200": lambda: stack.append(stack.pop() in stack.pop()),
    "1201": lambda: stack.append(stack.pop(-2).find(stack.pop())),
    "1202": 0,
    "1210": 0,
    "1211": 0,
    "1212": lambda: stack.append(stack.pop().lower()),
    "1220": lambda: stack.append(stack.pop().upper()),
    "1221": lambda: stack.append(ord(stack.pop())),
    "1222": lambda: stack.append(chr(stack.pop())),
    "2000": lambda: stack.append(math.floor(stack.pop())),
    "2001": lambda: stack.append(math.ceil(stack.pop())),
    "2002": lambda: stack.append(round(stack.pop())),
    "2010": lambda: stack.append(abs(stack.pop())),
    "2011": 0,
    "2012": 0,
    "2020": lambda: stack.append(len(stack.pop())),
    "2021": 0,
    "2022": 0,
    "2100": lambda: stack.append(min(stack)),
    "2101": lambda: stack.append(max(stack)),
    "2102": lambda: stack.append(stack.count(stack.pop())),
    "2110": lambda: stack.append(sum(stack) / len(stack)),
    "2111": 0,
    "2112": 0,
    "2120": 0,
    "2121": 0,
    "2122": 0,
    "2200": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop())),
    "2201": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop(), 1)),
    "2202": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "")),
    "2210": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "", 1)),
    "2211": 0,
    "2212": lambda: stack.append(eval(stack.pop())),
    "2220": lambda: stack.append(eval(input())),
    "2221": lambda: print(stack[-1]),
    "2222": lambda: error()
}

def run_cmd(name):
    global stack, counter, backburner

    state = {
        "stack": list(stack),
        "counter": counter,
        "backburner": list(backburner)
    }

    # TODO: unknown command

    try:
        commands[name]()
    except IndexError:
        stack = state["stack"]
        counter = state["counter"]
        backburner = state["backburner"]

class AST:
    pass

class Main(AST):
    def __init__(self):
        self.nodes = []

class Do(AST):
    def __init__(self, node):
        self.node = node

class If(AST):
    def __init__(self, first, second):
        self.first = first
        self.second = second

class Literal(AST):
    def __init__(self, val):
        self.val = val

class Command(AST):
    def __init__(self, val):
        self.val = val

class Parser:
    def __init__(self, lexer):
        self.lexer = lexer
        self.token = None

    def parse(self):
        pgm = Main()
        self.token = self.lexer.read()

        while self.token is not None and self.token.type != END and self.token.type != ELSE:
            if self.token.type == DO:
                pgm.nodes.append(Do(self.parse()))

            elif self.token.type == NUMBER or self.token.type == STRING:
                pgm.nodes.append(Literal(self.token.val))

            elif self.token.type == IF:
                first = self.parse()

                if self.token.type == ELSE:
                    second = self.parse()
                else:
                    second = None

                pgm.nodes.append(If(first, second))

            elif self.token.type == COMMAND:
                pgm.nodes.append(Command(self.token.val))

            self.token = self.lexer.read()

        return pgm

class Interpreter:
    def __init__(self, tree):
        self.tree = tree

    def visit(self, node):
        method_name = "visit_" + type(node).__name__
        visitor = getattr(self, method_name.lower())
        return visitor(node)

    def interpret(self):
        self.visit(self.tree)

    def visit_main(self, node):
        for each in node.nodes:
            self.visit(each)

    def visit_do(self, node):
        while counter:
            self.visit(node)

    def visit_if(self, node):
        if stack[-1]:
            self.visit(node.first)
        elif node.second:
            self.visit(node.second)

    def visit_literal(self, node):
        stack.append(node.val)

    def visit_command(self, node):
        run_cmd(node.val)

if source == "":
    with open("info.txt") as f:
        info = f.read()

    print(info)
else:
    main = Parser(Lexer(source)).parse()

    interpreter = Interpreter(main)
    interpreter.interpret()

    try:
        sys.exit(stack[-1])
    except IndexError:
        pass


Count how many times your program repeats Your task is to write a program or function. It's output/return value must follow these rules:

The program outputs 1
The program repeated n times outputs n
The program backwards outputs -1
The program backwards and repeated n times outputs -n
A mix of forward and backward programs will output number_forward - number_backward

Take the program aB for example.

aB should output 1
aBaB should output 2
Ba should output -1
BaBa should output -2
aBBa should output 0
aBBaBa should output -1
aaB, C, or  would not need to be handled

This is code-golf, so shortest in bytes per language wins.

Jelly, 2 bytes
NC

Try it online! Or see all test-cases.
How?
In Jelly any sequence of monadic atoms forms a monadic chain which simply applies those monadic atoms in turn from left to right, starting with the value of it's left argument. When a full program is run with no arguments zeros are implicitly supplied as necessary, i.e. main_link(0) is called. As such NC is C(N(0)) and CN is N(C(0)).
NCNC ... CN ... NC - Main Link: no arguments
N                  - negate((implicit)0)     -1 *  0 =  0
 C                 - complement(that)         1 -  0 =  1
  N                - negate(that)            -1 *  1 = -1
   C               - complement(that)         1 - -1 =  2
     ...           -
     ...           -                             ... =  a
        C          - complement(a)            1 -  a =  1 - a
         N         - negate(that)       -1 * (1 - a) =  a - 1
            ...    -
            ...    -                             ... =  b
               N   - negate(b)               -1 *  b = -b
                C  - complement(that)         1 - -b =  b + 1


Calculate Exponents bit by bit Your task is to slowly calculate exponentiation, with the following steps:

Given two inputs (in this example, 4 and 8), you must calculate the exponentiation by calculate the equation bit by bit. You would do 4^8, have a greater base value (4) and a smaller exponent (8). You can do this using more exponentiation and division. You can divide the exponent by a value X (provided X is a prime divisor of the exponent), and make the base value (B) into B^X. For example, you can do:

4^8 = (4 ^ 2)^(8 / 2) = 16^4

I have replaced X with 2 in the previous equation.

You can 'simplify' 16^4 further, again with X = 2:

16^4 = (16 ^ 2)^(4 / 2) = 256^2

And then finally calculate a number (again, X = 2):

256^2 = (256 ^ 2)^(2 / 2) = 65536^1 = 65536

Therefore,

4^8 = 16^4 = 256^2 = 65536

This is the output you should give. The output separator is a little flexible, for example, you can separate the equations by newlines or spaces instead of =. Or, you may put them into a list (but you mustn't use a digit or the ^ character as a separator).

As Martin Ender pointed out, the ^ is also flexible. For example, you may use [A, B] or A**B instead of A^B in the output.

X may only be prime, which means you cannot use X = 8 to get straight to the solution, and the values of X will only be prime factors of the second input (the exponent).

Examples:

(input) -> (output)
4^8 -> 4^8=16^4=256^2=65536
5^11 -> 5^11=48828125
2^15 -> 2^15=32^3=32768 (2^15=8^5=32768 is also a valid output)

Mind that the input format is also flexible (eg you may take A \n B or A B instead of A^B. Obviously, this wouldn't be a problem if you write a function taking two arguments.

In the second example, we go straight to calculation, since 11 is prime and we cannot take any more steps.

You may write a program or a function to solve this, and you may print or return the value, respectively.

As this is code-golf, that shortest code wins!

JavaScript (ES7), 55 bytes

f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(a**c,b/c)]:a

Uses , in place of = (2^15,8^5,32768).

Test cases

f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(Math.pow(a,c),b/c)]:a
g=(a,b)=>console.log(`f(${a}, ${b}):`,f(a,b))

g(4,8)
g(5,11)
g(2,15)

Note: the snippet uses Math.pow instead of ** for cross-browser compatibility.


Koalas, Crabs, and Commapillars Given two positive integers X and Y, output any combination of the following three ASCII-art animals such that the output contains exactly X commas (,) and Y periods (.), if it is possible.

Koala: 1 comma, 2 periods

<.,.>

Crab: 2 commas, 2 periods

,<..>,

Commapillar: 3 or more commas, 1 period

<,,,.>

or <,,,,.> or <,,,,,.> or <,,,,,,.> or <,,,,,,,.> etc.

If no combination of these animals can produce exactly X commas and Y periods, output a single commaleon who will camouflage the failure:

~<.,,>~~

The output animals can be in any amounts and any order. They may be in a string, space or newline separated, or else in a list where each animal is one element.

For example, for X = 7, Y = 5, these would all be valid outputs (separated by empty lines):

<.,.> <.,.> <,,,,,.>

<.,.>
<,,,,,.>
<.,.>

,<..>, <.,.> <,,,,.>

<,,,,.>
,<..>,
<.,.>

,<..>, <,,,.> ,<..>,

[",<..>,", ",<..>,", "<,,,.>"] (list syntax depends on language)

Note that (at least in this example) there are multiple sets of animals than can work. But remember you only need to output any one valid solution, if one exists. The number of animals or number of distinct animals does not matter.

For inputs such as X = 3, Y = 3 or X = 1, Y = 5 where there is no solution, the output will always be

~<.,,>~~

perhaps in a single-element list.

The shortest code in bytes wins.

Ruby, 139 bytes
Lambda function, takes x and y as arguments and returns a string
->x,y{c=y-2*n=y-(x>y ?1:0)>>1
x+=-c/2*s=[x-n,c*3].max
x<n||x>n*2?'~<.,,>~~':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}

If a solution exists, it can be done with all koalas+commapillars or all koalas+crabs.
The principle is to use a minimum of commapillars. If the number is odd, we use 1 commapillar. if even we use 0 commapillars, unless there are more commas than periods, in which case we use 2.
The number of periods used in noncommapillars (crabs + koalas) is necessarily even, and the number of noncommapillars is half (number of periods)-(number of commapillars). If there are insufficient commas for all koalas, or too many for all crabs, no solution is possible. Otherwise, we return a solution.
Commented in test program
uses "fail" instead of chameleon for clarity
f=->x,y{c=y-2*n=y-(x>y ?1:0)>>1
#n=noncommapillars=y>>1 as they have 2 periods. c=commapillars=y-2*n, 1 for odd y, 0 for even y.
#if x>y there are too many commas to have 0 commapillars for even y. noncommapillars= y-1 >> 1, so 2 commapillars

x+=-c/2*s=[x-n,c*3].max
# s=number of commas allocated to commapillars. x-n to allow all noncommapillars to be koalas, but at least 3 per commapillar.
#-c/2 == -1 if there are commapillars, 0 if not (Ruby truncates toward -inf). Subtract commas for commapillars from x if necessary

x<n||x>n*2?'fail':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}
#if x<n (insufficient commas for all koalas) or x>n*2 (too many for all crabs) return fail. Else...
#return string off crabs, koalas, and (using % operator like sprintf) c commapillars (0..2), the second with 3 commas (if present) and the first with the rest.

10.times{|j|10.times{|i|puts "%-20s %s"%[?.*j+?,*i,f[i,j]]}}
#all x,y from 0..9

Output
,                    fail
,,                   fail
,,,                  fail
,,,,                 fail
,,,,,                fail
,,,,,,               fail
,,,,,,,              fail
,,,,,,,,             fail
,,,,,,,,,            fail
.                    fail
.,                   fail
.,,                  fail
.,,,                 <,,,.>
.,,,,                <,,,,.>
.,,,,,               <,,,,,.>
.,,,,,,              <,,,,,,.>
.,,,,,,,             <,,,,,,,.>
.,,,,,,,,            <,,,,,,,,.>
.,,,,,,,,,           <,,,,,,,,,.>
..                   fail
..,                  <.,.>
..,,                 ,<..>,
..,,,                fail
..,,,,               fail
..,,,,,              fail
..,,,,,,             <,,,.> <,,,.>
..,,,,,,,            <,,,,.> <,,,.>
..,,,,,,,,           <,,,,,.> <,,,.>
..,,,,,,,,,          <,,,,,,.> <,,,.>
...                  fail
...,                 fail
...,,                fail
...,,,               fail
...,,,,              <.,.> <,,,.>
...,,,,,             <.,.> <,,,,.>
...,,,,,,            <.,.> <,,,,,.>
...,,,,,,,           <.,.> <,,,,,,.>
...,,,,,,,,          <.,.> <,,,,,,,.>
...,,,,,,,,,         <.,.> <,,,,,,,,.>
....                 fail
....,                fail
....,,               <.,.> <.,.>
....,,,              ,<..>, <.,.>
....,,,,             ,<..>, ,<..>,
....,,,,,            fail
....,,,,,,           fail
....,,,,,,,          <.,.> <,,,.> <,,,.>
....,,,,,,,,         <.,.> <,,,,.> <,,,.>
....,,,,,,,,,        <.,.> <,,,,,.> <,,,.>
.....                fail
.....,               fail
.....,,              fail
.....,,,             fail
.....,,,,            fail
.....,,,,,           <.,.> <.,.> <,,,.>
.....,,,,,,          <.,.> <.,.> <,,,,.>
.....,,,,,,,         <.,.> <.,.> <,,,,,.>
.....,,,,,,,,        <.,.> <.,.> <,,,,,,.>
.....,,,,,,,,,       <.,.> <.,.> <,,,,,,,.>
......               fail
......,              fail
......,,             fail
......,,,            <.,.> <.,.> <.,.>
......,,,,           ,<..>, <.,.> <.,.>
......,,,,,          ,<..>, ,<..>, <.,.>
......,,,,,,         ,<..>, ,<..>, ,<..>,
......,,,,,,,        fail
......,,,,,,,,       <.,.> <.,.> <,,,.> <,,,.>
......,,,,,,,,,      <.,.> <.,.> <,,,,.> <,,,.>
.......              fail
.......,             fail
.......,,            fail
.......,,,           fail
.......,,,,          fail
.......,,,,,         fail
.......,,,,,,        <.,.> <.,.> <.,.> <,,,.>
.......,,,,,,,       <.,.> <.,.> <.,.> <,,,,.>
.......,,,,,,,,      <.,.> <.,.> <.,.> <,,,,,.>
.......,,,,,,,,,     <.,.> <.,.> <.,.> <,,,,,,.>
........             fail
........,            fail
........,,           fail
........,,,          fail
........,,,,         <.,.> <.,.> <.,.> <.,.>
........,,,,,        ,<..>, <.,.> <.,.> <.,.>
........,,,,,,       ,<..>, ,<..>, <.,.> <.,.>
........,,,,,,,      ,<..>, ,<..>, ,<..>, <.,.>
........,,,,,,,,     ,<..>, ,<..>, ,<..>, ,<..>,
........,,,,,,,,,    <.,.> <.,.> <.,.> <,,,.> <,,,.>
.........            fail
.........,           fail
.........,,          fail
.........,,,         fail
.........,,,,        fail
.........,,,,,       fail
.........,,,,,,      fail
.........,,,,,,,     <.,.> <.,.> <.,.> <.,.> <,,,.>
.........,,,,,,,,    <.,.> <.,.> <.,.> <.,.> <,,,,.>
.........,,,,,,,,,   <.,.> <.,.> <.,.> <.,.> <,,,,,.>


Missing Integer Sequence Detection -- Filesystem The challenge is to detect missing integer sequences of files or directories. You have a directory filled with files/directories that are named as integers.

The files/directories are generated from multiple threads yet the job did not complete - there are therefore gaps in the sequence.

The input is two integers a start and an end, and your task is detect the starting integer of the next missing sequences. You may presume that all files and directories in the directory where run have only integer named files or directories.

Acceptable answer forms: functions, code snippets - they must run on the command line.
Acceptable start/end input: included on the command line, env variables/argv are okay, parameters to functions, user input is okay.
Shortest code wins.

Update -- Although I managed to squeeze out this one, there were many interesting answers. The idea in apricotboy's Bash answer was used in part to help me design my 35 Byte Bash answer. Best of luck on the next one.

E.g. Presume files 1,2,3,4,7,8,9,10,18 are present, start is 1, end is 20:

The output should be:
5
11
19

Python 2, 101 bytes

2 bytes thanks to @xnor.

import os
t=-1
for n in range(input(),input()+1):
 if~-os.path.isfile(str(n)):
  if~t+n:print n
  t=n


Thinking outside the box You are trying to fit a sphere into a 5-sided box, but sometimes it does not fit completely. Write a function to calculate how much of the sphere is outside (above the rim of) the box.

There are 3 possible situations:

The sphere fits completely in the box. The answer will be 0.
The sphere sits on the rim of the box. The answer will be more than half of the total volume.
The sphere sits on the bottom of the box.

You can see each situation here:

You must write a program or function to compute this value to at least 4 significant digits.

Input: 4 non-negative real numbers in whatever format is convenient* - width, length, depth of the box (interior measurements), and diameter of the sphere.

Output: 1 non-negative real number in a usable format* - the total volume (not the percentage) of the sphere outside the box.

* must be convertible to/from a decimal string

You are encouraged to limit your use of trigonometry as much as possible.

This is a popularity contest, so think outside the box!

Forth

Please find, below, a sphere outside the box.

The "sphere" is the volume-computing function f. The reference test cases compose the "box".

                     ( x y z d -- v )
                 : f { F: z F: d } d f2/
              { F: r } fmin { F: m } m f2/ {
             F: b } d m f<= d z f<= and if 0e
             else r r r f* b b f* f- fsqrt f-
              { F: t } d m f<= t z f> or if d
               z f- else d t f- then r 3e f*
                  fover f- pi f* fover f*
                      f* 3e f/ then ;

                     1e                 1e
                     1e                 1e
                     f                  f.
            cr       1e        1e       0e
            1e       f         f.       cr
            1e       1e 0.5e 1e f f. cr 1e
            0.999e 1e          1e     f
            f.  cr            0.1e 1e
            1.000e 0.500e f f. cr

Output:

0.
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212


Map an array of functions to their return values in point-free style Introduction

I have some JavaScript code that uses Array.prototype.map to map an array of functions fns to their return values:

const fns = [() => 1, () => 2];
const result = fns.map(
  fn => fn()
);
console.log(result); // => [1, 2]

Challenge

The argument to map above is fn => fn(). The challenge is to rewrite this function using point-free style. Your solution should work when it replaces the third line of the above program:

const fns = [() => 1, () => 2];
const result = fns.map(
  /* your solution should work when inserted here */
);
console.log(result); // => [1, 2]

fn => fn() is not a valid solution because it defines a parameter named fn. Writing a function in point-free style requires writing it without any variable or parameter names.

Note that map will pass three arguments to your solution function: currentValue: () => T, index: number, and array: Array<() => T>. The function for the solution must return the result of calling the currentValue function, so hard-coding 1 and 2 will not help. The functions being mapped over are guaranteed to ignore their arguments and their this value, so calling the function in any way will work.

Scoring

The best answer is the one that is represented by the fewest tokens when lexed. The ANTLR 4 JavaScript lexer is the official lexer for the sake of objectivity, but if you know how a lexer works you should be able to estimate how many tokens some JavaScript needs without having to read that link. For example, fn => fn() is composed of five tokens: fn => fn ( ).

However, I personally think that figuring out any answer is the fun part, so if this problem interests you, try to solve it yourself before scrolling down and seeing the answer.

Based on the answer by Rory O'Kane:

  10 tokens: Number.call.bind(String.call)

Try it online!

It is trivial, since Number.call, String.call, Object.call, Function.call, (function () {}).call, Function.prototype.call are all the same.

If Bind Operator Proposal is accepted, this could be simplified to:

  6 tokens: ::Function.call.call

Babel

BTW, if eval is allowed eval("Number.call.bind(String.call)") only use 4 tokens.