Python advice: Portability of introspective function call In Python, you can use the dir function on any object to get a list of the names of its instance functions:

>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__','__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

I'm wondering if this could be a useful golfing technique in a program than calls several lengthily named functions. In such a case, I could create a function selection function F:

F=lambda o,i:eval('o.'+dir(o)[i])

Now suppose I have a string s and I want store the result of capitalizing its first letter in the variable c. Then instead of c=s.capitalize(), I could note that capitalize is at position 33 in the above list and do the following:

s='abc'
c=G(s,33)()

which assigns 'Abc' to c.

My question is whether this is likely to work most of the time. In particular,

Can I always count on the list being lexicographically sorted by ASCII values?
Are there many changes to list of available between minor versions?
Do differences exist between implementations?

Also, has anyone used this before on PPCG?

From the documentation:

  The resulting list is sorted alphabetically

As for the differences, I think you will have to check (and specifying in your answer is probably a good idea). There are clear differences between python 2 and 3, for example, __nonzero__ was renamed to __bool__.

I have never heard of any differences between implementations, but I can't find any references on this.

I don't think this has been used before in part because it will rarely save you any characters over doing something like:

F=str.capitalize
s='abc'
c=F(s)

You would need to use several different functions from dir() in order for this to be worth it.


Output the answer above yours Write a program that outputs the contents of the first HTML ... block of the answer to this question that is just above yours when the answers are sorted by votes. Output Top! if you are the top answer.

Ignore answers that have negative votes or no ... tags. The source of your program must appear in the first ... block in your post. These blocks are created automatically when you use backticks or

indent things with 4 spaces.

This is code-golf, the answer with the fewest characters wins.

Additional Rules (Updated)

Answer in any programming language you want but if you answer multiple times use different languages.
You may not hard code your output. Your program's ability to run correctly should not depend on it's vote count or on what the answer above is. If the vote distribution changed drastically your program should still correctly output the code of the answer above it.
You may hard code your program to search for itself on this page (so as to find the next highest) via some unique property of your answer, such as your username (if you only have one answer) or the answer's direct link.
If two answers have equal votes you should still use the one just above yours (which I believe will be the newest one).
You may have multiple ... blocks in your answer but the first one must contain your program's source.

PHP 666 611 593 588 580 Characters
Edit: Used even smaller url than previously from tinyurl.
Edit: Following comment on other answer I used int rather than boolean. Also needed to correct an error that became apparent but fixed now.
Here is my code
<?
$a=34727;$b=new DOMDocument();$b->loadHTMLFile("http://turl.no/t2u");$c=$b->saveHTML();$d=$e=1;$f='data-answerid="';$g=strpos($c,$f);$h=substr($c,0,$g);$c=substr($c,($g+15));while($d==1){$g=strpos($c,'"');$i=substr($c,0,$g);if($i==$a){$j=$h;$k=$e;}$g=strpos($c,'vote-count-post ">');$c=substr($c,($g+18));$g=strpos($c,'<');$l=substr($c,0,$g);$g=strpos($c,'data-answerid="');if($g){++$e;++$e;$h=substr($c,0,$g);$c=substr($c,($g+15));}else{$d=2;}}if($k==1){echo 'Top!';}else{$g=strpos($j,'>');$m=strpos($j,'
');$n=$m-$g-7;$o=substr($j,($g+7),$n);echo nl2br($o);}

I am sure this can be improved using DOMXPath and nodes. However am quite pleased with it. I could not decide what to do in the case of mine is the only answer but with -ve points so ignored. However another answer was posted so not a problem any more.
I also used tinyurl to shorten the url, saving lots of characters.
I hope you like it,
Paul.
PS This will not run in codepad so can't show a fiddle.
Edit: saved 5 more with the php tags being altered
You can see it working here on a domain I do not currently use (so am not just trying a sneaky link). This is not a permanent link though but is currently available.


Write the longest program that prints the date of tomorrow I would like to propose a new kind of challenge: Anti Code Golf! (as anti-golf, not anti-code). The idea is to write the longest program you can write to do something.

That would be Code Bowling, as pointed out by ProgramFOX.

Rules

No ridiculously unnecessary whitespace (e.g. 3 lines between each statement, etc. indentation is OK, just don't overuse).
Score is awarded by number of bytes used to work * (in source code, input data or output data) memory usage doesn't count.
Highest score wins. In the event of a tie, most upvoted wins. In the event of a voting tie a randomly chosen answer wins.
You may not read from a external resource, such as a file or web service, except (when possible) the program's own source code and/or a file/service provided by the program itself.
The program must run in a reasonable time (< 5 minutes) except where otherwise specified.

.* Comments do not count for length.

Now, onto the challenge itself:

  Write a program that prints the full date of tomorrow to stdout (or equivalent) in ASCII encoding. It may or not receive any arguments, but the current date must not be input directly by the user.

C# - ~500Kb -

Don't you love nested if's?
Used to work only for 2014 dates, but successfully refactored to work for any date :)

Cannot post code here, I just receive an error...

http://pastebin.com/azGr3JSz

(Will probably hang your browser, sorry)


Recognize ASCII art numbers Challenge

Recognize ASCII art numbers. To make things interesting, three random points in the image might be flipped. For example:

 *****
 *  **
    **

   **
  **
 **

Input

A 7x7 ASCII art number generated by the below Python script.

Output

A digit.

Testing script

Here's a Python script (2.6+) to generate the test cases:

import random

digits = '''\
  ***
 ** **
**   **
**   **
**   **
 ** **
  ***

   *
 ***
   *
   *
   *
   *
 *****

  ***
 *  **
     *
    **
   **
  **
 ******

  ***
 *  **
     *
  ***
     *
 *  **
  ***

   **
  ***
 * **
*  **
******
   **
   **

 *****
 **
 ****
     *
     *
 *   *
  ***

  ****
 **
 *****
 *   *
 **  **
 **  *
  ****

 *****
    **
    **
   **
   **
  **
 **

  ****
 **  **
 **  **
  ****
 **  **
 **  **
  ****

  ***
 ** **
**   **
 **  *
  ****
    **
 ****  '''.split('\n\n')

def speckle(image, num_speckles):
    grid = [list(row) for row in image.split('\n')]

    for i in range(num_speckles):
        row = random.choice(grid)
        row[random.randint(0, 6)] = random.choice([' ', '*'])

    return '\n'.join([''.join(row) for row in grid])

digit = random.choice(digits)

print(speckle(digit, 3))

APL (87 85)

1-⍨⊃⍒(,↑{7↑'*'=⍞}¨⍳7)∘(+.=)¨{49↑,(16/2)⊤⎕UCS⍵}¨↓10 3⍴'嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢'

Explanation:

Each possible ASCII number is encoded in 48 bits. (The 49th bit is always zero anyway). The string 嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢 has three characters per ASCII number, each of which encodes 16 bits.

↓10 3⍴: split the data string into 10 3-char groups, each of which encodes a number.
{...}¨: for each of the groups:

(16/2)⊤⎕UCS⍵: get the first 16 bits of each of the three characters
,: concatenate the bit arrays into one array
49↑: take the first 49 elements. There are only 48, so this is equivalent to adding a 0 at the end.

,↑{7↑'*'=⍞}¨⍳7: read 7 lines of 7 characters from the keyboard, make a bit array for each line where 1 means the character was a *, and join them together.
(+.=)¨: for each possible digit, calculate how much bits the input had in common with the digit.
⍒: get the indices for a downwards sort of that list, so that the first item in the result is the index of the largest number in the previous list.
⊃: take the first item, which is the index of the digit
1-⍨: subtract one, because APL indices are 1-based.


Total number of topological sorts For a given DAG (directed acyclic graph), each of its topological sorts is a permutation of all vertices, where for every edges (u,v) in the DAG, u appears before v in the permutation.
Your task is to calculate the total number of topological sorts of a given DAG.
Rules

You can use any format to represent the graph, like adjacency matrix, adjacency list or edge list, as long as you don't do useful computations in your encoding. You can also have things like vertex count or vertex list in the input, if those are useful.
You can assume the graph in the input is always a DAG (doesn't have any cycles).
Your program should work in theory for any input. But it can fail if it overflows the basic integer type in your language.
The names of vertices can be any consecutive values in any type. For example: numbers starting at 0 or 1. (And only if you are not storing code in this number, of course.)
This is code-golf. Shortest code wins.

Example
This is the same input in different formats. Your program don't have to accept all of them. Vertices are always integers starting at 0.
Adjacency list:
[ [1 2 3 5] [2 4] [] [2] [] [3] ]
Adjacency matrix:
[ [0 1 1 1 0 1] [0 0 1 0 1 0] [0 0 0 0 0 0] [0 0 1 0 0 0] [0 0 0 0 0 0] [0 0 0 1 0 0] ]
Edge list:
6 [ [0 1] [0 2] [0 3] [0 5] [1 2] [1 4] [3 2] [5 3] ]

It's the graph shown in this image:

The output should be:
9

The topological sorts are:
[0 1 4 5 3 2]
[0 1 5 4 3 2]
[0 1 5 3 4 2]
[0 1 5 3 2 4]
[0 5 1 4 3 2]
[0 5 1 3 4 2]
[0 5 1 3 2 4]
[0 5 3 1 4 2]
[0 5 3 1 2 4]

Python, 58
f=lambda G,V:V<{0}or sum(f(G,V-{v})*(V-G[v]==V)for v in V)

The input consists of an adjacency dictionary G and a vertex set V.
G = {0:{1,2,3,5}, 1:{2,4}, 2:set(), 3:{2}, 4:set(), 5:{3}, 6:set()}
V = {0,1,2,3,4,5,6}

The code is recursive. The set V stores all nodes that still need visiting. For each potential next node, we check its suitability by seeing if no remaining vertices point to it, with V-G[v]==V checking that V and G[v] are disjoint. For all suitable such vertices, we add the number of topological sorts with it removed. As a base case, the empty set gives 1.


Build an adding machine using NAND logic gates This is "programming" at its most fundamental.

Build a diagram of (two-wire) NAND logic gates that will take the input wires A1, A2, A4, A8, B1, B2, B4, B8, representing two binary numbers A to B from 0 to 15, and return values on the output wires C1, C2, C4, and C8 representing C, which is the sum of A and B modulo 16.

Your score is determined by the number of NAND gates (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

Lowest score wins.

Updates:

03-07 19:09: Due to discussions with Jan Dvorak, it came to my attention that the total number of gates, constants and splits is always determined solely by the number of gates. Because of this, I have simplified the score requirement back down to simply the number of gates required.

31 gates

[created in Logisim]

The standard XOR-gate can be built with four NANDs. Tapping the first NAND provides us with a fairly compact half-adder with inverted carry:
hadder(A,B) => (sum, iCarry):

X = A^B

sum = (A^X)^(B^X)
iCarry = X

These can be combined into a 9-gate full adder:
fadder(A,B,C) => (sum, carry):

DD1 = hadder(A,B)
DD2 = hadder(DD1.sum, C)

sum = DD2.sum
carry = DD1.iCarry ^ DD2.iCarry

These combined yield a naive 36-gate four-bit adder. Not bad.
Now, we inline all modules and perform these optimizations:
delete gates with no output (only the final gate)
0^x => 1                    (one gate, twice)
1^(1^x) => 0                (two gates, once)

for a grand total of 31 gates.

Note that the count of splits and NAND-gates are intimately connected: Each 2-input NAND (larger are explicitly forbidden) takes two inputs and produces one output. Each 2-way split (let's assume larger splits are forbidden) takes one input and produces two outputs. Also, there are no unused outputs or floating inputs (let's assume constants are not allowed). If there are N more inputs than outputs, there must be N more NANDs than splits.
Thus, a 31-NAND 8=>4 module will neccessarily have 27 2-way splits.
Here are the split cardinalities for the above adder just in case larger splits are allowed:
18x wire (no split)
  4x output
  14x XOR 2nd stage
16x 2-way split
  8x input
  6x H2 input
  2x last bit XOR 1st stage
4x  3-way split
  4x XOR 1st stage
1x  4-way split
  1x 1st bit XOR 1st stage; if constants are alloweed; this is a three-way split


Compare version numbers When we publish some software, we assign a version number to it. And users may want to update to the latest version of some software. So, it is the time to find out which version should be newer.
Input
Input two version numbers as strings.
In the context of this challenge, we only support version numbers which are some digits joined by dots.

A version number is a non-empty string which may only contain digits (0 ~ 9) and dots (.).
Dots would not be the first / last character of a version number.
There must be some digits between dots. No two dots may appear continuously.
All numbers in a version number would be less than 216.

Output
Compare the inputted version numbers and output whether first one is greater than / equals to / less than the second one. You are allowed to choose one of the following presentations:

Use positive number / zero / negative number, while zero means equal;
Use three constant distinct values;

Comparing
You are not required to implement the algorithm described in this section. Your submission is valid as long as it result the same output with this algorithm.

Version numbers are some decimal numbers joined by dots. We first split the two version numbers to arrays of numbers;
Padding the ending of arrays with zeros to make them have same length;
Compare from the first item to the last one:

If the two array items different, the greater number means greater version number
If they are the same, continue to compare the following items;
If all items in the array are equal, the two versions are equal.

Testcases
version1  version2  result
2         1         >
1.0.0     1         =
1.0       1.0.0     =
1.2.42    1.2.41    >
1.1.56789 1.2.0     <
1.10      1.2       >
1.20      1.150     <
18.04     18.4      =
7.010     7.8       >
1.0.0.1.0 1.00.00.2 <
00.00.01  0.0.0.1   >
0.0.1     0.1       <
42.0      4.2.0     >
999.999   999.999.1 <
2018.08.1 2018.08   >

Python 2, 84 79 76 bytes

lambda*l:cmp(*map(lambda v:map(int,v.split('.')+[0]*len(`l`))[:len(`l`)],l))

Try it online!

Outputs -1,0,1 for <,=,>


Mode length of a sentence The task is simple. You are given a string with alphabetical words (say "Hello world, this are tests"). You have to return the mode of the lengths of words in the string. In this case, output is 5, as it's the most often length of words in the string.
Definition of an alphabetical word (for this challenge): a string that consists of a-zA-Z only.
Sample I/O:
Constraints: Input has atleast one word, and a unique mode. Max. length is provided in last test case. Also, the string would be a single line, no newline chars.
(In = Out format)
"Hello world, this are tests"                     =  5
"Hello    world, this... are tests"               =  5
"I"                                               =  1
"Let's box (ง︡'-'︠)ง"                               =  3
"Writing some ✍(◔◡◔) program"                   =  7
"the-the-the-then"                                =  3
"Gooooooooogle is an app"                         =  2
"()<>a+/sentence$#@(@with::many---_symbols{}|~~"  =  4
"anot_her test actually"                          =  4

The unicode tests are optional.
1000 words string = 5 (Password: PXuCdMj5u65vwst)
This is a code-golf, so fewest bytes will win!

05AB1E, 10 9 7 bytes
-1 byte inspired by Jonathan Allans Jelly answer.
-2 bytes thanks to Kevin Cruijssen!
Input is a list of characters.
aγO0K.M

Try it online!
Commented:
aγO0K.M     implicit input       ["a","b"," ","c","d"," ","e","."]

a           is_alpha (vectorizes)[1, 1, 0, 0, 1, 1, 0, 1, 0]
 γ          split into chunks of equal elements
              [[1, 1], [0, 0], [1, 1], [0], [1], [0]]
  O         sum the lists        [2, 0, 2, 0, 1, 0]
   0K       remove 0's
     .M     mode                 2

            implicit output      2

a is implemented as Regex.match?(~r/^[a-zA-Z]+$/, to_string(x)), which should be equivalent to the challenge specification.
I feel like there has to be a shorter way to remove 0s from a list than ʒĀ}.


Minimum of a Polynomial in Python What is the shortest amount of code that can find the minimum of an inputted polynomial? I realize that you can import packages like Numpy and others, but using only user defined functions, what is the shortest way to do this? For example, if 6x6 + 4x3-12 is entered (ignore parsing issues), what would be the shortest amount of code to find the minimum value?

Python - 202 Bytes

D=lambda p:[i*p[i]for i in range(1,len(p))]
A=lambda p,x:p>[]and p[0]+x*A(p[1:],x)
def N(p):f=D(p);s=D(f);x=1.;y=-x;exec'x-=A(f,x)/A(s,x);y-=A(f,y)/A(s,y);'*99;return A(p,x),A(p,y)
print min(N(input()))

11 bytes saved due to @xnor.

Input is taken from stdin, and is expected to be in the following format: [x0, x1, x2, ...]. For example, the sample in the problem description would be entered as [-12, 0, 0, 4, 0, 0, 6].

Functions

D - Calculates the derivative of a polynomial p.
A - Applies a polynomial p to the value x.
N - Uses Newton's Method to calculate local minima/maxima of a polynomial p.

Note: For higher order polynomials, there may be several local minima. In these cases, this function is not guaranteed to find the global minimum.

Sample Usage

$ echo [-12, 0, 0, 4, 0, 0, 6] | python poly-min.py
-12.6666666667


Is this molecule polar? Disclaimer

  It is bad practice to draw out your molecules in 2 dimensions because that is not how they are. I chose to do this in 2D because it is easier to explain.

  Note that the bond angles are wrong too: the angle in CH4 is 109.5°, not 90° as I said and the bond angle in NH4 is 107°. BHCl2 does have a bond angle of 120° and is 2D, however.

Challenge

Given the formula of a simple molecule as input, output a truthy value if the molecule is polar (asymmetrical) or a falsey value if the molecule is non-polar (symmetrical).

Determining Polarity

To determine whether a molecule is polar or not, we will have to look at its shape. For the purposes of this challenge, we will assume that molecules are 2D.

To demonstrate how to determine the polarity of a molecule, let us use three examples: methane (CH4), ammonia (NH3) and BHCl2.

CH4

Firstly, lets take the centre molecule, carbon. Carbon is in group four of the periodic table so it has four outer shell electrons, as shown below:

Now, we add the hydrogen atoms (each hydrogen atom supplies its own electron to make a pair):

Since there are no lone pairs of electrons, we can draw it with 90° between each bond since all bonds repel equally:

We can now see that methane is symmetrical so it is non-polar.

NH3

Like above, we take the centre molecule, nitrogen and draw out its outer shell electrons:

Adding the hydrogen atoms, we notice that there is a lone pair of electrons:

Since the lone pair is closer to the atom, it repels more than a bonding pair, so the angle between the bonds is smaller:

Evidently, NH3 is not symmetrical, so it is polar.

BHCl2

Taking boron as the centre molecule, we draw the three outer electrons:

We then add the hydrogen and the chlorines:

There are no lone pairs, so the bonds repel equally, forming an angle of 120°:

Although, the shape is symmetrical, the hydrogen atom makes the molecule asymmetrical, so BHCl2 is polar.

Rules

Built-ins which access molecule information are disallowed. You may access periodic table data using built-ins or without adding the file to your byte count. This data may be stored however you wish.

Input will only ever be a valid simple molecule: a single central atom (p-block element) which comes first in the formula and up to eight outer atoms (hydrogen, fluorine, chlorine, bromine, iodine, astatine) which only use single bonds.

You will never get a polyatomic ion or a molecule with co-ordinate (dative covalent) bonds as input. For example, with NH4, there would be a single unpaired electron, so the only for NH4 to form a stable molecule would be to lose the extra electron and become an ion (a polyatomic ion, since there is more than one atom in the ion).

If there are multiple lone pairs, they have to be spaced as far as possible from each other. For example, two lone pairs will have to be opposite from each other.

If there are non-polar and polar isomers of a molecule (e.g. SiF2Cl2) you should assume the molecule is non-polar.

Examples

Input -> Output
OH2 -> Falsey
CCl4 -> Falsey
OF4 -> Truthy
CH4 -> Falsey
NH3 -> Truthy
BHCl2 -> Truthy

Winning

Shortest code in bytes wins.

Python 3, 296 bytes

import P,re,itertools
r="[A-Z][a-z]?"
f=re.findall(r,re.sub("(%s)(\d)"%r,lambda g:g.group(1)*int(g.group(2)),input()))
print(all(any(any(q[:len(q)//i]*i==q for i in range(2,len(q)))for q in[j[i:]+j[:i]for i in range(len(j))])<1for j in itertools.permutations(f+['e']*-(len(f)-P.a[f.pop(0)]>>1))))

Try it online!

-29 bytes thanks to ovs

Prints False or True.

This requires a dict of all p-block element symbols to the number of valence electrons they have. H is not necessary since it will only be one of the surrounding atoms. The dict is stored in P.py as a variable named a (it's written in the input for TIO and then placed into a Python file by the header)


Reverse a string by chunks Your task is to write a program which, given a number and a string, splits the string into chunks of that size and reverses them.
Rules
Your program will receive a positive integer n, as well as a string s with length at least one consisting of only printable ASCII (not including whitespace). The string should then be split into chunks of length n, if the length of the string isn't divisible by n any leftover at the end should be considered its own chunk. Then, reverse the order of the chunks and put them together again.
Test Cases
n   s           Output

2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef

This is code-golf, so you should aim for as few bytes as possible.

Jelly, 2 bytes

sṚ

A full program that prints the result.

Try it online!

How?

sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc


Is it possible to make a clamp function shorter than a ternary in JS? Imagine this short function to clamp a number between 0 and 255:

c = n => n > 0 ? n < 255 ? n : 255 : 0

Is this the shortest possible version of a clamp function with JavaScript (without ES.Next features)?

P.S: Not sure if it's relevant but, the 0 and 255 are not random, the idea is to clamp a number as an 8-bit unsigned integer.

20 bytes
For reference, this is the original version without whitespace and without naming the function:

n=>n>0?n<255?n:255:0

Try it online!

19 bytes
We can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether \$n\$ is greater than \$255\$. Because of the bitwise operation, this will however fail for \$n\ge 2^{32}\$.

n=>n<0?0:n>>8?255:n

Try it online!

19 bytes
This one returns \$false\$ instead of \$0\$ but works for \$n\ge 2^{32}\$.

n=>n>255?255:n>0&&n

Try it online!

18 bytes
By combining both versions above, we end up with a function that works for \$256-2^{32}\le n<2^{32}\$ and returns \$false\$ for \$n<0\$.

n=>n>>8?n>0&&255:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    n > 0 &&  //   return false if n is negative
    255       //   or 255 otherwise
  :           // else:
    n         //   return n unchanged

(This is a fixed revision of the code proposed by @ValueInk in the comments.)

17 bytes
We can go a step further by limiting the valid input range to \$-2^{24}< n\le 2^{24}\$:

n=>n>>8?-n>>>24:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    -n >>> 24 //   non-arithmetic right-shift of -n by 24 positions
  :           // else:
    n         //   return n unchanged


How much do I have to write? Writing out numbers is among the Hello worlds of programming, often the numbers 1-10.
I want to write out many numbers! Many, Many numbers. But how many numbers do I have to write?
Task
Given an integer input, give a number as output that would give me the number of digits that would be in a string containing all integer numbers in the range from 0 to the input, inclusive. The negation identifier ("-") counts as a single character.
Example I/Os
Input: 8
Written out: 0,1,2,3,4,5,6,7,8
Output: 9
Input: 101
written out: 0,1,2,3....,99,100,101
Output: 196
Input: 102
written out: 0,1,2,3....,100,101,102
output: 199
Input -10
Written out: 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
output: 22
This is a code-golf. The lowest number of bytes wins!

05AB1E, 3 bytes

Code:

ÝJg

Uses the CP-1252 encoding. Try it online!

Explanation:

Ý     # Range [0 .. input]
 J    # Join into one string
  g   # Get the length of the string


Draw an ASCII Checkerboard Summary

Inspired by the recent popularity of ASCII art challenges, this challenge's purpose is to draw an ASCII checkerboard, like one on which Chess can be played.

Write a program that takes a positive integer n as an argument, in stdin, or as user input, and output an checkerboard with nxn squares, along with a border that is 1 character thick.

Each square should be 2x2 characters. The squares should follow the normal alternating white-black (white first, as in top-left corner) pattern of a checkerboard. White squares should be made out of space () characters, and black squares should be made out of pound (#) characters.

The border should be made out of dashes (-) with a plus (+) on the border or perpendicular point of a square.

Input

Positive integer in representing the number of squares (dimensions in squares) to draw in the checkerboard, with each square being 2x2 characters.

Example Results

n=2

+--+--+
|  |##|
|  |##|
+--+--+
|##|  |
|##|  |
+--+--+

n=3

+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
|##|  |##|
|##|  |##|
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+

n=4

+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+

... and so on.

Notes

Trailing spaces and new lines are acceptable.
You may write either an entire program or a function.
No leading spaces.
Your program should display correct results for n=15.
For less-known esoteric languages and similar, provide a link to the language.
n=0 should produce +. (optional, but highly recommended and encouraged.)
Shortest code in bytes wins, as this is code golf.


Tri-interquine - Three programs that output each other in a loop Related: Interquine

Program A outputs program B's code when run, and B outputs C's source, and C outputs A's source.

This time you can't exchange two characters and exchange again :)

Requirements:

Only one language across all programs
Standard loopholes restrictions apply
All programs are different. One program that outputs itself does not qualify. Two that output each other does not qualify, too.
All programs are non-empty, or at least 1 byte in length.
There's nothing to read because stdin is connected to /dev/null (You can abuse this rule if you can). Output goes to stdout.
Do not use functions that generate random results.

Additional:

Give explanations if possible

Score is length of the shortest one (can you generate a long program from a short one?). Please write the length of all programs and highlight the smallest number. Trailing newline does not count. Lowest score wins.

Python 3, 50 bytes

s='s=%r;print(s%%(s,%i*2%%7))';print(s%(s,1*2%7))

Try it online!

The last expression goes from 1*2%7 to 2*2%7 to 4*2%7 then back to 1*2%7.


Calculate the square of an integer with restrictions The Puzzle

You have to write a program or function p(n) that returns the square of what is entered into it and you may assume that the input is a non-negative integer. Put in simpler terms, return n2.

Rules

You are not allowed to use * or / (or any other power or square root operator, such as POW or SQRT, if your language contains such functions)
You may not use a loop, or use a constructions that is similar to a loop.  Example of loop like constructions are GOTO and recursion.

Example

Function p(n)
Dim r()
ReDim r(n)
p = Len(Join(r, Space(n)))
End Function

Be creative and (ab)use the functions and features given to  you by your language of choice.

*edit

Loop like structures are loops that allow you to repeat 1 or more instructions

-if you could add an stdout "1" to your code and you would end up with repeating that output n times, it will count as a loop

CJam, puts on his glasses
q~33c

(*_*)

(*_")>⌐■-■

(⌐■_■)

"]sG>4%,)

Input via STDIN
Try the code here
Note that * in the code is not used as multiplying, but as a join operator
Also note that the cool part of the code is not just string, half of it is actually the code involved in finding the square. So.. DEAL WITH IT
This will help you in dealing with it:
q~33c                    "Read the number and put ASCII character 33 on stack with it"
(                        "Decrease it to get ASCII code 32 character, which is a space";
 *_                      "Repeat the space input number times and make another copy";
   *                     "Put that many spaces in between each space. Now we have";
    )                    "n*n spaces string. We take out the last space out of it";
(                        "Decrement the space to get ASCII 31 character";
 *                       "Fill the n*n - 1 spaces with that to get 2*n*n - 3";
  _                      "string. Then copy it again.";
   ")>⌐■-■               "Put the sun glasses in";
(⌐■_■)                   "Wear the sun glasses. Be cool.";
"]s                      "Add everything to a single string of 4*n*n - 6 + 16"
   G>                    "length. Remove first 16 characters";
     4%                  "Take every 4th character from that string to get n*n - 1"
       ,)                "length string. Take length and increment to get n*n";


Identify arborally satisfied point sets An arborally satisfied point set is a 2D set of points such that, for any axis-aligned rectangle that can be formed using two points in the set as opposite corners, that rectangle contains or touches at least one other point.  Here is an equivalent definition from Wikipedia:

  A point set is said to be arborally satisfied if the following property holds: for any pair of points that do not both lie on the same horizontal or vertical line, there exists a third point which lies in the rectangle spanned by the first two points (either inside or on the boundary).

The following image illustrates how the rectangles are formed.  This point set is NOT arborally satisfied because this rectangle needs to contain at least one more point.

In ASCII art, this point set can be represented as:

......
....O.
......
.O....
......

A slight modification can make this arborally satisfied:

......
....O.
......
.O..O.
......

Above, you can see that all rectangles (of which there is only one) contain at least three points.

Here is another example of a more complex point set that is arborally satisfied:

For any rectangle that can be drawn spanning two points, that rectangle contains at least one other point.

The Challenge

Given a rectangular grid of points (which I represent with O) and empty space (which I represent with .), output a truthy value if it is arborally satisfied, or a falsey value if it is not.  This is code-golf.

Additional rules:

You can choose to have the characters O and . swapped out with any other pair of printable ASCII characters.  Simply specify which character mapping your program uses.
The grid will always be rectangular.  A trailing newline is allowable.

More Examples

Arborally satisfied:

.OOO.
OO...
.O.OO
.O..O
....O

..O..
OOOO.
...O.
.O.O.
...OO

O.O.
..O.
OOOO
.O.O
OO..

...
...
...

...
..O
...

O.....
O.O..O
.....O

OOO.OO

Not Arborally Satisfied:

..O..
O....
...O.
.O...
....O

..O..
O.OO.
...O.
.O.O.
...OO

O.....
..O...
.....O

Snails, 29 30 39 bytes
!{t\Oo\.+c\.,\O!{t\O{w!(.,~}2

It works by tracing out 2 sides of the rectangle, and then checking whether there is some square containing an O such that traveling in a straight line from the square in 2 of the cardinal directions would result in hitting a side of the rectangle.
Prints the maximum of 1 and the grid's area if the input is "arborally satisfied"; otherwise 0.


Convert a string containing integers to list of integers What is the shortest way to convert a string containing integers separated by spaces to a list of integers?

input : "-3 1 5 8 10"
output : [-3, 1, 5, 8, 10]

I regularly face this situation and I wanted to know if there is a better way than (24 bytes):

list(map(int,s.split()))

Using map is way shorter than any of the ways I mentioned. You should do that.

Instead of calling list(...), you should use [*...] (21 bytes):

[*map(int,s.split())]

Or even better, if you switch to python 2, map will always return a list. (18 bytes):

map(int,s.split())

Try it online!

Original Post:

The straightforward way is going to be 26 bytes

[int(n)for n in s.split()]

Try it online!

However, if a tuple is acceptable instead of a list, we could use a trick to shave one byte off leaving us with 25 bytes

eval(",".join(s.split()))

Try it online!

This can be shortened even more with the replace function (24):

eval(s.replace(' ',','))

Try it online!

and even more with iterable unpacking (22):

eval(s.replace(*" ,"))

Try it online!

If you truly need a list, you can wrap it in [*...]. This is still shorter than the straightforward way by 1 byte:

[*eval(s.replace(*" ,"))]


Squaring Off (fit to smallest possible square) Intro
More complex than A square of text since this requires padding and input has unknown data type.
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's tenth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
Write a program/function that will reshape a given string or numeric list into the smallest square that will contain all the elements of the input, padding with additional elements if necessary. The pad element should be the default fill element for the given data type, or any one element of your choice. The elements of the square should be in such order that flattening it will give the original order of input data (with trailing padding elements, if any).
Test cases
[1,2,3,4] →
[[1,2],
 [3,4]]

[1,2,3,4,5] →
[[1,2,3],
 [4,5,0],
 [0,0,0]]

"Dyalog APL" →
[["Dyal"],       [["D","y","a","l"],
 ["og A"],   or   ["o","g"," ","A"],
 ["PL  "],        ["P","L"," "," "],
 ["    "]]        [" "," "," "," "]]

[100] →
[[100]]

[] →
your language's closest equivalent to an empty matrix, e.g. [] or [[]]

MATL, 12 9 bytes

Saved three bytes thanks to Luis. he instead of UGwewe, but adding a t in the beginning.

tnX^Xkthe

Try it online!

This returns the results, but transposed compared to the result in OPs post (which is OK).

Explanation:

This works the same way for both numeric and string input, as MATL treats them the same way.

Assume the input is 'Dyalog APL'

                % Implicit: Take string or numeric array as input
                % Stack: 'Dyalog APL'
t               % Duplicate
                % Stack: 'Dyalog APL'
                %        'Dyalog APL'
 n              % Number of elements in last element.
                % Stack: 'Dyalog APL'
                %        10
  X^            % Take the square root of the number of elements
                % Stack: 'Dyalog APL'
                % Stack: 3.16...
    Xk          % Ceil last number
                % Stack: 'Dyalog APL'
                %        4
      t         % Duplicate element
                % Stack: 'Dyalog APL'
                %        4
                %        4
       h        % Concatenate the last to elements horizontally
                % Stack: 'Dyalog APL'
                %        4  4
        e       % reshape into 4 rows, and 4 columns. Pads the input with zeros or spaces
                % if necessary.
                % Stack: (Note that there's a trailing column not shown below)
                %        DoP
                %        ygL
                %        a
                %        lA

This outputs nothing for empty input, which happens to be way MATL outputs empty matrices / strings.


Implement PCRE in your language. Note: After trying this myself, I soon realized what a mistake this was. Therfore, I am modifying the rules a bit.

The minimum required functionality:

Character classes (., \w, \W, etc.)
Multipliers (+, *, and ?)
Simple capture groups

Your challenge is to implement PCRE in the language of your choice subject to the following conditions:

You may not use your language's native RegEx facilities in any way. You may not use a 3rd party RegEx library either.
Your entry should implement as much of the PCRE spec. as possible.
Your program should accept as input, 2 lines:

  the regular expression
  the string input to match against

Your program should indicate in its output:

  Whether the RegEx matched anywhere in the input string
  The results of any capturing groups

The winner shall be the entry that implements as much of the spec. as possible. In case of a tie, the winner shall be the most creative entry, as judged by me.

Edit: to clarify a few things, here are some examples of input and expected output:

Input:

^\s*(\w+)$
         hello

Output:

Matches: yes
Group 1: 'hello'

Input:

(\w+)@(\w+)(?:\.com|\.net)
sam@test.net

Output:

Matches: yes
Group 1: 'sam'
Group 2: 'test'

Python

Since implementing full PCRE is too much I implemented only an essential subset of it.

Supports |.\.\w\W\s+*(). Input regexp must be correct.

Examples:

$ python regexp.py
^\s*(\w+)$
   hello
Matches:     hello
Group 1 hello

$ python regexp.py
(a*)+
infinite loop

$ python regexp.py
(\w+)@(\w+)(\.com|\.net)
sam@test.net
Matches:  sam@test.net
Group 1 sam
Group 2 test
Group 3 .net

How it works:

For detailed theory read this Introduction to Automata Theory, Languages, and Computation.

The idea is to convert the original regular expression into a nondeterminist finite automata (NFA). Actually, PCRE regular expressions are at least context free grammars for which we need push-down automata, but we'll limit ourselves to a subset of PCRE.

Finite automatas are directed graphs in which nodes are states, edges are transitions and each transition has a matching input. Initially you start from a start node, predefined. Whenever you receive an input that matches one of the transition you take that transition  to a new state. If you reached a terminal node it is called that automata accepted input. In our case input is a matching function that returns true.

They are called nondeterminist automata because sometimes there are more matching transitions that you can take from the same state. In my implementation all transition to the same state must match the same thing, so I stored the matching function together with the destination state (states[dest][0]).

We transform our regexp to a finite automata using building blocks. A building block has a start node (first) and an end node (last) and matches something from the text (possible empty string).

The simplest examples include

matching nothing: True (first == last)
matching a character: c == txt[pos] (first == last)
matching end of string: pos == len(txt)(first == last`)

You will also need the new position in text where to match next token.

More complicated examples are (capital letters stand for blocks).

matching B+:

create nodes: u, v (matching nothing)
create transitions: u -> B.first, B.last -> v, v -> u
when you get to node v you already matched B. Then you have two options: go further, or try to match B again.

matching A|B|C:

create nodes: u, v (matching nothing)
create transitions: u -> A.first, u -> C.first, u -> C.first,
create transitions: A->last -> v, B->last -> v, C->last -> v,
from u you can go to any block

All regexp operators can be transformed like this. Just give a try for *.

The last part is to parse the regexp which requires a very simple grammar:

 or: seq ('|' seq)*
 seq: empty
 seq: atom seq
 seq: paran seq
 paran: '(' or ')'

Hopefully implementing a simple grammar (I think is LL(1), but correct me if I'm wrong) is much easier than building an NFA.

Once you have the NFA you need to backtrack until you reach terminal node.

Source code (or here):

from functools import *

WORDCHAR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_'

def match_nothing(txt, pos):
  return True, pos

def match_character(c, txt, pos):
  return pos < len(txt) and txt[pos] == c, pos + 1

def match_space(txt, pos):
  return pos < len(txt) and txt[pos].isspace(), pos + 1

def match_word(txt, pos):
  return pos < len(txt) and txt[pos] in WORDCHAR, pos + 1

def match_nonword(txt, pos):
  return pos < len(txt) and txt[pos] not in WORDCHAR, pos + 1

def match_dot(txt, pos):
  return pos < len(txt), pos + 1

def match_start(txt, pos):
  return pos == 0, pos

def match_end(txt, pos):
  return pos == len(txt), pos

def create_state(states, match=None, last=None, next=None, name=None):
  if next is None: next = []
  if match is None: match = match_nothing

  state = len(states)
  states[state] = (match, next, name)
  if last is not None:
    states[last][1].append(state)

  return state

def compile_or(states, last, regexp, pos):
  mfirst = create_state(states, last=last, name='or_first')
  mlast = create_state(states, name='or_last')

  while True:
    pos, first, last = compile_seq(states, mfirst, regexp, pos)
    states[last][1].append(mlast)
    if pos != len(regexp) and regexp[pos] == '|':
      pos += 1
    else:
      assert pos == len(regexp) or regexp[pos] == ')'
      break

  return pos, mfirst, mlast

def compile_paren(states, last, regexp, pos):
  states.setdefault(-2, [])   # stores indexes
  states.setdefault(-1, [])   # stores text

  group = len(states[-1])
  states[-2].append(None)
  states[-1].append(None)

  def match_pfirst(txt, pos):
    states[-2][group] = pos
    return True, pos

  def match_plast(txt, pos):
    old = states[-2][group]
    states[-1][group] = txt[old:pos]
    return True, pos

  mfirst = create_state(states, match=match_pfirst, last=last, name='paren_first')
  mlast = create_state(states, match=match_plast, name='paren_last')

  pos, first, last = compile_or(states, mfirst, regexp, pos)
  assert regexp[pos] == ')'

  states[last][1].append(mlast)
  return pos + 1, mfirst, mlast

def compile_seq(states, last, regexp, pos):
  first = create_state(states, last=last, name='seq')
  last = first

  while pos < len(regexp):
    p = regexp[pos]
    if p == '\\':
      pos += 1
      p += regexp[pos]

    if p in '|)':
      break

    elif p == '(':
      pos, first, last = compile_paren(states, last, regexp, pos + 1)

    elif p in '+*':
      # first -> u ->...-> last -> v -> t
      # v -> first (matches at least once)
      # first -> t (skip on *)
      # u becomes new first
      # first is inserted before u

      u = create_state(states)
      v = create_state(states, next=[first])
      t = create_state(states, last=v)

      states[last][1].append(v)
      states[u] = states[first]
      states[first] = (match_nothing, [[u], [u, t]][p == '*'])

      last = t
      pos += 1

    else:  # simple states
      if p == '^':
    state = create_state(states, match=match_start, last=last, name='begin')
      elif p == '$':
    state = create_state(states, match=match_end, last=last, name='end')
      elif p == '.':
    state = create_state(states, match=match_dot, last=last, name='dot')
      elif p == '\\.':
    state = create_state(states, match=partial(match_character, '.'), last=last, name='dot')
      elif p == '\\s':
    state = create_state(states, match=match_space, last=last, name='space')
      elif p == '\\w':
    state = create_state(states, match=match_word, last=last, name='word')
      elif p == '\\W':
    state = create_state(states, match=match_nonword, last=last, name='nonword')
      elif p.isalnum() or p in '_@':
    state = create_state(states, match=partial(match_character, p), last=last, name='char_' + p)
      else:
    assert False

      first, last = state, state
      pos += 1

  return pos, first, last

def compile(regexp):
  states = {}
  pos, first, last = compile_or(states, create_state(states, name='root'), regexp, 0)
  assert pos == len(regexp)
  return states, last

def backtrack(states, last, string, start=None):
  if start is None:
    for i in range(len(string)):
      if backtrack(states, last, string, i):
    return True
    return False

  stack = [[0, 0, start]]   # state, pos in next, pos in text
  while stack:
    state = stack[-1][0]
    pos = stack[-1][2]
    #print 'in state', state, states[state]

    if state == last:
      print 'Matches: ', string[start:pos]
      for i in xrange(len(states[-1])):
    print 'Group', i + 1, states[-1][i]
      return True

    while stack[-1][1] < len(states[state][1]):
      nstate = states[state][1][stack[-1][1]]
      stack[-1][1] += 1

      ok, npos = states[nstate][0](string, pos)
      if ok:
    stack.append([nstate, 0, npos])
    break
      else:
    pass
    #print 'not matched', states[nstate][2]
    else:
      stack.pop()

  return False

# regexp = '(\\w+)@(\\w+)(\\.com|\\.net)'
# string = 'sam@test.net'
regexp = raw_input()
string = raw_input()

states, last = compile(regexp)
backtrack(states, last, string)


Ain't no thang! ...or is it? Introduction

Street talk can be really difficult to understand, in particular to programmers, who aren't known to be very streetwise.

It is your job to create an interpreter to help us all survive in the urban environment.

Challenge

Given an English sentence as input, create a program or a function that determines whether the outcome of the sentence is positive or negative.

The sentence will contain 0 to 2 negative words. As any programmer knows, a double negative results in a positive. Therefore, your code must output or return a truthy/falsey value according to the following rule:

No negative words  -> truthy
One negative word  -> falsey
Two negative words -> truthy

The list of negative words:

no, not, none
Anything ending in n't
never, neither, nor
nobody, nothing, nowhere

There is one edge case. Whenever a sentence begins with No,, that word isn't treated as a negative word when determining the result (it does count towards the number of negative words so there can be just one more).

The sentence will follow basic grammar rules (capitalization, punctuation) and will only contain words that can be found from a dictionary (luckily, this doesn't invalidate the question title). The sentence won't contain any proper nouns (sorry, Dr. No, you're out).

Test cases

Truthy:

Yes.
It's noon.
Hello, World!
What is this?
Ain't no thang!
Never say never.
No, it's noon now.
Neither me nor you.
I didn't do nothing!
No, I am your father.
A non-alcoholic drink.
I can't get no satisfaction.
All your base are belong to us.

Falsey:

No.
No, no!
Not today.
Neither am I.
Don't do that!
That's no moon!
And none survived.
Is this not my car?
No man is an island.
Nosebleeds are no fun.
Nothing compares to you.
That's a no, I'm afraid.
No, I am not your mother.

The irony here, of course, is that some of these should be interpreted differently. But hey, you can't fault the speaker for not conforming to our logic.

Rules

Standard loopholes are forbidden. This is code-golf, so be concise!

Retina, 63 bytes

No,

Mi`\bn(e(ith|v)er|o(|body|ne|r|t|thing|where))\b|n't\b
0|2

Try it online!

Explanation

No,

Remove No, from the input. Due to the capitalisation rules, this can only appear at the beginning of the input, so we don't need an explicit ^.

Mi`\bn(e(ith|v)er|o(|body|ne|r|t|thing|where))\b|n't\b

Count the number of matches of the case-insensitive regex after the `. It just matches all the relevant words, where I've extracted common prefixes/suffixes with the alternatives.

0|2

Count 0 or 2s, so we turn even counts into 1 and odd counts into 0.


Shortest program that displays a red 3D cube Write the shortest program you can that displays a red 3D cube.

Rules:

The cube must be red, have 6 rendered sides, and be displayed in 3D.
Your program cannot load any textures.
More than 1 side must be visible.
The result does not need to be rotatable.

T-SQL, 168 chars (but no OpenGL)
Decidedly not using OpenGL or Direct3D because there is absolutely no way to do that in SQL. I think I have a pretty nice little cube, anyway.
RAISERROR('
      @@@
   @@@@@@@@@
@@@@@@@@@@@@@@@
x@@@@@@@@@@@@&&
xxx@@@@@@@@&&&&
xxxxx@@@&&&&&&&
xxxxxx&&&&&&&&&
 xxxxx&&&&&&&
   xxx&&&&
     x&&
',15,1)

Exploiting the fact that errors of high severity are raised in red:


Days in indexed month This simple challenge is very similar to this one: How many days in a month? The only difference is you yield the number of days in a month given the index of the month instead of its name.

The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...

INPUT: Integer indicating the month; 1 through 12. (Optionally, you can accept 0-indexed month numbers from 0 to 11.)

OUTPUT: Number of days in that month. February can return 28 or 29.

Complete I/O table:

INPUT   :   OUTPUT
  1          31
  2          28 or 29
  3          31
  4          30
  5          31
  6          30
  7          31
  8          31
  9          30
 10          31
 11          30
 12          31

APL (Dyalog Unicode), 13 12 bytesSBCS

Anonymous tacit prefix function. 0-indexed. February is 29.

31-1∘=+2|7∘|

Try it online!

31- thirty-one minus…

 1∘= the equal-to-one'ness…

  + plus…

   2| the two-mod of…

    7∘| the seven-mod'ness

  The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...

This solution implements the following mathematical pattern:

$$f(x)=31-[x=1]-\big((x\mod 7)\mod 2\big)$$

or

$$f(x)=31-x-\left[x=1\right]+7\left\lfloor\frac{x}7\right\rfloor+2\left\lfloor x-7\left\lfloor\frac{x}7\right\rfloor\over2\right\rfloor$$


Generate Sexy Primes Sexy Primes are pairs of numbers \$(n, n+6)\$ such as \$n\$ and \$n+6\$ are both prime
You need to create a function which will take an integer, check for sexy primes from 0 to that integer, and return an array of arrays.
For example, listSexy(30) must return [[5,11], [7,13], [11,17], [13,19], [17,23], [23,29]] or some equivalent.
This is code-golf so the program with the shortest bytecount wins!

MATLAB 32

i=1:n;i(isprime(i)&isprime(i+6))

n is your number


Stacked digit staircases Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below.

The first row begins with 11 0s, the second row with 10 1s, third with nine 2s and so on down the the tenth row with two 9s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of 0s occurs, the digits after it are always 9s.

Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0).

The first \$11\times10\$ elements are as follows:

00000000000
11111111110
22222222211
33333333221
44444443322
55555544332
66666554433
77776655443
88877665544
99887766554

Here is an image with colored text to make the pattern more clear.

If you need to produce fewer columns/rows then you should simply crop the above text.

If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be

000000000009988
111111111100998
222222222110099
333333332211009
444444433221100
555555443322110
666665544332211
777766554433221
888776655443322
998877665544332
099887766554433
009988776655443
100998877665544

Here is an image of this text with color:

Rules

Output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
You can return a list of lines if you prefer.
You can return a 2D array of digits or list of lists of digits if you prefer.
Standard loopholes disallowed.

Shortest code wins.

Test cases

Input is taken as \$(w,h)\$ for the test cases.

1,1
0

3,2
000
111

20,1
00000000000998877665

11,10
00000000000
11111111110
22222222211
33333333221
44444443322
55555544332
66666554433
77776655443
88877665544
99887766554

15,13
000000000009988
111111111100998
222222222110099
333333332211009
444444433221100
555555443322110
666665544332211
777766554433221
888776655443322
998877665544332
099887766554433
009988776655443
100998877665544

C (gcc), 101 100 99 bytes

Saved a byte thanks to pizzapants184.
Saved a byte.

s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));}

Try it online!


Random array without repetition I was answering one challenge here and this task was part of the challenge. I've got a 73 bytes solution in javascript. But I think it is too much for a simple thing.

Challenge

Given as input two integers:

N the length of the expected array
R the interval's range starting in one: 1..R, not 0..R-1

Output in each run of your program/function one different array of length N with values between 1..R in such a way no one value occurs more than once.

You must use R-value in your code.

Restrictions

You can assume: 2 <= N <= R.

I really would like to see a javascript solution shorter than mine 73 bytes.

But of course, it is open to all languages!

If your language can not return an array, you can print all the numbers ;)

Dyalog APL, 1 byte
?

Just a builtin. Try it here.


Surround a string with "friendliness pellets" Input a String and surround it with a rounded rectangle of alternating "friendliness pellets".(0)
Sandbox

Idea originally from Lyxal.
Challenge
Given a single line non-empty String of length \$<100\$, print the string with a rounded rectangle of alternating pellets(0) around it.
The rectangle must be 11 lines in height.
The first line of the rectangle must have at least 1 pellet.
The middle line of the rectangle must be at least 13 characters long. There must be a padding of one space on each side of the text.
Strings smaller than 9 characters must be padded with spaces equally on both sides to fit the above specification.
The right side is allowed to have one extra space if the string is of even length.
The template for the output is as follows:
      00000..... 6 spaces
    0 4 spaces
  0   2 spaces
 0    1 space
0     no spaces

If the string's length is greater than or equal to 9; the first line must have \$\text{length}-8\$ pellets.
Example Input and Output
Input:

Hello World!

Output:
       0000
     0      0
   0          0
  0            0
 0              0
 0 Hello World! 0
 0              0
  0            0
   0          0
     0      0
       0000

Input

0

Output
       0
     0   0
   0       0
  0         0
 0           0
 0     0     0
 0           0
  0         0
   0       0
     0   0
       0

Input

The quick brown fox

Output
       00000000000
     0             0
   0                 0
  0                   0
 0                     0
 0 the quick brown fox 0
 0                     0
  0                   0
   0                 0
     0             0
       00000000000

Input

In this world, it's KILL or BE killed

Output
      00000000000000000000000000000
    0                               0
  0                                   0
 0                                     0
0                                       0
0 In this world, it's KILL or BE killed 0
0                                       0
 0                                     0
  0                                   0
    0                               0
      00000000000000000000000000000

Input

hi there

Output
      0
    0   0
  0       0
 0         0
0           0
0 hi there  0
0           0
 0         0
  0       0
    0   0
      0

Example code in Ruby
Try it online!
a=[4,2,1,0] # space length to create circle

str=gets.chomp;
l = str.length;
# print first line of pellets
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end

# initial pattern
for n in a do
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"

end

# display string with spaces
if l<9 then puts "0"+" "*((11-l)/2).floor + str + " "*((12-l)/2).ceil + "0" else puts "0 #{str} 0" end

#initial pattern but reversed
for n in a.reverse do
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"
end

# last line(same as first line)
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end

Scoring
This is code-golf. Shortest answer in each language wins.

Charcoal, 40 bytes
≔⌈⟦¹⁻Ｌθ⁸⟧η×η0↘↘0→↘00↓00‖ＯＯ←η‖Ｏ↓Ｊ⊘⁻⊖ηＬθ⁵θ

Try it online! Link is to verbose version of code. Explanation:
≔⌈⟦¹⁻Ｌθ⁸⟧η

Calculate the number of 0s in the top row.
×η0

Print them.
↘↘0→↘00↓00

Print the remaining 0s on the right.
‖ＯＯ←η

Reflect the additional rows of 0s to the left, by overlapping the top row of 0s onto itself.
‖Ｏ↓

Reflect the 0s downwards overlapping the middle row.
Ｊ⊘⁻⊖ηＬθ⁵θ

Calculate the position of the text and print it there. This is necessary for short strings but also avoids dealing with a Charcoal bug whereby an overlapped reflection moves the cursor to the wrong place.


Palindrome Hello, World Your task is to create a program that prints "Greetings, Planet!" exactly to the console. Seems simple enough, right? Well, here's the trick. The code must be a palindrome, meaning it reads from right to left the same as in left to right.
Standard loopholes are NOT allowed.

///, 37 bytes

Greetings, Planet!/!tenalP ,sgniteerG


Self-contained hello-world program I want a program that outputs "hello world" on console on my x86_64 based Linux computer. Yes, a complete program, not something silly that needs an interpreter or a compiler to work.

You may:

use all glibc functionality
submit a static executable
submit a dynamic executable with dependencies if you outline them
compile an ELF file
dig into the ELF format and remove all unneeded stuff
be creative and work around the ELF format

Describe here how you create and execute the program.

The shortest program wins.

This is what you had in mind? Or you want any more hacky?

EDITED(2)

Assembler (NASM) { source: 155 bytes, compiled: 384 bytes }

Source code: helloworld.nasm

global _start
_start:
write:
 mov eax, 4
 mov ebx, 1
 mov ecx, h
 mov edx, 12
 int 0x80
exit:
 mov eax, 1
 mov ebx, 0
 int 0x80
h: db 'hello world', 10, 0

Compile

$ nasm helloworld.nasm -f elf64 -o helloworld.o
$ ld helloworld.o -s -o helloworld

Execution

$ ./helloworld
hello world

Size

$ ls -al helloworld.nasm helloworld
-rw-rw-r-- 1 user user 155 Jan  5 11:08 helloworld.nasm
-rwxrwxr-x 1 user user 384 Jan  5 11:09 helloworld

Platform:

$ uname -io
x86_64 GNU/Linux
$ nasm -v
NASM version 2.09.10 compiled on Oct 17 2011


Write a 0815 interpreter I like the concept of 0815, except the interpreter on the creator's website returns an Error 404. So I decided to ask you all to help!

The Basics

0815 is based around three (3) registers and a queue. The registers are named X, Y, and Z, with X being write-only, Z being read-only, and Y being a "helper" register that can't be directly accessed. All registers start out set to 0. All numbers are in hexadecimal.

Instructions

Note: Some instructions take parameters which are formatted like }:hello: where the :hello: is the parameter. Other note: Some of the instruction descriptions are unclear, so I took some liberties with  them. (Original instructions here)

~ means the parameter is required

----------|---|--------------------------------------------
  ~Move   | < | <:8: will write 8 to X (parameter required)
----------|---|--------------------------------------------
   Swap   | x | Swap X and Y
----------|---|--------------------------------------------
  ~Label  | } | }:hello: makes a label called 'hello'
----------|---|--------------------------------------------
  Input   | | | Set X to an integer from input in
 Number   |   | hexadecimal greedily (regex: [0-9A-F]+)
----------|---|--------------------------------------------
  Input   | ! | Set X to the ASCII code of one ASCII
  ASCII   |   | character in the input
----------|---|--------------------------------------------
  Print   | % | Prints an integer stored in Z
  number  |   | (hexadecimal base)
----------|---|--------------------------------------------
  Print   | $ | Prints an ASCII char stored in Z
  ASCII   |   |
----------|---|--------------------------------------------
  Roll    |   | Rolls all registers to the left
Registers | ~ | X <- Y <- Z <- X
  Left    |   | After roll: X = Y, Y = Z and Z = X
----------|---|--------------------------------------------
  Roll    |   | Rolls all registers to the right
Registers | = | X -> Y -> Z -> X
  Right   |   | After roll: Y = X, Z = Y and X = Z
----------|---|--------------------------------------------
 ~Jump if | ^ | ^:loop: Jumps to the label 'loop' if Z is
 not zero |   | not zero
----------|---|--------------------------------------------
 ~Jump if | # | #:loop: Jumps to the label 'loop' if Z is
   zero   |   | zero
----------|---|--------------------------------------------

Queue Instructions

----------|---|--------------------------------------------
   Clear  | ? | Clears the queue
----------|---|--------------------------------------------
  Enqueue | > | Enqueue the number stored in Z
----------|---|--------------------------------------------
  Dequeue | { | Dequeue a number into X
----------|---|--------------------------------------------
          |   | Rolls the queue to the left, wrapping as
   Roll   |   | necessary. The first number becomes the
   Queue  | @ | last; second becomes first and so on. Can
   Left   |   | take a parameter to roll a certain number
          |   | of times. @:b: rolls 11 times.
----------|---|--------------------------------------------
   Roll   |   |
   Queue  | & | The opposite of @
   Right  |   |
----------|---|--------------------------------------------

Arithmetic instructions

----------|---|--------------------------------------------
   Add    | + | Z = X + Y
----------|---|--------------------------------------------
 Subtract | - | Z = X - Y
----------|---|--------------------------------------------
 Multiply | * | Z = X * Y
----------|---|--------------------------------------------
  Divide  | / | Z = X / Y
          |   | Y = remainder
----------|---|--------------------------------------------

Example programs

Hello world: (Slightly golfed)

<:48:~$<:65:~$<:6C:~$$><:6F:~$>@<:2C:~$<:20:~$<:57:~${~$<:72:~${~$<:64:~$

Cat:

}:_t:!~$^:_t:

Truth Machine:

|~}:i:%^:i:

This is code-golf, so the submission with the least bytes wins!

Pip, 321 262 248 bytes

Greatly shortened using eval and some Kolmogorov-complexity tricks.

a@:`.(:.*?:)?`z:Y0w:2**64W++v<#a{UnpWa@v^':;V("Yp57Syi7UybWb^@(b@?`[^0-9A-F]|$`)Yy57Y APOb7OzTB167O Cz7SyzSyi7SyiSyz7I2I!2l:[]7lPBz7Y3B3UDQl7z:(y+4-4*4//i)i:y%i"R2`zv:a@?"}:".p.':7`R3"POl7Lp?p5olP"R4"i)%w7z:(y"R5"FB16%w"^7"<x|!%$~=^#?>{@&+-*/"@?n)}

Try it online! (The example is the Collatz/hailstone numbers program from the language author's website.)

Notes:

Takes the 0815 code as the first command-line argument and the input as the second. Yes, it's a bit awkward (much less so on TIO, where you get separate text boxes), but Pip isn't that great at reading all of stdin.
Numbers in input must use uppercase hex digits (as per OP: matching the regex [0-9A-F]+). If, at a | instruction, the next character of input is not 0-9A-F, the read fails and causes potentially weird behavior. This means the author's even-odd program doesn't work as written... I'm not sure how he expected multiple number reads to work, but I just implemented according to what the spec said.
If a label is duplicated, a jump goes to the first one. If a label doesn't exist, a jump terminates the program.

My ungolfed version with comments:

;;; INITIALIZATION ;;;

; a is the code, analyzed with regex into a list of instructions
a @: `.(:.*?:)?`
; b is the input
; x, y, z are registers (initially three 0s)
x:y:z:0
; l is the queue (initially empty list)
; v is the instruction pointer (initially -1, but gets incremented at top of loop)
; w represents the width of the registers
w:2**64

;;; MAIN LOOP ;;;

; Loop while IP hasn't gone past last instruction
W ++v<#a {
 ; Unify n with first char of current iNstruction, p with the parameter (or nil)
 U np W a@v ^ ':

 ; If n eQuals "<": move p value into x
 InQ'<
  ; Convert p from hex and truncate to register width
  x : pFB16%w
 ; Swap x and y
 InQ'x
  Sxy
 ; Input number (in hex, uppercase only)
 InQ'| {
  ; Find index of first non-hex character in b and split at that index
  ; Unify left half with x and right with b
  U xb W b^@(b @? `[^0-9A-F]|$`)
  ; Convert x from hex and truncate to register width
  x : xFB16%w
 }
 ; Input ASCII
 InQ'!
  ; Pop 1st char of b and get ASCII code
  x : A POb
 ; Print number (in hex)
 InQ'%
  ; Output z converted to hex
  O zTB16
 ; Print ASCII
 InQ'$
  ; Output chr(z)
  O Cz
 ; Roll registers left
 InQ'~ {
  ; With three registers, a roll is just two swaps
  Sxz
  Sxy
 }
 ; Roll registers right
 InQ'= {
  Sxy
  Sxz
 }
 ; Jump (combines if-nonzero and if-zero cases)
 I nQ'^ & z | nQ'# & !z
  ; Construct the corresponding label, find its index in a, and set IP to that
  v : a @? "}:".p.':
  ; If the label doesn't exist, v becomes nil, which makes the loop condition nil,
  ; which (being falsy) exits the loop and terminates the program

 ; Clear queue
 InQ'?
  l:[]
 ; Enqueue
 InQ'>
  ; Push z to back of l
  lPBz
 ; Dequeue
 InQ'{
  ; Pop l and assign to x
  x:POl
 ; Roll queue left
 ; NOTE: doesn't work if 0 is a valid parameter for roll operation
 ; If we want to handle that case, use #p?... instead of p?... for +1 byte
 InQ'@
  ; Loop specified number of times (converted from hex), or 1 if not specified
  L p ? pFB16 1
   ; Pop (front of) l and push that value to the back of l
   l PB POl
 ; Roll queue right
 InQ'&
  L p ? pFB16 1
   ; Dequeue from back of l and push that value to (the front of) l
   l PU DQl

 ; Add (truncating as needed)
 InQ'+
  z:(x+y)%w
 ; Subtract (truncating as needed)
 InQ'-
  z:(x-y)%w
 ; Multiply (truncating as needed)
 InQ'*
  z:x*y%w
 ; Divide (truncating not needed)
 InQ'/ {
  z:x//y
  y:x%y
 }
}


Sort a list of unknown values with the least amount of comparisons In this optimization challenge you will write a program that sorts a single array by only comparing elements through asking the user on stdout to input comparison results on stdin.

The below protocol is line-based, so everytime you print to stdout or read from stdin it is assumed a newline follows. Throughout the question below it is assumed that the user (read: the scoring program) has an array it wants sorted in a 0-based indexed array called array. For technical reasons I suggest flushing after every print to stout.

As your first step your program must read the array size n from stdin.
Then, as often as you wish, you can print a < b to stdout, with two integers 0 <= a, b < n. Then the user will enter 1 in stdin if array[a] < array[b], and 0 otherwise.
Finally, once your program is convinced it has correctly deduced the order of the array, it must print a ... to stdout, where ... is a space separated list of integers indicating the order. So if your program outputs a 3 0 1 4 2 it means your program has deduced

array[3] <= array[0] <= array[1] <= array[4] <= array[2]

Note that your program never knew the contents of array, and never will.

You can only ask for < on stdin to sort the array. You can get other comparison operations by these equivalencies:

a > b        b < a
a <= b       !(b < a)
a >= b       !(a < b)
a != b       (a < b) || (b < a)
a == b       !(a < b) && !(b < a)

Finally, since your program interacts with the scoring program on stdout, print debug information to stderr.

Your program will be scored using the following Python program:

from __future__ import print_function
from subprocess import Popen, PIPE
import sys, random

def sort_test(size):
    array = [random.randrange(0, size) for _ in range(size)]
    pipe = Popen(sys.argv[1:], stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True)
    print(str(size), file=pipe.stdin); pipe.stdin.flush()
    num_comparisons = 0
    while True:
        args = pipe.stdout.readline().strip().split()
        if args and args[0] == "a":
            answer_array = [array[int(n)] for n in args[1:]]
            if list(sorted(array)) != answer_array:
                raise RuntimeError("incorrect sort for size {}, array was {}".format(size, array))
            return num_comparisons
        elif len(args) == 3 and args[1] == "<":
            a, b = int(args[0]), int(args[2])
            print(int(array[a] < array[b]), file=pipe.stdin); pipe.stdin.flush()
            num_comparisons += 1
        else:
            raise RuntimeError("unknown command")

random.seed(0)
total = 0
for i in range(101):
    num_comparisons = sort_test(i)
    print(i, num_comparisons)
    total += num_comparisons
print("total", total)

You score your program by typing python score.py yourprogram. The scoring is done by having your program sort one random array of each size 0 to 100 and counting the amount of comparisons your program asks for. These random arrays can have duplicates, your algorithm must be able to handle equal elements. In the event there are duplicates, there are no requirements on the order of the equal elements. So if the array is [0, 0] it doesn't matter if you output a 0 1 or a 1 0.

You may not optimize specifically for the particular arrays the scoring program generates. I may change the RNG seed at any point in time. Answers using built-in sorting algorithms are permitted to be posted for interest's sake, but are non-competing.

Program with lowest score wins.

Python, score 23069

This uses the Ford–Johnson merge insertion sorting algorithm.

from __future__ import print_function
import sys

def less(x, y):
    print(x, '<', y)
    sys.stdout.flush()
    return bool(int(input()))

def insert(x, a, key=lambda z: z):
    if not a:
        return [x]
    m = len(a)//2
    if less(key(x), key(a[m])):
        return insert(x, a[:m], key) + a[m:]
    else:
        return a[:m + 1] + insert(x, a[m + 1:], key)

def sort(a, key=lambda z: z):
    if len(a) <= 1:
        return a
    m = len(a)//2
    key1 = lambda z: key(z[-1])
    b = sort([insert(x, [y], key) for x, y in zip(a[:m], a[m:2*m])], key=key1)
    if len(a) % 2:
        b += [[a[-1], None]]
    for k in range(m, len(a)):
        l, i, (x, y) = max((-i.bit_length(), i, t) for i, t in enumerate(b) if len(t) == 2)
        b[:i + 1] = insert([x], b[:i], key=key1) + [[y]]
    if len(a) % 2:
        b.pop()
    return [x for x, in b]

print('a', ' '.join(map(str, sort(range(int(input()))))))


Different number, same weight Background

The Hamming weight of an integer is the number of ones in its binary representation. For this challenge, integers are represented with 32 bits, and they are unsigned.

Challenge

Given an integer between 0 and 2^32-1 (non-inclusive), output a different integer within the same range, and also with the same Hamming weight.

Examples

Input (Decimal) | Input (Binary) | Hamming weight | Possible output (Decimal)
       46       |   0b0010 1110  |       4        |      15
       12       |   0b0000 1100  |       2        |      3
        1       |   0b0000 0001  |       1        |      2
        3       |   0b0000 0011  |       2        |      6
      2^31      |   0b1000....0  |       1        |      1
      2^31+2    |   0b1000...10  |       2        |      3
      2^32-5    |   0b1111..011  |       31       |      2^31-1
      2^32-2    |   0b1111....0  |       31       |      2^31-1
        0       |   0b0000 0000  |       0        | None (This case need not be handled)
      2^32-1    |   0b1111....1  |       32       | None (This case need not be handled)

Scoring

This is code-golf, so the solution in the fewest bytes in each language wins.

x86-64 assembly, 5 4 bytes

   0:   97                      xchg   %eax,%edi
   1:   d1 c0                   rol    %eax
   3:   c3                      retq

A function using the C calling convention that bitwise rotates its argument left by 1 bit.


Rainbowlify An Image This challenge is about gradually shifting hues in an image to make pretty pictures like this:

(original)
Challenge
Write a program or function that takes in two non-negative integers and an image in any common image file format of your choosing (you can take a path to the image or the raw image data).
We'll call the first integer the cycles and the second integer the offset.
We'll also define floating-point step as 360 times cycles divided by the area of the image, or step = 360 * cycles / (image width * image height).
For each pixel P in the image, moving one row at a time, left-to-right, top-to-bottom (i.e. in reading order if the pixels were letters), do the following:

Increase the hue of P by offset degrees (looping around from 360 to 0 if necessary).

Then increase offset by step.

Save, display, or output raw the resulting image in any common image file format.
This procedure incrementally increases the hue of all the pixels in the image, making cycles full loops around the hue rainbow, starting by initially offsetting the hue by offset.
When cycles is 1 and offset is 0, as in the Starry Night image above, the top and bottom rows of pixels have practically no hue shift but in between there's a full color cycle.
Details

Cycles can be any non-negative integer but you may assume that offset is from 0 to 359 inclusive.

When cycles is 0, every pixel in the image will have its hue shifted by exactly offset since step must be 0 too. (In this case if offset is 0 then the image doesn't change at all.)

You may assume cycles and offset are input as floats if desired (i.e. 1.0 instead of 1). (I realize they needn't be integers at all, it just makes the challenge simpler.)

"Hue" refers to the RGB color space version, common in HSL/HSV color models.

Examples
Original:

Cycles = 1, offset = 0:

Cycles = 1, offset = 180:

Original:

Cycles = 2, offset = 60:

Original:

(Thanks ArtOfCode.)
Cycles = 1, offset = 120:

Original:

(Thanks Doorknob.)
Cycles = 1, offset = 0:

Cycles = 4, offset = 0:

Cycles = 200, offset = 0:

Cycles = 30000, offset = 0:

(These images may not be pixel perfect due to imgur compressing them.)
Scoring
The shortest code in bytes wins. Tiebreaker is higher voted answer.
Answers that post their own cool looking test images will get more brownie points from me.

Pyth, 86 bytes, full program

=N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z

Pyth doesn't have built-in color space conversions - this is the real deal.

Takes input in the following format on stdin:

input_filename.png
offset
cycles

The output image is written to o.png.

This works by rotating the color cube around its diagonal, and then clamping any values outside of the range.

If a is the angle to rotate by, and r, g, b is the input color, we calculate the new color r', g', b' by:

o = cos(a), i = sin(a) / sqrt(3)
n = (1 - o) / 3
m = [n + o, n - i, n + i]
clamp(c) = max(0, min(255, c))
r' = clamp(r*m[0] + g*m[1] + b*m[2])
g' = clamp(r*m[2] + g*m[0] + b*m[1])
b' = clamp(r*m[1] + g*m[2] + b*m[0])


Unnecessary Text Abbreviations Introduction

I can't stand text abbreviations, mainly because for the most part I have no idea what most of them mean. Of course, cut backs need to be made, so if they are necessary to fit the text in the character limit, I'll allow them.

Challenge

You have to write a program that takes passage of text and determines whether text abbreviations are required to fit the passage in the 140 character limit (as used by Twitter).

The passage can be read from a plaintext file, supplied via system arguments or input by a user. You may not hardcode it.

Determining

Your program needs to replace all abbreviations (Note: Don't, can't, won't etc. are allowed) found in the passage and replace them with full words. If the expanded passage fits within 140 characters, then abbreviations are unneccessary. Otherwise, abbreviations are necessary. Any unknown abbreviations should be treated as standard words.

The output should be boolean (True if necessary or False otherwise) but if the passage was longer than 140 characters in the first place, then Tl;dr should be printed.

Abbreviations

All abbreviations required are detailed here. You decide how you parse the information. You may store the list in a local file of any name, providing that the list is taken from the provided URL.

Abbreviations should be defined as all in capital letters (eg. LOL, LMFAO, OP not lol, lmfao, op).

Note: In several cases, the abbreviation is not the standard format (abbreviation -> meaning) and sometimes has multiple meanings, words and/or spellings. Ignore all of these cases. For clarification, all abbreviations that you need to worry about should be single word.

Ignore all non alphabetic abbreviations (e.g. Ignore <3,99). Abbreviations that start with an alphabetic character can be parsed (e.g. Do not ignore A/S/L,L8).

Test cases (taken from random tweets)

1: Returns true

  IDG people who MSG U and still lag even THO U reply straight away like how did U become that busy in 5 secs that U can't communicate LOL CYA

2: Returns false

  If your role models are celebrities; Athletes, Actors, Singers, Politicians, etc then you need a life coach. ASAP.

3: Returns Tl;dr

  For your information: we technically live about 80 milliseconds in the past because that's how long it takes our brains to process information.

Winning Criteria

The shortest code wins.

Based upon the alt-text of xkcd 1083

Thanks to Ingo Bürk, here's a JSON file of the list

ECMAScript 6 + HTML (117 123 144)
Using HTML to store the dictionary. Try it online (with any ECMAScript 6 browser such as Firefox).
d=eval(d.innerHTML),t=r=prompt(l=140);for(k in d)r=r.replace(RegExp(k,'g'),d[k])
alert(t.length>l?'Tl;dr':r.length>l)

I'm just blatantly ignoring the currently open questions to this challenge, hoping it won't render my solution incorrect. YOLO #abbreviations
Explanation
The dictionary has been filtered according to the rules (ignoring abbreviations starting with non-alphanumeric character, ignoring multi word abbreviations, only considering uppercase abbreviations, using first replacement if there are options).
To save bytes in the code, the dictionary has also been transformed such that the key is already a regular expression with word boundary match to deal with punctuation.
Then the actual code becomes a matter of reading the tweet, doing all the replacements and checking for the length.
The script used for preparation can be found here. It is based upon the JSON file I have extracted from the website.

Edit #1: Thanks to Optimizer for golfing it down for a win of 21 bytes
Edit #2: Another 6 bytes thanks to Optimizer's tip of using eval.


Connecting Gaps with Tetris Pieces You should write a program or function which given a list of tetris blocks as input outputs or returns the biggest gap between two points in the same height level which the pieces can connect.

The 7 types of tetris pieces are the following:

We will refer to these pieces by the letters I, J, L, O, S, T and Z respectively, referring to their shapes. You can rotate the pieces but cannot mirror them just like in a Tetris game.

Our task is to create an orthogonally connected area (sides connected to sides) from the given pieces. This area should connect (also orthogonally) two unit squares which are at the same height. We should find the biggest possible gap between the two squares which we can bridge.

Detailed examples

With the piece L we can connect a gap of 3

   L
XLLLX

With the piece S we can connect a gap of 2

  SS
XSSX

With the pieces S,S,O we can connect a gap of 7 (Note that we can't connect a gap of 8)

 S
XSSOO SSX
  SOOSS

Input

A string representing the available pieces containing only the uppercase letters I, J, L, O, S, T and Z. Every letter represents a complete tetris piece.
The letters will be in alphabetical order in the string.
The string will be at least one character long.

Output

A single positive integer, the biggest gap connectable with the given pieces.

Examples

Input => Output

OSS  =>  7

LS  =>  5

LZ  =>  6

ZZZZ  =>  10

LLSSS  =>  14

IIJSSSTTZ  =>  28

IISSSSSS  =>  24

OOOSSSSSSSSSSSSTT  =>  45

IJLOSTZ  =>  21

IJLOSTZZZZZZZ  =>  37

IIJLLLOSTT  =>  31

IJJJOOSSSTTZ  =>  35

This is code-golf so the shortest entry wins.

CJam, 53

'[,73>qf{1$e=s':+\+~}:+3*I+O-SZ-JO+m0e>ZS-LO+-e>2+3/-

Try it online

The idea is: assign each of the I, J, ..., Z variables to be the number of occurences of that letter, and calculate string length * 3 + I - O. Then count the number of non-compensated S's or Z's: an S can be compensated by Z, J or O, and a Z can be compensated by S, L or O, and subtract ceil(that number/3), as we lose 1 unit for every 3 S's or Z's.


Draw diagonal positions of me squared Based on the interpretation user @ThePirateBay made from the first version of my own challenge
Output diagonal positions of me squared
now I challenge you to make ASCII art that draws diagonal lines based on a square character matrix  based on a given number n.
Input
A number n.
Output
A square matrix of size n^2 which outputs diagonals represented by the adequate one of the \ X /chars. All other positions are to be fulfilled with # chars.
Examples:
1
X

2
\/
/\

3
\#/
#X#
/#\

4
\##/
#\/#
#/\#
/##\

5
\###/
#\#/#
##X##
#/#\#
/###\

There will be no accepted answer. I want to know the shortest code for each language.

Jelly, 14 bytes
⁼þµḤ+Ṛị“/\X#”Y

A monadic link taking a number and returning a list of characters; or a full program printing the result.
Try it online! or see [1-12] in one go.
How?
⁼þµḤ+Ṛị“/\X#”Y - Link: number, n
 þ             - outer product (implicit range build on left AND right from n) with:
⁼              -   is equal (yields a table of 0s except the main diagonal is 1s)
  µ            - monadic chain separation, call that I
   Ḥ           - double (change all the 1s to 2s)
     Ṛ         - reverse I (a table of 0s with 1s as the anti-diagonal)
    +          - add (vectorises to make a table of zeros with 2s on the diagonal,
               -      1s on the anti-diagonal and, if the meet, a 3 at the centre)
       “/\X#”  - literal list of characters ['/','\','X','#']
      ị        - index into (replaces... 1:'/'; 2:'\'; 3:'X'; and 0:'#')
             Y - join with newline characters
               - as a full program: implicit print


Barcodegolf: Generate a number's UPC Just about every store nowadays uses Universal Product Code (UPC) barcodes to simplify the checking out process. If the name doesn't mean anything to you, you will surely recognize what they look like:

Format

The most common system is UPC-A, which uses 12 digits to represent each specific product. Each digit is encoded into a series of black and white stripes to allow machines to read the code, a length of seven bits. There are a total of 11 bits worth of patterns that indicate the beginning, middle, and end of the barcode. This comes to a total barcode length of 12 × 7 + 11 = 95 bits. (From now on, when binary is used to refer to the color of each bit, 0 is white and 1 is black.)

The beginning and end both have a pattern of 101. The digits are then divided into 2 groups of 6 and encoded as shown below, with a pattern 01010 between the left and right groups. This table lists the pattern for each number. Note that the pattern is different depending on if the digit is on the right or left side (This allows the barcode to be scanned upside down). However, the pattern for the right is the opposite (swap black for white and vice versa) of that of the left.

If you can't see the image above, this is each number's binary equivalent.

#   Left    Right
0   0001101 1110010
1   0011001 1100110
2   0010011 1101100
3   0111101 1000010
4   0100011 1011100
5   0110001 1001110
6   0101111 1010000
7   0111011 1000100
8   0110111 1001000
9   0001011 1110100

Example

Say you have the UPC 022000 125033. (Those aren't random numbers. Leave a comment if you figure out their significance.) You start with this boilerplate that is the same in every barcode:

101xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx01010xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx101

For the digits, you replace each one with the corresponding encoding for the side (left or right) it's on. If you're still confused, see the image below.

Here is the output in binary with | pipes separating the parts.

101|0001101|0010011|0010011|0001101|0001101|0001101|01010|1100110|1101100|1001110|1110010|1000010|1000010|101

Challenge

Write a program that outputs the UPC-A barcode for the user input. The image's dimensions should be 95 × 30 pixels, with each "bit" being one pixel wide and 30 pixels tall. Black stripes are in rgb(0, 0, 0) and white stripes are consistently transparent or rgb(255, 255, 255).

Notes

Take input from stdin or the command line, or write a function that takes a string or integer (note that input can have leading zeroes, and most languages remove them or convert the number to octal).
Output the image in one of the following ways:

Save it to a file with a name and format (PNG, PBM, etc.) of your choice.
Display it on the screen.
Output its file data to stdout.

You may not use libraries or builtins that generate barcodes (I'm looking at you, Mathematica), although you may use image or graphics libraries.
The last digit of a UPC is usually a check digit, but for these purposes you don't have to worry about it.

Examples

Here are some more examples to test your code with. The binary output is also given for convenience.

Input: 012345678910

Output:

10100011010011001001001101111010100011011000101010101000010001001001000111010011001101110010101

Input: 777777222222

Output:

10101110110111011011101101110110111011011101101010110110011011001101100110110011011001101100101

Scoring

This is code golf, so the shortest submission (in bytes wins). Tiebreaker goes to the earliest post.

Rev 1 BBC BASIC, 155 ascii chars, tokenised filesize 132 bytes
INPUTn$
FORi=91TO185p=i MOD2j=i MOD47IFj<42j+=i DIV141*42p=(j>41EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1
IFp LINEi*2,60,i*2,0
NEXT

saved a few bytes by incorporating the offset of 43 into the i loop. In order to avoid breaking the MOD2 an additional 47 had to be added for a total of 90.
This moves the barcode further from the origin, as shown, if that is acceptable:

Rev 0 BBC BASIC, 157 ascii chars, tokenised filesize 137 bytes
INPUTn$
FORi=1TO95p=i MOD2j=(i+43)MOD47IFj<42j+=i DIV51*42p=(i>50EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1
IFp LINEi*2,0,i*2,60
NEXT

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
The default screen mode is black text on a white background. This differs from original BBC BASC.
Ungolfed version with test printing
Calculation of a data bar depends on IF j<42 and must all be done on one line. In the ungolfed version it is done in three steps. In the golfed version the last two steps are combined into a single huge expression p=...
I had to reverse the order of the bitmaps, because I use >>(j MOD 7) to access the bits, which means I access the least significant bit first. Once this is done, all the left bitmaps are conveniently in the ASCII range.
  INPUTn$
  FOR i=1TO95                            :REM iterate through 95 bars
    p=i MOD2                             :REM calculate colour of format bar 1=black
    j=(i+43)MOD47                        :REM repetition is 42 data bars + 5 format bars. offset and modulo. if j<42 it is a data bar and we must change p.

    REM if i DIV 51=1 we are in the second half, so add 42 to j. Find the bitmap for left hand value, from character j/7 of the input.
    REM i>50 evaluates to false=0 true=-1. XOR this with p to invert bitmap for right hand side. Shift and AND with 1.
    IF j<42 j+=i DIV51*42:p=ASC(MID$("XLd^bFznvh",  VAL(MID$(n$,j/7+1,1))+1  )) :p=(i>50EORp)>>(j MOD7) AND 1

    IF j MOD 7 = 0 PRINT                  :REM format test output
    PRINT ;p;                             :REM print test output
    IF p LINEi*2-2,0,i*2-2,60             :REM if p=1 plot bar. there are 2 logical units for each pixel.
  NEXT

Typical output, ungolfed version, with test output


Several bases but not twice the same digit Input

A non-empty array of positive integers.

Task

Convert each integer to either binary, octal, decimal or hexadecimal in such a way that each digit (0 to F) is used at most once.

Output

The list of bases that were used to solve the puzzle.

Detailed example

The expected output for [ 16, 17 ] is [ octal, decimal ].

Here is why:

We can't simply use decimal for both numbers, because they both contains a 1.
16 cannot be converted to binary, because its representation in this base (10000) contains several 0's.
17 cannot be converted to binary either, because its representation in this base (10001) contains several 0's and  several 1's.
17 cannot be converted to hexadecimal, because its representation in this base (11) consists of two 1's.
Let's consider all remaining possibilities:

               +---------+---------+--------+
               | oct(16) | dec(16) | hex(16)|
               | = 20    | = 16    | = 10   |
+--------------+---------+---------+--------+
| oct(17) = 21 | 20,21   | 16,21   | 10,21  |
| dec(17) = 17 | 20,17   | 16,17   | 10,17  |
+--------------+---------+---------+--------+

The only possible solution is to convert 16 in octal (20) and to keep 17 in decimal (17). This way, the digits 0, 1, 2 and 7 are used exactly once.

Clarifications and rules

The input is guaranteed to lead to a unique solution. Your code is not supposed to support arrays that give several solutions or no solution at all.
You may output the bases in any reasonable format, such as [ "bin","oct","dec","hex" ], [ 'b','o','d','h' ], "BODH", [ 2,8,10,16 ], [ 0,1,2,3 ] etc. But it should be clearly explained in your answer.
The order of the bases in the output must match the order of the input integers.
If that helps, you may assume that the input is sorted from lowest to highest, or from highest to lowest.
This is code-golf, so the shortest answer in bytes wins!

Test cases

You do not have to output the conversion results listed below. They are purely informational.

Input                                  | Output          | Conversion result
---------------------------------------+-----------------+------------------------
[ 119 ]                                | O               | 167
[ 170 ]                                | D               | 170
[ 64222 ]                              | H               | FADE
[ 16, 17 ]                             | O/D             | 20/17
[ 14, 64, 96 ]                         | H/H/D           | E/40/96
[ 34, 37, 94 ]                         | O/D/H           | 42/37/5E
[ 2, 68, 82 ]                          | B/D/H           | 10/68/52
[ 22, 43, 96 ]                         | O/O/O           | 26/53/140
[ 3639, 19086, 57162 ]                 | H/D/H           | E37/19086/DF4A
[ 190, 229, 771 ]                      | O/H/O           | 276/E5/1403
[ 2, 44, 69, 99 ]                      | B/H/H/H         | 10/2C/45/63
[ 75, 207, 218, 357, 385 ]             | H/H/H/D/O       | 4B/CF/DA/357/601
[ 12, 28, 46, 78, 154, 188, 222, 240 ] | D/O/O/D/H/H/H/H | 12/34/56/78/9A/BC/DE/F0

The raw input list is available here.

JavaScript (Node.js),192,155,154,152,151,145,136,113,99,92 90 bytes

thanks to @Arnauld for reminding me that i can return [0,1,2,3] -> which is [2,8,10,16] saves 8 bytes, and for the brilliant idea (which help to reduce by 23+ bytes)
thanks to @Kevin Cruijssen for reducing by 1 bytes

f=([c,...a],t="")=>c?[1,4,5,8].find(b=>T=!/(.).*\1/.test(n=t+c.toString(b*2))&&f(a,n))+T:a

Try it online!
Explanation:
[c,...a] - @Arnauld trick for taking one item at a time
c?***:" " ->if c is undefined we managed to get to the end result- [] - if i would put "" than the find would not considered that legit. ([]+5="5" JS FTW)
[1,4,5,8].find every time we find the correct base (the output will be of this array (1,4,5,8)->(2,8,10,16) its legit.
now how the find works -> if it finds something it returns the element (1-8)
and than i add the result of the inner solution. if it doesnt find then it returns undefined + T is now false -> NaN which in the parent call will be considered false
!/(.).*\1/.test(n=t+b) determine if the string has duplicates, if so:
f(a,n)) just go the the next number(a is now array.slice(1)) with the new string(n)
we assign result to T(temp) of the result because find stops when it finds and so we know that the last result will be f() which is result B


Find the nth Fibonnaci Prime, in the shortest code The challenge is rather simple:

Take a positive whole number \$n\$ as input.
Output the \$n\$th Fibonacci prime number, i.e. the \$n\$th Fibonacci number that is also prime.

Input can be as an parameter to a function (and the output will be the return value), or can be taken from the command line (and outputted there).
Note: Using built in prime checking functions or Fibonacci series generators is not allowed.
The first 10 Fibonacci primes are
[2, 3, 5, 13, 89, 233, 1597, 28657, 514229, 433494437]

Shortest code wins. Good luck!