Jelly, 31 bytes
ØṖḟØBṭØBUs26¤f€³Lİ⁴¡$ÐṀFf
¹⁶Ç?€

Try it online!
The boolean values are 2 and 1 (or any other positive even/odd pair), which represent True and False respectively. I will try to add an explanation after further golfing.
Thanks to caird coinheringaahing for saving 2 bytes, and to Lynn for saving 4 bytes! Thanks to one of Erik's tricks, which inspired me to save 4 bytes!
How it works
Note that this is the explanation for the 35-byte version. The new one does roughly the same (but tweaked a bit by Lynn), so I won't change it.
ØBUs26f€³µ³ḟØBW,µẎLİ⁴¡$ÐṀF - Niladic helper link.
ØB                         - String of base digits: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
                             abcdefghijklmnopqrstuvwxyz'.
  U                        - Reverse.
   s26                     - Chop into sublists of length 26, preserving shorter
                             trailing substrings.
      f€³                  - For each, keep the common characters with the input.
            ØB             - Base digits.
          ³ḟ               - Get the signs in the input. Filter the characters of the
                             input that aren't alphanumeric.
              W,µẎ         - Concatenate (wrap, two element list, tighten).
                       ÐṀ  - Keep the elements with maximal link value.
                  L        - Length.
                    ⁴¡     - Do N times, where N is the second input.
                   İ       - Inverse. Computes 1 ÷ Length. 2 maps to the length itself,
                             because 1 ÷ (1 ÷ Length) = length; 1 yields
                             (1 ÷ Length), swapping the maximal numbers with minimal ones.
                         F - Flatten.

¹⁶e¢$?€ - Main link.
      € - For each character.
   e¢?  - If it is contained by the last link (called niladically), then:
¹       - Identity, the character itself, else:
 ⁶      - A space.


Python with numpy, 59 bytes

lambda M,N:trace(mat(tri(M+1)[::-1])**N)
from numpy import*

Try it online!

Uses matrix multiplication to count paths. If float precision is an issue, the mat could specify mat(...,int).


J, 126 bytes

[:>[:{:"1@}./:~(({.@I.@:~:>@{.)({:@](|.@:{`[`]}~;])[,[:(0{*/,&I.{.)(<0{i.@$)*"1{"0 1=|.@])(,:>@{.))^:(-.@-:>@{.)^:a:;&(0 2$'')

Try it online!

Here is the same code in a more procedural form, if you're looking for an explanation of algorithm.

f=. 3 :0
sorting=.y NB. copy of input we'll mutate
sorted=./:~y
swaps=.0 2$''
for_j. i.#y do.
  correct=.j{sorted
  cur=.j{sorting
  if. cur = correct do.
    continue.
  end.
  NB. correctly fill the current idx j
  valid_idxs=.(j<i.#sorting)
  good_j=. valid_idxs * correct = sorting
  NB. will any of these be the correct desitnation for the current elm?
  good_dest=. valid_idxs * cur = sorted
  both=.good_j * good_dest
  use=.(1 e.both) { good_j ,: both
  swap_with=. {.I.use
  swaps=.swaps,(j, swap_with)
  sorting=.(sorting {~ swap_with, j) (j, swap_with)} sorting
end.
swaps
)

Try it online!

original answer, doesn't work for repeats

J, 18 bytes

[:;(2]\])&.>@C.@/:

Try it online!

NOTE: Thanks to Neil for pointing out this currently fails on the test case 4 5 2 1 3 3.

/: Grade up, ie, return the permutation that puts the list into order
C.@ Convert that to cyclic permutation form, which uses boxes
&.> For each of those boxed lists, ie, permutation cycles...
(2]\]) Return all consecutive pairs of two elements.  This gives us the swaps, and it works because J gives the cycle list in descending order.
[:; raze the list of boxes.  This gives us all the swap pairs as a single list of pairs, ie, an N x 2 matrix.


Python - 10 operations

def f(n):
    q=str(n)
    p=q[::-1]
    return 1-n%2+(q!=p and f(n+long(p)))


Return the clock emoji closest to the current time when run

Ruby — 61 54 bytes
Python 3 — 79 77 75 74 bytes
edit: Turns out this is much shorter in Ruby, because Time doesn't need to be imported and integer division is the default.
a=(Time.now.to_i/900-3)/2%24
puts""<<128336+a/2+a%2*12

Arithmetic:

Time.now.to_i: Seconds since epoch.
/900: Combine time into 15-minute segments.
-3: -4 because characters start at 1 o'clock, +1 so that rounding is done to nearest half hour, rather than downwards.
/2: Combine into half-hour segments.
%24: Get current half-hour segment out of 12 hours.
a/2 + a%2*12: Account for the fact that whole-hour characters come in a block before half-hour characters.

Local time version, 69 bytes:
n=Time.now
a=((n.to_i+n.gmtoff)/900-3)/2%24
puts""<<128336+a/2+a%2*12

Original Python 3 version:
import time
a=int((time.time()/900-3)/2%24)
print(chr(128336+a//2+a%2*12))

Prints the current time UTC. Python 2's chr only accepts 0-255, and unichr only 0-65535. In Python 3, / is always floating-point division and // is always integer division.


Brainf*** subprograms with unique outputs

Score: 35 41 69 78 79 83
(Remove the newline.)
-->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>-
>+>->+>->+>->+>->+>->+>->+>->+>++[>[-<+++>]<<++]>.

Try it online!
I'm not sure exactly why it works...
Score: 79
X->>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>
+>+>+>+>+>+>+>+>+>+>+>+[>[-<+>>+<]+>[-<+>]<<<+]>>.

Try it online!
It was supposed to sum 2*mem[i]*i and add the number of cells (+const) where the addresses are counted from the right to the left. The multiplier 2 and number of cells can make removing + and > having different parity.
It indeed worked like that in the 69 points version. But the latest version broke that and got something else by coincidence. It calculates sum(mem[i]*i+i+1) and removing + and > does almost the same, except for the sum(i) which has a difference of the number of cells, which is also the number of different output for either removing + and >.
For the bonus:

 +.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.


Python 3, 44 43 40 bytes

Based off of mabel's answer but using dictionary comprehensions:

lambda n:[*{n**i%10:0for i in[1,2,3,4]}]

Saved 1 byte thanks to mabel.

Saved 3 bytes thanks to xnor.

You can try it online


TSQL(sqlserver 2016) 310 294 280 bytes
What a wonderful opportunity to write ugly code:
Golfed:
DECLARE @ varchar(max)= '5,5,5'
DECLARE @a varchar(20) = '125'

,@ varchar(max)='';WITH D as(SELECT @a a UNION ALL SELECT STUFF(a,charindex(',',a),1,value)FROM STRING_SPLIT('*,+,./,-,',',')x,d WHERE a like'%,%')SELECT @+=a+','''+REPLACE(a,'.','')+'''),('FROM D WHERE a not like'%,%'EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b)

Try it online
Readable:(insertion of decimal point(.) and removal of the same is necessary in order for sql to accept that 4/5 is not 0 - well removal is for the people testing it)
DECLARE @a varchar(max)= '5,5,5'
DECLARE @b varchar(20) = '5'

,@ varchar(max)=''
;WITH D as
(
  SELECT @a a
  UNION ALL
  SELECT STUFF(a,charindex(',',a),1,value)
  FROM STRING_SPLIT('*,+,./,-,',',')x,d
  WHERE a like'%,%'
)
SELECT @+=a+','''+REPLACE(a,',','')+'''),('
FROM D
WHERE a not like'%,%'

EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b)

This solution can also handle these types of input:

Input :[1,2,3,4,5] 0 Output : 12-3-4-5


Mathematica, 67 bytes

Fold["("<>#<>")"<>#2&,RomanNumeral[#~IntegerDigits~1000]/."N"->""]&

Avoids all trouble with M by converting the input to base 1000 and converting each digit separately with RomanNumeral. Then we fold them up by inserting (...) from the left.

Unfortunately, Mathematica represents zeros as N so we need to get rid of those.


JavaScript (Node.js), 465 bytes
(i,C)=>(p='https://codegolf.stackexchange.com',n=t=a=[],g=(u,c)=>require('https').get(u,r=>r.on('data',d=>i+=d,r.on('end',_=>c(r.headers.location)))))(p+'/users/'+i,l=>g(p+l,_=>g(s=i.match(/ht.+\/s[^"]+\d\/[^?]/)+0,l=>g(new URL(l,s)+'?tab=accounts',_=>i.replace(/unt-[^]+?\n *([\w&].+)[^]+?r".+?([\d,]+)/g,(_,s,r)=>a.push([s,r=r.split`,`.join``,t-=r,n--]))&&C(a.map(([s,r])=>s.replace(/&#?(.+?);/g,(_,m)=>String.fromCharCode('0'+m|0||38))+` ${r/t*n}x`).join`
`)))))

Function which accepts a the ID as a string and returns the result to a callback.
I tried to make it robust and it should work for any profile as of time of submission with one possible exception: the accounts tab on the network profile contains a profile summary which can be edited by the user so it's possible for a user to write something to fool the regex in their bio.
Explanation
(i,C)=>(p='https://codegolf.stackexchange.com',
// n = count of sites, t = total sum of reputation, a = array of (siteName, rep) tuples
n=t=a=[],
// Function which performs a GET request.
// The body is appended to `i` and the callback is called with the location header.
g=(u,c)=>require('https').get(u,r=>r.on('data',d=>i+=d,r.on('end',_=>c(r.headers.location))))
// Load the user's PPCG profile.
)(p+'/users/'+i,l=>
// Since we only provided the ID and not the name in the URL, it will return a 301 redirect.
// Load the redirect.
g(p+l,_=>
// The first URL on the body to match this regex is the network profile URL of the user.
// Note that this comes before the custom content in the profile
// (which could contain other network profile URLs).
// This request will result in a 301 if the user's name is different on the
// network profile than PPCG, so the first character plus 0 will force a redirect
// because display names are a minimum of 3 characters long.
g(s=i.match(/ht.+\/s[^"]+\d\/[^?]/)+0,l=>
// Load the accounts tab of the network profile.
g(new URL(l,s)+'?tab=accounts',_=>
// Find each site and reputation count.
i.replace(/unt-[^]+?\n *([\w&].+)[^]+?r".+?([\d,]+)/g,
// Remove the commas from the rep value, populate `a` and add them up for the average.
// decodeURIComponent is annoyingly long but there's no shorter way to correctly display
// sites like the Japanese site which is made solely of URI encoded characters.
(_,s,r)=>a.push([s,r=r.split`,`.join``,t-=r,n--]))&&
// Calculate and print the results.
// There is a lot of bytes dedicated here to unescaping HTML entities because
// unfortunately there's no easy way to correctly display sites like the Japanese site
// which is made solely of HTML encoded characters.
// As far as I can tell the only escapes used in site names are the `&#xXX` style
// and `&amp;`.
C(a.map(([s,r])=>s.replace(/&#?(.+?);/g,(_,m)=>String.fromCharCode(0+m|0||38))+` ${r/t*n}x`).join`
`)))))


Mathematica, 45 36 bytes

Last@Select[IntegerDigits[#!],#>0&]&

Very readable for a winning answer. :) (Then again, there's no GolfScript & Co. submission yet.)

This handles input 1,000,000 in about 5 seconds on my machine.


Remove entries from array to sort it and maximize sum of elements

Haskell, \$O(n \log n)\$ time, \$O(n)\$ space

{-# LANGUAGE MultiParamTypeClasses #-}

import qualified Data.FingerTree as F

data S = S
  { sSum :: Int
  , sArr :: [Int]
  } deriving (Show)

instance Monoid S where
  mempty = S 0 []
  mappend _ s = s

instance F.Measured S S where
  measure = id

bestSubarrays :: [Int] -> F.FingerTree S S
bestSubarrays [] = F.empty
bestSubarrays (x:xs) = left F.>< sNew F.<| right'
  where
    (left, right) = F.split (\s -> sArr s > [x]) (bestSubarrays xs)
    sLeft = F.measure left
    sNew = S (x + sSum sLeft) (x : sArr sLeft)
    right' = F.dropUntil (\s -> sSum s > sSum sNew) right

bestSubarray :: [Int] -> [Int]
bestSubarray = sArr . F.measure . bestSubarrays

How it works

bestSubarrays xs is the sequence of subarrays of xs that are on the efficient frontier of {largest sum, smallest first element}, ordered from left to right by increasing sum and increasing first element.

To go from bestSubarrays xs to bestSubarrays (x:xs), we

split the sequence into a left side with first elements less than x, and a right side with first elements greater than x,
find a new subarray by prepending x to the rightmost subarray on the left side,
drop the prefix of subarrays from the right side with smaller sum than the new subarray,
concatenate the left side, the new subarray, and the remainder of the right side.

A finger tree supports all these operations in \$O(\log n)\$ time.


Python, 32 bytes

lambda n:eval('['*n+'n'+']*n'*n)

Try it online!

Makes a string like "[[[n]*n]*n]*n" with n multiplcations, and evaluates it as Python code. Since the evaluation happens within the function scope, the variable name n evaluates to the function input.


Python, 71-25=46 63-25=38 chars

f=lambda a,b:max((a*i,b/i/i)for i in range(1,b)if b%(i*i)==0)

g=lambda a,b,c:max((a*i,b/i**c)for i in range(1,b)if b%i**c==0)

f is 61, chars. g is 63 but gets a 25 char bonus.


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

Test it online!
Based on the observation that

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

Or, rather, that

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

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


Write a code golf problem in which Java wins

48 characters

Task: Ignore any input. Always produce exactly the following output:

java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
    at M.<init>(M.java:1)
    at M.<clinit>(M.java:1)

Solution:

enum M{M;System x;{x.setErr(x.out);int y=1/0;}}

Save as M.java, compile with javac M.java and run with java M. It also produces an error message on standard error, but that doesn't violate any of the rules.


Selective character count (only non-alphanumeric)?


Generate a mantis's head (symmetrical triangle)

Jelly, 15 bytes
RØ.ṗŒpFS=ɗƇUƑƇḢ

Try it online!
-1 byte thanks to caird coinheringaahing
RØ.ṗŒpFS=ɗƇUƑƇḢ  Main Link; accepts w as the left argument and n as the right argument
R                Range; [1, 2, ..., w]
 Ø.ṗ             [0, 1] ~ cartesian power ~ ^
    Œp           Cartesian Product of ^'s items - this gets all valid triangles of the right size
      ---ɗƇ      Keep elements where
       S         the sum of
      F          the triangle flattened
        =        equals (right argument)
             Ƈ   Keep elements where
            Ƒ    the element is the same when
           U     each sub-list is reversed
              Ḣ  Get the first such triangle


Jelly, 10 bytes

Œgœ^/€FµÐL

Try it online!

How it works

Œgœ^/€FµÐL  Main link. Argument: A (array)

       µ    Combine all links to the left into a chain.
Œg              Group all adjacent equal items.
    /€          Reduce each group by...
  œ^                symmetric multiset difference.
                In each step, this maps ([], n) to [n] and ([n], n) to [], so the
                group is left with a single item if its length is odd, and no items
                at all if its length if even.
      F         Flatten the resulting array of singleton and empty arrays.
        ÐL  Apply the chain until the results are no longer unique. Return the last
            unique result.


APL (Dyalog Unicode), 3 bytes

-≡⍉

Try it online!
This is exactly an APLcart entry on "antisymmetric". Basically it checks if the input's negative - matches ≡ the input's transpose ⍉.


Is this string a palindrome (in Morse Code)?

Jelly, 28 bytes

ØAŻŻ“¡9o|çṫ¡X1ỴỌġQ’œ?iⱮḃ2FŒḂ

Try it online!

ØA                             The uppercase alphabet.
  ŻŻ                           Prepend two zeroes.
    “¡9o|çṫ¡X1ỴỌġQ’œ?          Get the 73540211105102870315464559332nd permutation.
                                  (= “ETIANMSURWDKGOHVF0L0PJBXCYZQ”)
                     iⱮ        Find indices of input letters in this list.
                       ḃ2      Bijective base 2: map [1,2,3,4,5…] to
                                 [1], [2], [1,1], [1,2], [2,1], …
                         F     Flatten.
                          ŒḂ   Is palindrome?

I wrote this answer looking at one of these (read the rows from right-to-left, and you get my magic string!):


How many times is rectangular array A embedded in rectangular array B?

APL (160)

{∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬

Output:

      {∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬
abb
aba

ababb
aabba
babab
abbaa

 5  .....  .....  ab..b  ab.b.  a..bb
    a.bb.  .abb.  .....  .....  a..ba
    .....  .aba.  .....  .....  .....
    a.ba.  .....  ab..a  ab.a.  .....

Explanation:

{...}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬: read the two arrays from the keyboard, and return them as two matrices. Reduce the following function over the list of the two matrices.
∆{...}¨(∆←⍴⍵)-⍴⍺: get the height and width of each of the matrices. In both the width and the height, get a list of possible lines to drop.

⍵=0:⊂⍺/1: if the matrices are the same length in a dimension, never drop any lines from that dimension. Otherwise:
⍺=1:(⍳⍵)⋄: If the difference is one, try to drop each line
∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵: otherwise, drop each possible combination of ⍺ lines.

∆←,⊃∘.,/⊂¨¨: combine each height mask with each width mask, giving all possible combinations to make the second list the size of the first.
⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆: for each possible combination, remove those lines from the second matrix.
∆/⍨⍺∘≡¨: drop all the ones that are not equal to the first matrix, giving the solutions.
⊃¨∘.∧/¨: for each of the possible solutions, make a matrix with 0 where a dot should go and 1 where the corresponding character from the first matrix should go.
⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨: for each of these, flatten both the second matrix (,⍵) and the matrix of dots (,⍺), and take either the character or a dot for each position ({⍺:⍵⋄'.'}¨). Then reshape it to the shape it had before ((⍴⍵)⍴).
∆,⍨⍴∆: give the amount of solution, and each solution.


150 character

Quicksort.

/* 146 character.
 * sizeup 1.000; speedup 1.000; */
#define REC_SIZE    \
    sort(l, v+n-l); \
    n = l-v;

/* 150 character.
 * sizeup 1.027; speedup 1.038; */
#define REC_FAST  \
    sort(v, l-v); \
    n = v+n-l;    \
    v = l;

void sort(float* v, int n)
{
    while ( n > 1 )
     {
       float* l = v-1, * r = v+n, x = v[n/2], t;
L:
       while ( *++l < x );
       while ( x < (t = *--r) );

       if (l < r)
        {
          *r = *l; *l = t;
          goto L;
        }
       REC_FAST
     }
}

Compressed.

void sort(float* v, int n) {
while(n>1){float*l=v-1,*r=v+n,x=v[n/2],t;L:while(*++l<x);while(x<(t=*--r));if(l<r){*r=*l;*l=t;goto L;}sort(v,l-v);n=v+n-l;v=l;}
}


PowerShell, 91 89 91 56 bytes

date("$args"-replace'th|rd|st|(\b.*)day|,')-f yyyy/MM/dd

Try it online!

Takes input as a string. Uses a -replace to get rid of junk, then uses the built-in Get-Date command with the -format flag to specify the required yyyy/MM/dd format. That string is left on the pipeline and output is implicit.

Saved two bytes thanks to Mr Xcoder. Saved a huge chunk thanks to TessellatingHeckler's regex golfing.


Python 3, 84 bytes

lambda n,*s:"DLL"+"L".join(i*"SLSC"+"LSLSCDURLCULCULSC"for i in s[::-1])+n*"SR"+"UR"

Usage:

# Example: 4 2 0 1 3 2 -> LSLCSLSCSLCULSLSCSLSCLSLDCSCUSLCU
>>> f = lambda ...
>>> f(4, 2, 0, 1, 3, 2)
'DLLSLSCSLSCLSLSCDURLCULCULSCLSLSCSLSCSLSCLSLSCDURLCULCULSCLSLSCLSLSCDURLCULCULSCLLSLSCDURLCULCULSCLSLSCSLSCLSLSCDURLCULCULSCSRSRSRSRUR'

Explanation: To start off we duplicate the zero and wrap it in a list:

DL -> 3 2 1 0 (0)

This is our base. Now I will explain a general algorithm that turns ... 1 0 (x) into ... 1 0 (i x) for arbitrary integer i. I will use as an example i = 2, and we have some arbitrary list (x). We start by wrapping our current list (x) into another list:

L -> 3 2 1 0 ((x))

Now we repeat the following sequence i times:

SLSC -> 3 2 1 (0 (x))
SLSC -> 3 2 (1 0 (x))

Now we're ready to insert the 2 into list (x). This goes as follows:

LSLSC -> 3 (2 (1 0 (x)))
DU -> 3 (2 (1 0 (x))) 2 (1 0 (x))
RLCU -> 3 2 (1 0 (x)) 2
LCU -> 3 2 1 0 (x) 2
LSC -> 3 2 1 0 (2 x)

Note that we keep pushing new integers on the left. So the very first (0) we started with stays on the right.

After we have inserted every integer we need into the list we remove the rest of the stack by swapping and removing n time (SR). Finally we unpack our list and delete the first 0 we inserted to start our list (UR).


CJam, 32 - 10 = 22

q_~{_{T&},:U-U:+a+}fTp~m*::&La-p

::& is newer than this question.

CJam, 36 - 10 = 26

q_~{:T;_{T&},:U-U:+a+}/p~m*{~&}%La-p

Input:

[[0] [1] [2 3 4 7 6]]
[[2 3] [4 7] [6] [1 0]]

Output:

[[2 3 4 7 6] [0 1]]
[[0] [1] [2 3] [4 7] [6]]

Explanation

q                 " Read the input. ";
_~                " Evaluate a copy. ";
{:T;              " For each list T in the second partition: ";
    _{T&},        " Select all lists in the first partition which share items with T. ";
    :U-           " Save to U and remove them from the first partition. ";
    U:+a+         " Append the union of U to the first partition. ";
}/
p                 " Print the meet. ";
~                 " Evaluate another copy. ";
m*                " Get the Cartesian product. ";
{~&}%             " Get the intersections of each pair of lists. ";
La-               " Remove empty lists. ";
p                 " Print. ";


TI BASIC, 6 bytes
This might change, since the rules are still not totally stable, but I wanted to post this while I could.
:Prompt X,F
:F

Asks for X, then parses whatever formula is put into F and displays it.
If I could assume that X was already stored in the memory, it would be
TI BASIC (maybe), 0 bytes

Is this ok?Guess not. :-(


Java 8, 58 57 bytes

n->{int i=0,m=0;while(n!=0)n+=n<0?++i:--m;return-~i*i/2;}

Online test suite

Thanks to Dennis for a 1-byte saving.


gs2, 1 byte

x

gs2 takes input from STDIN, and pushes it to the stack as a string.
x is the prefixes built-in, returning a list of all prefixes of the argument, in ascending-length order.
The resulting list of strings is implicitly printed one-by-one, without a delimiter, when the program terminates.


zsh + coreutils + unclutter + amixer + xterm (Arch Linux)

I took the answer by @TheDoctor and ran with it. This version has many improvements, and is 99% convincing to an experienced user (me) on my Arch Linux system. I use Zsh since it has good array and floating-point number support.
Dependencies: feh, unclutter, amixer, zsh, xterm

Improvements:

1) Use the number printed in the first column by dmesg, which is the time since boot, (e.g. [    0.000000] ) to determine the time to sleep. Without this it looks very unrealistic on my machine. These times are parsed before the loop (in an early call to sleep) since parsing inside the loop is too slow.

2) Don't print lines where time since boot is larger than 16 seconds. This specific number is machine-dependent, but the point is to avoid printing later dmesg-stuff that comes from inserting/removing usb sticks, etc. and is unrelated to booting.

3) Do all this in a fullscreen terminal window with black background and white text. Kudos to Mechanical Snail for this trick used in: Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible

4) Mute the audio on shutdown, restore volume when script finishes.

5) Hide the mouse cursor, restore when script finishes.

6) Show BIOS and Syslinux splash screens.

Run with: xterm -fu -fg white -bg black -e '/usr/bin/zsh fake-reboot.sh'

Code:

#!/usr/bin/zsh
# Remove (undisplay) the mouse pointer
unclutter -idle 0 -jitter 255 &
# Since there is no easily-accessible (i.e. without being root) shutdown log, we
# fake these messages.
echo "The system is going down for maintenance NOW."
sleep 2.0
echo "[21656.404742] systemd[1]: Shutting down."
echo "[21656.404742] systemd[1]: Stopping Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopped Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopping Sound Card."
# For added effect, store volume and then mute sound
volume=`amixer -- sget Master | awk -F'[][]' 'END{print $2}'`
amixer -- sset Master 0% &> /dev/null
echo "[21656.404742] systemd[1]: Stopped target Sound Card."
sleep 0.5
echo "[21656.919792] systemd[1]: Stopping system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Removed slice system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Stopping system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Removed slice system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Stopping User Manager for UID `id -u`..."
sleep 0.7
echo "[21657.624741] systemd[1]: Stopping Graphical Interface."
echo "[21657.624742] systemd[1]: Stopped target Graphical Interface."
echo "[21657.624745] systemd[1]: Stopping Multi-User System."
sleep 0.9
echo "[21658.606561] systemd[1]: Stopped target Multi-User System."
echo "[21658.606562] systemd[1]: Stopping Paths."
echo "[21658.606562] systemd[1]: Stopped D-Bus System Message Bus."
echo "[21658.606562] systemd[1]: Stopped target Paths."
echo "[21658.606568] systemd[1]: Stopping Timers."
echo "[21658.606568] systemd[1]: Stopped target Timers."
echo "[21658.606568] systemd[1]: Stopping Sockets."
echo "[21658.606568] systemd[1]: Stopped target Sockets."
echo "[21658.606568] systemd[1]: Starting Shutdown."
echo "[21658.606571] systemd[1]: Reached target Shutdown."
echo "[21658.606571] systemd[1]: Starting Exit the Session..."
echo "[21658.606571] systemd[1]: Received SIGRTMIN+26 from PID 10988 (kill)."
echo "[21658.606571] systemd[1]: Deactivated swap."
sleep 0.4
echo "[21659.001741] systemd[1]: Starting Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Unmounted /home."
echo "[21659.001742] systemd[1]: Reached target Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Stopping Remount Root and Kernel File Systems..."
echo "[21659.001742] systemd[1]: Stopped Remount Root and Kernel File Systems."
echo "[21659.001743] systemd[1]: Reached target Shutdown."
echo "[21659.001743] systemd[1]: Starting Final Step."
echo "[21659.001743] systemd[1]: Reached target Final Step."
echo "[21659.001754] systemd[1]: Shutting down."
sleep 0.3
echo "[21659.304341] systemd-journal[250]: Journal stopped"
sleep 0.2
echo "System halted."
sleep 2
clear
sleep 1
# Get the BIOS splash screen and display it
wget http://pvv.ntnu.no/~asmunder/bios.jpg  &> /dev/null
feh -Z -x -F -N --force-aliasing bios.jpg &
pid=$! # Store PID of Feh, so we can kill it later
# While showing the BIOS splash, use the time to parse dmesg output into arrays
tim=`dmesg | awk '{print $2}' | sed 's/]//' | grep "[0-9][0-9][0-9][0-9][0-9]"`
tim=($=tim)
dmsg=("${(@f)$(dmesg)}")
sleep 2.5
kill $pid
sleep 0.5
# Get the Syslinux splash and display it
wget http://pvv.ntnu.no/~asmunder/syslinux.png  &> /dev/null
feh -Z -x -F -N --force-aliasing syslinux.png &
pid=$!
sleep 1.3
kill $pid
# Loop through the arrays we created. Calculate the time we have to wait before
# displaying this line. If the wait time is less than 0.1 sec, we skip waiting.
T1=0.0
T2=0.0
n=0
for d in $dmsg; do
  T1=$T2
  T2=${tim[$n]}
  ((dT = $T2-$T1))
  if (( $dT > 0.1));then
    sleep $dT
  fi
  echo $d
  if (( $T2 > 16.0 )); then
    break
  fi
  ((n=$n+1))
done
sleep 1
clear
# It's normally agetty that parses /etc/issue and handles escape codes in a
# special way. Thus we skip the first line of /etc/issue and do that manually.
echo "Arch Linux "`uname -r`" (tty1)"
tail -n +2 /etc/issue
echo `hostname`" login:"
sleep 10
# Reset the mouse pointer so it is visible again
unclutter -idle 5 -jitter 0 &
# Reset the audio volume
amixer -- sset Master $volume &> /dev/null


Stitch Together a Palindrome from Palindromic Substrings

Brachylog, 10 bytes
{s.↔}ᶠpc.↔

Try it online!
Fails (i.e. prints false.) if not possible.
Explanation
{   }ᶠ         Find all…
 s.              …substrings of the input…
  .↔             …which are their own reverse
      p        Take a permutation of this list of palindromes
       c.      The output is the concatenation of this permutation
        .↔     The output is its own reverse


Coding in song - Representing music lyrics in a programming language of your choosing

Python - 8+4+15 = 27 points

Here's on couple of stanzas from The Hunting of the Snark by Lewis Carroll.
It calculates a number, based on the algorithm suggested in the poem, and uses it to state a proof about the voice of the jubjub.

class taking:
    def __init__(self, n): convenient.val = (n)
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass
def a(x,y): x.val = y(x.val); return True
class We:
    def __init__(self): self.val=0
    def __add(self, y): return y+sum(self.x)
    def add(self, *x): self.x = x; return self.__add
    def multiply(self,x,by,diminished_by): self.val *= by-diminished_by
    def proceed2divide(self,x,by): self.val /= by
    def subtract(self,x): self.val -= x; return True
perfectly = lambda x: x and not not x
def must_be(x):
    if x:
        print "\n".join(["Tis the %s of the Jubjub!"%["voice","note","song"][x%3] for x in range(out.val)])
        return out.val
out=convenient=as_you_see=we=then=the=We()
_ = exactly = 15
with\
\
    taking(3) as the_subject_to_reason_about:
    a(convenient, #2 state
    we.add(7,_ & 10)) and then.multiply(out,
    by=1000, diminished_by=8)

    the_result = we.proceed2divide(as_you_see,
    by=992)
    then.subtract(17) and the; answer = must_be(
    exactly and perfectly(True))

The original text:

  "Taking Three as the subject to reason about—
     A convenient number to state—
   We add Seven, and Ten, and then multiply out
     By One Thousand diminished by Eight.

  "The result we proceed to divide, as you see,
     By Nine Hundred and Ninety Two:
   Then subtract Seventeen, and the answer must be
     Exactly and perfectly true.


Check if all vowels exist in pairs of strings

Java openjdk8

Using bit arrays,

Coding each word on an int where if a is present the lowest bit is 1, if e the second is 1, etc.

For example password has a and o, so its code is 1|8 == 9  == 0b01001.
As we only need the number of pairs we can store the number of words for each code in an array of size 32.

Then for each pair of different indexes except the last (31) where first is less than second and where bitwise or of indexes is 31,  we multiply the number of words with code, and the last is particular because it's the only one that can make a pair with a word of the same code, and also with any word.

public static void main( String[] args ) {
    int[] a = new int[ 32 ];
    int count = 0;
    try (Scanner scan = new Scanner( System.in )) {
        while ( scan.hasNext() ) {
            String s = scan.next();
            a[ code( s ) ]++;
        }
    }

    int t = 0;
    for ( int i = 0 ; i < 31 ; ++i ) {
        count += a[ i ];
        for ( int j = i + 1 ; j < 31 ; ++j ) {
            if ( ( i | j ) == 31 ) {
                t += a[ i ] * a[ j ];
            }
        }
    }

    t += a[ 31 ] * count + a[ 31 ] * ( a[ 31 ] - 1 ) / 2;
    System.out.println( t );
}

// a e i o u
// 1 2 4 8 16
public static int code( String s ) {
    int r = 0;
    for ( char c : s.toCharArray() ) {
        r |= c == 'a' ? 1 : c == 'e' ? 2 : c == 'i' ? 4 : c == 'o' ? 8 : c == 'u' ? 16 : 0;
    }
    return r;
}

TIO

C++

translating to C++ is straightforward

test with 100 first words

test on TIO with 10000 words of dataset

1968503

Real time: 0.419 s
User time: 0.315 s
Sys. time: 0.099 s
CPU share: 98.83 %
Exit code: 0


Pyth, 92 bytes

I!%vzhK%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2)J*L/vzhKtKeoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ

It's quite a monster.

Try it online: Demonstration. The input format is c\n[a,b] and the output format is [x,y].

In the case that no integer solution exists, I'll print nothing, and in the case that no natural integer solution exists, I'll simply print a random integer solution.

Explanation (Rough Overview)

At first I'll find an integer solution to the equation ax + by = gcd(a,b) by using the Extended Euclidean algorithm.
Then I'll modify the solution (my multiplying a and b with c/gcd(a,b)) to get an integer solution of ax + by = c. This works, if c/gcd(a,b) is an integer. Otherwise there doesn't exist a solution.
All the other integer solutions have the form a(x+n*b/d) + b(y-n*a/d) = c  with d = gcd(a,b) for integer n. Using the two inequalities x+n*b/d >= 0 and y-n*a/d >= 0 I can determine 6 possible values for n. I'll try all 6 of them and print the solution with the highest lowest coefficient.

Explanation (Detailed)

The first step is to find an integer solution to the equation ax' + by' = gcd(a,b). This can be done by using the extended Euclidean algorithm. You can get an idea on how it works at Wikipedia. The only difference is, that instead of using 3 columns (r_i s_i t_i) I'll use 6 columns (r_i-1 r_i s_i-1 s_i t_i-1 t_i). This way I don't have to keep the last two rows in memory, only the last one.

K%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2)   implicit: Q = [a,b] (from input)
                                     j9 2    convert 9 to base 2: [1,0,0,1]
                            + Q              add to Q => [a,b,1,0,0,1]
                                             this is the initial row
   u                                     )   start with G = ^ and update G repeatedly
                                             by the following expression, until
                                             the value of G doesn't change anymore
    ?                   @G1                    if G[1] != 0:
                     cG2                         split G into parts of 2
      m                                          map the parts d to:
       ,                                           the pair
        ed                                           d[1]
          -hd*ed/F<G2                                d[0]-d[1]*G[0]/G[1]
     s                                           unfold
                                               else:
                           G                     G (don't change it, stop criterion for u)
 %2                                          take every second element
                                             we get the list [gcd(a,b),x',y']
K                                            store this list in K
                             ~Q,hQ_eQ        afterwards change Q to [Q[0],-Q[1]] = [a,-b]
                                             This will be important for the other parts.

Now I want to find a solution to ax + by = c. This is possible only, when c mod gcd(a,b) == 0. If this equation is satisfied, I simply multiplying x',y' with c/gcd(a,b).

I!%vzhK...J*L/vzhKtK   implicit: z = c in string format (from input)
  %vzhK                evaluated(z) mod K[0] (=gcd(a,b))
I!                     if not ^ than:
             /vzhK        c/K[0]
           *L     tK      multipy ^ to each element in K[1:] (=[x',y'])
          J               and store the result in J, this is now [x,y]

We have an integer solution for ax + by = c. Notice, that x, y or both may be negative. So our goal is to transform these to non-negative.

The nice thing about Diophantine equations is, that we can describe all solution using only one initial solution. If (x,y) is a solution, that all other solutions are of the form (x-n*b/gcd(a,b),y+n*a/gcd(a,b)) for n integer.

Therefore we want to find a n, where x-n*b/gcd(a,b) >= 0 and y+n*a/gcd(a,b >= 0. After some transformation we end up with the two inequalities n >= -x*gcd(a,b)/b and n >= y*gcd(a,b)/a. Notice that the inequality symbol might look in the other direction due the division with a potential negative a or b. I don't care that much about it, I simply say that one number of -x*gcd(a,b)/b - 1, -x*gcd(a,b)/b, -x*gcd(a,b)/b + 1 definitly satisfies inequality 1, and one number of y*gcd(a,b)/a - 1, y*gcd(a,b)/a, y*gcd(a,b)/a + 1 satisfies inequality 2. It there is a n, that satisfies both inequalities, one of the 6 numbers also does.

Then I calculate the new solutions (x-n*b/gcd(a,b),y+n*a/gcd(a,b)) for all 6 possible values of n. And I print the solution with the highest lowest value.

eoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ
                               _J    reverse J => [y,x]
                           *LhK      multiply each value with K[0] => [y*gcd,x*gcd]
                         /V      Q   vectorized division => [y*gcd/a,-x*gcd/b]
                  m                  map each d of ^ to:
                      tM3              [-1,0,1]
                   +Ld                 add d to each ^
                 s                   unfold
                                     these are the possible values for n
    m                                map each d (actually n) of ^ to:
             *LdQ                      multiply d to Q => [a*n,-b*n]
            _                          reverse => [-b*n,a*n]
        /RhK                           divide by K[0] => [-b*n/gcd,a*n/gcd]
     -VJ                               vectorized subtraction with J
                                       => [x+b*n/gcd,y-a*n/gcd]
 oSN                                 order the solutions by their sorted order
e                                    print the last one

The sort by their sorted order thing works the following way. I'm using the example 2x + 3y = 11

I sort each of the 6 solutions (this are called keys), and sort the original solutions by their keys:

solutions: [1, 3], [4, 1], [7, -1], [-5, 7], [-2, 5], [1, 3]
keys:      [1, 3], [1, 4], [-1, 7], [-5, 7], [-2, 5], [1, 3]
sort by key:
solutions: [-5, 7], [-2, 5], [7, -1], [1, 3], [1, 3], [4, 1]
keys:      [-5, 7], [-2, 5], [-1, 7], [1, 3], [1, 3], [1, 4]

This sorts a complete non-negative solution to the end (if there is any).


Non-golfed haskell, 32

f a n t=takeWhile(<=t)[a,a+n..]

I'd love to change takeWhile to take, but integer division can't be done with /, it needs to be done with div. If I go with / then I need to do implicit conversion which makes it that much longer.


Calculate hamming weight with low hamming weight

J, weight 34

+/,#:a.i.

Usage - place the string to be measured in quotes at the end:

   +/,#:a.i.'+/,#:a.i.'
34

Alternatively, taking input from the keyboard (weight 54):

   +/,#:a.i.1!:1[1
hello
21


Transformers in Disguise (Robbers' Thread)

Node.js v10.9.0, Arnauld

o=>[...o].sort(n=>16&(j+=13),j=9).join``

Try it online!

This outputs this particular permutation of itself when using Node's current sorting algorithm:

&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t

An insightful comment by l4m2 gave me a headstart, but I had to write a brute-forcer to figure out which permutation of digits gives the correct output...


Haskell, 229 bytes

e=zip[0..]
x!y=abs$x-y
k=e["Q W E R T Y U I O P"," A S D F G H J K L","  Z X C V B N M"]
f c=filter(any(<"a").words)[unlines[[[z..]!!sum[32|z>'@',max(2*y!i)(y!i+x!j)/=d*2]|(x,z)<-e m]|(y,m)<-k]|(i,l)<-k,(j,h)<-e l,c==h,d<-[0..9]]

Try it online!
f takes an uppercase char argument and returns a list of multiline strings.
It loops over the keyboard layout looking for (i,j), the position of the given character. When it finds it, for each d<-[0..9] it generates a string (unlines[…]) of the keyboard with all letters not d hex-steps away lowercased. It never takes longer than 10 steps for the wave to leave the keyboard, so this is OK. Finally, strings that don't contain any uppercase letters are filtered away from the result.
I calculate the hex distance between two points on the keyboard as: \$ \max\left(2|y_1-y_2|, |x_1-x_2|+|y_1-y_2|\right)\$. Here are some distances around a point under this metric:
   6666666                                 6 6 6 6
  654444456                               6 4 4 4 6
 65432223456                             6 4 2 2 4 6
6543210123456  --> on staggered grid:   6 4 2 0 2 4 6
 65432223456                             6 4 2 2 4 6
  654444456                               6 4 4 4 6
   6666666                                 6 6 6 6


Convert negadecimal to decimal (and back)

05AB1E, 6 bytes
Nega to Deca
T(ö

Try it online!
Deca to Nega
T(в

Try it online!


Python, 31 chars

Similarly to scleaver, define the generator like this:

from random import randint
n=0
def r():
    global n;n+=1
    return randint(1,n)

Then a function to return dice rolls:

D=lambda:eval('r(),'*6)[-1]%6+1

Call D() any time you need a uniformly random dice roll.


How many carries do I need to add these two numbers?

Mathematica, 46 39 bytes
x=Tr@*IntegerDigits;(x@#+x@#2-x@+##)/9&

input

[348,51]

-7 bytes from JungHwan


GolfScript (28 25 24 23 chars)

~1.{(2$+}{.@+2$%}/+\-,)

Takes input in stdin, leaves it on stdout (or the stack, if you want to further process it...)

This correctly handles the corner cases (Demo).

As a point of interest to GolfScript programmers, I think this is the first program I've written with an unfold which actually came out shorter than the other approaches I tried.


Smallest positive number whose y-th power is divisible by x

Brachylog, 19 17 16 15 12 bytes
2 bytes saved thanks to @LeakyNun.
:[I:1]*$r=#>

Try it online!
Explanation
               Input = [X, Y]
:[I:1]*        Get a list [X*I, Y] (I being any integer at this point)
       $r=     Get the first integer which is the Yth root of X*I
          #>   This integer must be strictly positive
               This integer is the Output


Shortest undefined behavior sample in C++

int main(){main;}

  3.6.1 Main function [basic.start.main]

  3 - [...] The function main shall not be used within a program.

Edit: this is diagnosable, so not UB.

int main(){for(;;);}

  1.10 Multi-threaded executions and data races [intro.multithread]

  24 - The implementation may assume that any thread will eventually do one of the following:
  — terminate,
  — make a call to a library I/O function,
  — access or modify a volatile object, or
  — perform a synchronization operation or an atomic operation.

int main(){int i=i;}

  4.1 Lvalue-to-rvalue conversion [conv.lval]

  1 - [...] If the object to which the glvalue refers is [...] uninitialized, a program
  that necessitates this conversion has undeﬁned behavior.

//^L.

Here ^L is the form feed character, which is part of the basic character set.  4 characters (a newline is not required per 2.2:2).  Undefined behaviour is per

  2.8 Comments [lex.comment]

  1 - If there is a
  form-feed or a vertical-tab character in [a //-style] comment, only white-space characters shall appear between it
  and the new-line that terminates the comment; no diagnostic is required.


Use the return value from predicates

In Husk, functions that test their inputs for some property will usually return a meaningful result in truthy cases, as any positive integer is truthy.

Examples:

≠  Numbers: Absolute difference
   Chars:   Absolute difference of code points
   Lists:   First Index where the differ

Comparisons <, >, ≤, ≥:

For strict comparisons:
Numbers,Chars:  max 0 (the appropriate difference¹)
Lists: The first index where the comparison between the two lists is true

For non-strict comparisons:
Numbers,Chars: max 0 (the appropriate difference + 1)
Lists: Either the result of the strict comparison or, if they are equal,
       the length of the list + 1

ṗ  Index into the list of prime numbers

V  The index of the first element for which the condition is true

€  The first index of that element/substring in the list

£  Works like €

&  Given two arguments of the same type will return the second argument if false,
   otherwise will return the first argument

|  Given two arguments of the same type will return the second argument if true,
   otherwise will return the first argument

¦  Return the quotient if divisibility holds

Λ,E,Ë  Will all return length+1 in truthy cases

Char predicates:
□,±,√,D,½  will each return the codepoint of its argument on truthy cases

¹ appropriate difference means difference of code points for chars. It also refers to the argument order. i.e For <x y, would be x-y


bash - 65

[ `date +%d%m -r $0` = `date +%d%m` ]&&echo Happy birthday to me!

Thanks to ugoren, ace and nyuszika7h for help.


Python 2, 67 66 bytes

lambda s,k:`sorted(s,key=lambda c:`k.index(3-ord(c)/32)`+c)`[2::5]

Test it on Ideone.


Javascript, 524 bytes
Hi, this is my first ever post here, so excuse me if I'm still ignorant on some stuff, I think I stayed within the rules though.
k=[8,9,"130","133","161","162","171","172","181","182",19,20,27,44,45,46,48,49,50,51,52,53,54,55,56,57,144,145,186,187,188,189,190,191,192,219,220,221,222];for(i=32;i<124;i+=1){i<41?k.push(i):i>64?i<91?k.push(i):i>95?i!=108?k.push(i):0:0:0}d=[13,16,17,18];m=document.addEventListener;c=console.log;m("keydown",e=>{e.preventDefault()});m("keyup",e=>{c(e.code);if(d.includes(e.which)){l=e.which+""+e.location;if(k.includes(l)){k.splice(k.indexOf(l),1)}}else if(k.includes(e.which)){k.splice(k.indexOf(e.which),1)}c(k.length)})

It seems buggy if I don't use Chrome, but you can try it out here.
(be sure to open the console before you focus on the example window, as the default functionality of F12 is prevented)
Overview
The program makes an array of all the 101 "keycodes". Some are written explicitly, some sequences are added with a for loop and some are stored as strings. I have a seperate array for the "double" keycodes, since left and right control for instance give the same keycode. They also give a location, however, so I combine the keycodes with the locations as strings in the array. From there it's just an eventlistener that prevents default keydown functionality (don't wanna refresh with F5 in this case) and a seperate eventlistener for keyup, because every single key can be detected on keydown, EXCEPT FOR PRINTSCREEN.
After every keyup event the remaining keys (aka the length of the array) gets logged, as well as the name of the keycode (so there is the distinction between left and right shift, etc). I wasn't sure if that was a requirement, if not you can subtract another 10 bytes from the score.
Limitations

It only seems to work well in Chrome

I hope this answer is appreciated and please let me know if I've done anything wrong.


Build an EBCDIC converter using NAND logic gates

727 Gates

How I did it:

turned the code page translation from wikipedia into an appropriately formatted truth table using Excel (15 minutes)
minimized the truth table using Espresso (5 minutes, 30 minutes on 1st iteration getting back into the saddle)
fed the minimized truth table into a schematic generator (1 minute)
iterated on 2&3 until I got a reasonable answer (<1 hour)
turned the schematic into an uploadable image (30 min, %$#@! Microsoft)

Here's the 100% NAND gate result:

If I was actually going to implement this, I'd drop the NAND-centric scoring. Building XOR gates out of NANDs is a big waste of transistors. Then I'd start worrying about UMC, fire up the FPGA design tools, maybe break out the HDL manuals, etc. Whew! I love software.

NB, for hobbyists interested in FPGAs, I'll recommend FPGA4fun.


Jelly,  15 13  12 bytes

-2 thanks to Dennis (using a Link rather than a chain allows right to be used implicitly by ¡; No need to wrap the 1 in a list due to the fact that Jelly prints lists of one item the same as the item)
-1 thanks to Erik the Outgolfer (use Ɗ to save the newline from using Ç)

1×€³§JḤ$¦ẎƊ¡

A full program printing a list in Jelly format (so [1] is printed as 1)

Try it online!

How?

1×€³§JḤ$¦ẎƊ¡ - Main link: segmentLengths; iterations
1            - literal 1 (start with a single segment of length 1)
           ¡ - repeat...
             - ...times: implicitly use chain's right argument, iterations
          Ɗ  - ...do: last 3 links as a monad (with 1 then the previous output):
   ³         - (1) program's 3rd argument = segmentLengths
 ×€          -  1  multiply €ach (e.g. [1,2,3] ×€ [1,2,1] = [[1,4,3],[2,4,2],[3,6,3]])
        ¦    -  2  sparse application...
       $     - (2) ...to: indices: last two links as a monad:
     J       - (2)          range of length = [1,2,3,...,numberOfLists]
      Ḥ      - (2)          double            [2,4,6,...] (note: out-of bounds are ignored by ¦)
    §        - (2) ...of: sum each (i.e. total the now split empty spaces)
         Ẏ   -  3  tighten (e.g. [[1,2,3],4,[5,6,7]] -> [1,2,3,4,5,6,7])
             - implicit print


GolfScript (10 bytes)

~(\10base=

This assumes input is as a string (e.g. via stdin). If it's as two integers on the stack, the initial ~ should be removed, saving 1 char.

If the base conversion is considered to fall foul of the built-in functions rule, I have a 16-char alternative:

~~)\{}{10/}/=10%


Jelly, 4 bytes

⁾ṘȮṘ

Try it online!

(Equivalent to the 5-byte: “ṘȮ”Ṙ)

Exponentially spawns:

“ṘȮ”ṘȮ
“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ

Since Ṙ is a monadic atom which prints a Jelly representation of its input and then yields it's input, and Ȯ is a monadic atom which prints its input and yields it's input (neither printing any newlines), while “...” defines a list of characters. So each “ṘȮ”Ṙ prints “ṘȮ” and yields to the following Ȯ which prints ṘȮ and yields... a trailing Ȯ finally yields for the programs return value, which is implicitly printed, so the pattern will continue until resources no longer suffice.


T-SQL, 442 441 426 355 349 344 bytes
DECLARE @ VARCHAR(MAX)=REPLACE(REPLACE(REPLACE('DECLARE @a5MULTIPOINT((0 31),(19 -2),(-19 -2))'',@b5MULTIPOINT((0 39),(26 -6),(-26 -6))'',@5POINT(0 9)'',@d5LINESTRING(0 9,0 99,90 -43,0 9,-90 -43)''SELECT @a830%b821)%86)%d81)%d84%819))).STUnion(@827%820)).STIntersection(@b819)))'
,8,'.STBuffer('),5,' GEOMETRY='''),'%',').STDifference(@')EXEC(@)

Saved 70+ bytes by using REPLACE() for long keywords and executing as dynamic SQL. See the post-replacement code in the screenshot below.
I doubled the coordinate values from the sample illustration and moved up 9 units, to reduce the number of decimals displayed.
This was done in SQL 2017, using geo-spatial features introduced in SQL 2008. Lots of useful built-in geometry functions, including STBuffer, which gives me a simple way to define circles of different sizes around a point.
Visual of output, with annotated code:

For more T-SQL drawing, see my Easter Bunny.
For more practical applications of this tech in SQL, read this article or watch this video. SE even has a related site, gis.stackexchange.com.
Edits:

Saved 1 byte by changing a coordinate from 104 to 99.
Saved 15 bytes by taking the STDifference of a STUnion of objects, instead of each individually.
Saved 71 bytes by using REPLACE() on repeated keywords, then executing as dynamic SQL. Reverted Edit 2, to leave more replacements of STDifference.
Saved 4 bytes by moving the center up 9 units, which changed a few coordinates to single (negative) digits. This also freed up the numeral 5 to use as a replacement character instead of '#', saving 2 more bytes on the quotes.
Saved 5 bytes by moving ) into the STDifference replacement string; thanks, @Nicholas!


Let's practice the scoring rules of 421!


How many dice can you roll without rolling the most probable number

Python 2, 70 bytes

from random import*
n=2
while eval("+randrange(6)-2.5"*n):print n;n+=2

Try it online!

The trick is to compute the sum by evaling a string the looks like

'+randrange(6)-2.5+randrange(6)-2.5'

with n copies of the expression concatenated. The randrange(6) outputs a random number from [0,1,2,3,4,5], which is shifted down by 2.5 to have average of 0. When the sum if 0, the while condition fails and the loop terminates.

An alternative using map was 4 bytes longer:

from random import*
n=2
while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2

I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter

randrange(6)-2.5
randint(0,5)-2.5
randrange(6)*2-5
uniform(-3,3)//1


Retina, 88 bytes

+is`(?<![a-z~])([a-z~]+)(?=([a-z]+)+[^a-z~].*(?<=[\n,]\1(?(2)!)(?<-2>~\2)+[\n,]))
$1~
\n.*
<empty>

For counting purposes, each line goes into a separate file, \n are replaced with actual newline characters and <empty> is an empty file. For convenience, you can run the above code from a single file (where <empty> is an empty line) if you use the -s interpreter flag.


MATL, 41 bytes

itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx

The output is 1 or 0.

Explanation

i              % get input array
tn2\           % is size odd?
?              % if that's the case
  YNh          % concat NaN at the end
]              % end if
tn             % get size of input array
t1+:           % vector 1:n+1, where n is input size, so loop will be entered even with []
"              % for loop
  x[]2e!PY)    % delete result from previous iteration and do the shuffling
  ttZN~)       % remove NaN, if there's any
  tS=A         % check if array is sorted
  t.           % copy the result. If true, break loop
]              % end for
wx             % remove unwanted intermediate result

Example

>> matl itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx
> [1,1,2,3,5,8,13,21]
1


How many times will you have to golf a quine?

Python 2, 50 bytes

Note the trailing comma and newline.

s='s=%r;print s%%s*input(),\n';print s%s*input(),

Try it online!


Python 2, \$O(2^{n/2})\$

import sys
def subsetsum(nums, target):
#    totalsum = sum(nums)
#    if(totalsum == target):
#        return target
#    if(totalsum < target):
#        return -1

    sumsA = {}
    sumsB = {}
    for n in nums[::2]:
        for k,v in sumsA.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsA:
                sumsA[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsA loop: "
                    return target
    minsum = sys.maxsize
    for n in nums[1::2]:
        for k,v in sumsB.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsB:
                sumsB[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsB loop: "
                    return target
                for a in sumsA:
                    combsum = a + newsum
                    if combsum == target:
                        print "target found in combined sumsA and sumsB loop: "
                        return target
                    if combsum > target and combsum < minsum:
                        minsum = combsum
    print "target",target,"not found, so return the closest alternative: "
    return minsum

# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)

Try it online.
My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.
The program uses the Knapsack Meet-in-the-middle approach. It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.


Bridges are metaphors for everything in ASCII Art

Python 2 , 173 bytes

i=input()
f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'
b=(i*'/--')[:~-i/2]
for x in range(1,~-i/2):print f((len(b)-x)*'-'+b[:x]).replace('-',' ')
print f(b)

Mirror the value of b and add the central "-"
f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'
Base pattern (right half of the bottom line)
b=(i*'/--')[:~-i/2]
Loop for non-bottom layers
for x in range(1,~-i/2):
Get the first x characters of the base pattern and complete with "-"
(len(b)-x)*'-'+b[:x]
Replace all - with spaces to print all the layers (except bottom)
print f().replace('-',' ')
Print bottom layer
print f(b)


Find the maximum of 3 numbers without branching

Javascript
6 tokens
function maxOf3(a, b, c) {
    (b>a) && (a=b);
    (c>a) && (a=c);
    return a;
}


Brackets/Structures autocomplete
Totally not stolen from Tips for golfing in keg because Vyxal totally isn't supposed to be keg but 69 times better
If you have a structure (e.g. if/for/while/function/lambda) at the end of your program, and EOF follows, you can leave the closing bracket/semicolon off. Note that this only applies if you are submitting a full program.
For example:
9(0,)

Can be shortened to:
9(0,

And:
{:1=[1,]}

Can be shortened to:
{:1=[1,


Go south, east and north, come to the same place

CJam, 62 chars

{4e4/:Y\9e-3*:X90-P180/:Q*mc/XY2$m](/mCQ/+_90<\@XY@m[)/mCQ/-?}

This is a block (subroutine) which takes x y on the stack and leaves the solution on the stack.

Online demo

I'm interpreting the spec to allow returning 90 as an "impossible value" if there is no other solution. If that interpretation is disallowed, I think the best fix would be

{4e4/:Y\9e-3*:X90-P180/:Q*mc/[XY2$m](/mCQ/+\XY@m[)/mCQ/--91]{90<}=}


JavaScript (ES7),  75  72 bytes
Expects an array of ASCII codes.
a=>a.map(g=k=>--d-1?g(k,d=n%d?d:++n):p*=n**(17088/k%75%14|1),d=p=n=1)&&p

Try it online!
Magic formula
The formula 17088/k%75%14|1 was found by injecting random values into several handcrafted templates.
More specifically, the template for this one was `${p}/k%${m0}%${m1}|1` with \$0<p<10^5\$, \$0<m_0<10^3\$ and \$12\le m_1 \le 15\$.
 char. |  k  | floor(17088 / k) | mod 75 | mod 14 | OR 1
-------+-----+------------------+--------+--------+------
  '('  |  40 |        427       |   52   |   10   |  11
  ')'  |  41 |        416       |   41   |   13   |  13
  '0'  |  48 |        356       |   56   |    0   |   1
  'A'  |  65 |        262       |   37   |    9   |   9
  's'  | 115 |        148       |   73   |    3   |   3
  '|'  | 124 |        137       |   62   |    6   |   7
  '~'  | 126 |        135       |   60   |    4   |   5

Commented
a =>                // a[] = input
a.map(g = k =>      // for each ASCII code k in a[]:
  --d - 1 ?         //   decrement d; if d is not equal to 1:
    g(              //     do a recursive call to the callback function:
      k,            //       pass k unchanged
      d =           //       update d:
        n % d ? d   //         if d is not a divisor of n, leave d unchanged
              : ++n //         otherwise, increment n and set d = n
    )               //     end of recursive call
  :                 //   else (n is now the next prime):
    p *=            //     multiply p by
      n ** (        //     n raised to the power of
        17088 / k   //     the odd positive integer <= 13 which is obtained
        % 75 % 14   //     by applying our magic formula to k
        | 1         //
      ),            //
  d = p = n = 1     //   start with d = p = n = 1
) && p              // end of map(); return p


CJam, 68 66 58 55 bytes

This is too long for now. But a start.

ri:K"!;tK"206b4b<{S5*a*"+--+ "a:I+K)2/)"|  | "e]I+}%zN*

UPDATE: Now hardcoding for inputs till 15 instead of calculating the offset. Suggestion by Sp3000

Try it online here


First, a few neat things about list comprehensions, from a Haskell perspective:

The list monad in Haskell is set up so any list comprehension can be transformed into do notation rather easily:

> [(i,j) | i <- [1..3], j <- [1..3]]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
> do {i <- [1..3]; j <- [1..3]; return (i,j)}
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

Haskell has a sequence function that takes a list of "actions" in a monad and returns a list of the results:

> sequence [getLine, getLine, getLine]
one
two
three
["one","two","three"]

Consequently, using sequence with the list monad gives you combinations for free:

> do {i <- [1..3]; j <- [1..3]; return [i,j]}
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
> sequence [[1..3], [1..3]]
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]

Hence, the sequence function is very similar to the compr function asked for.  It just needs to be wrapped and mapped a bit:

function compr()
{
    $args = func_get_args();
    $f = $args[0];
    $call_f = function($array) use ($f) {
        return call_user_func_array($f, $array);
    };
    return array_map($call_f, sequence(listMonad(), array_slice($args, 1)));
}

Now, without further ado, here is a nearly direct translation of the list monad and sequence function from Haskell to PHP:

# instance  Monad []  where
#     m >>= k          = concat (map k m)
#     return x         = [x]
#     fail s           = []
function listMonad()
{
    return (object) array(
        'bind'   => function($m, $k) {
            return call_user_func_array('array_merge', array_map($k, $m));
        },
        'return' => function($x) { return array($x); },
        'fail'   => function($s) { return array(); }
    );
}

# sequence       :: Monad m => [m a] -> m [a]
# sequence       =  foldr mcons (return [])
#                     where mcons p q = p >>= \x -> q >>= \y -> return (x:y)
function sequence($monad, $list)
{
    $mcons =
        function($p, $q) use ($monad) {
            return call_user_func($monad->bind, $p,
                function($x) use ($monad, $q) {
                    return call_user_func($monad->bind, $q,
                        function($y) use ($monad, $x) {
                            return call_user_func($monad->return, cons($x, $y));});});};
    return foldr($mcons, call_user_func($monad->return, array()), $list);
}

# foldr            :: (a -> b -> b) -> b -> [a] -> b
# foldr f z []     =  z
# foldr f z (x:xs) =  f x (foldr f z xs)
function foldr($f, $z, $xs)
{
    if (empty($xs))
        return $z;
    return call_user_func($f, $xs[0], foldr($f, $z, array_slice($xs, 1)));
}

function cons($x, $xs)
{
    return array_merge(array($x), $xs);
}

I believe this meets all four of your criteria, especially the "inordinate amount of nested parenthesis/brackets" part.

Test code:

function printList($show, $list)
{
    echo showList($show, $list) . "\n";
}

function showList($show, $list)
{
    $str = "[";
    foreach($list as $x) {
        if ($str !== "[")
            $str .= ",";
        $str .= call_user_func($show, $x);
    }
    return $str . "]";
}

# Count in binary
printList('strval',
    compr(function($a, $b, $c, $d) {
        return "$a$b$c$d";
    }, array(0,1), array(0,1), array(0,1), array(0,1)));

# Combinations of items
printList(function($a) {return showList('strval', $a);},
    compr(function($a, $b, $c) {
        return array($a, $b, $c);
    }, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9)));

Output:

[0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111]
[[1,3,6],[1,3,7],[1,3,8],[1,3,9],[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,3,6],[2,3,7],[2,3,8],[2,3,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9]]


Insert a simulated Ken Thompson virus into a program

For some other languages, determining If the output of P is valid source code in the language you are using is almost impossible, unless you use/rewrite a compiler. For some other languages you can eval a string and catch for error, if any. However, for Mathematica, it is just check for if the head of the result is a function - Mathematica doesn't allow output invalid function, like 1!-!&.
So,
Mathematica, 209 bytes
(obviously can be golfed more, for example by assign long names to global variables)
With[{p=#,c=With[{p=#,c=6},If[#==="aNouIQ5xKvUfdZVzo0Xs","BOOM",With[{r=p@#},If[Head@r===Head@p,(c/.3!->c)[r],r]]]&]&},If[#==="aNouIQ5xKvUfdZVzo0Xs","BOOM",With[{r=p@#},If[Head@r===Head@p,(c/.3!->c)[r],r]]]&]&

The function takes a function as input, and output a function according to the specification.
Note that the input must be a pure function, not something like f[x_] := .... So all Mathematica built-in functions fail the criteria.
Although Mathematica have #0 parameter, I explicitly disallow that in my answer because a quine is not allowed to read the code of itself.
(I thought that question is trivial until I read the third rule)


Merging a dict compression referencing the original list into 1 line

dict_a = {t[0] : sum(tp[1] for tp in a if tp[0] == t[0]) for t in a}

Horribly slow, but hey it's a one liner!


Can this number be written in (3^x) - 1 format?

Mathematica, 21 16 bytes

-1&@@Log[3,#+1]&

Makes use of Mathematica's symbolic computation. If #+1 is a power of three then Log[3,#+1] will compute an integer result which is an atomic value. Otherwise we'll get Log[#+1]/Log[3] as is. Since this is not an atomic value, it's an expression which is always of the form head[val1,val2,...]. In this case it's actually something like Times[Power[Log[3], -1], Log[#+1]].

We distinguish between the two cases by applying another function to the result. What applying really does is that it replaces the head part of an expression. Since integer results are atomic, applying any function to them does nothing at all. In particular f @@ atom == atom.

However, in the other case, the head does get replaced. The function we're using is -1& which is a simple function that ignores its arguments and returns -1. So we get something -1&[Power[Log[3], -1], Log[#+1]] in non-integer cases, which evaluates directly to -1. Special casing via magic.


Get the lowest possible pylint score within 128 bytes of python


Python 2, 32 bytes

''*2;print"''*2;print"''*2;print

Try it online!

Based on my initial solution for the other variant of this puzzle.


Haskell, 263 261 247 243 characters

c[x]=[x]
c(x:"2")=[x,x]
c(x:_)=[x,x,x]
s!a@[x,y,z]=case s of
 'R'|x>0->[x,-z,y]
 'B'|y>0->[z,y,-x]
 'U'|z>0->[-y,x,z]
 'L'|x<0->[x,z,-y]
 'F'|y<0->[-z,y,x]
 'D'|z<0->[y,-x,z]
 _->a
r=[-2..2]
i=mapM id[r,r,r]
f w=i==foldr(map.(!))i(c=<<words w)

Rather straightworward algorithm; each cubelet is made out of 1,2,4 or 8 chunks encoding its position and orientation; 4 chunks per edge cubelet, 8 per corner cubelet, 7 cubelets are stationary.

c chomps each word of the input into a sequence of CW turns, and ! sends each chunk according to a turn. i is the identity position. f is the main function.

I'm not too happy with the chomp function, but I can't seem to find a way to shorten it either (@Nimi did, however)


CJam, 37 34 32 bytes

{e!Wf<{2*3ew{)f.-~W%.*:-V>},!}=}

Not sure if :-V is happy enough, but as K Zhang points out, there's the =} at the end. :)

This only prints one solution because removing duplicates would be more expensive.

Test it here.

Explanation

The idea is fairly simple. We generate all possible quadrilaterals (including all orderings of the points) and then just select the convex ones. We test convexity by looking at every pair of edges and checking that they're all turning in the same direction.

The turning sense can be obtained quite easily from a dot product. If you take the three consecutive points on a quadrilateral, and draw lines from the first to the second, and the first to the third, and then project the latter onto the perpendicular of the former... you get a number whose sign tells you whether these three points turn left or right. (I should probably add a diagram for this.) This "projecting onto the perpendicular" is sounds quite involved, but really just means that we reverse one of the two vectors and subtract the components after multiplication instead of adding them. So here's the code...

e!       e# Generate all permutations of the five input points.
Wf<      e# Discard the fifth point in each permutations, giving all
         e# possible quadrilaterals.
{        e# Select the first for which this block gives a truthy result...
  2*     e#   Double the list of points, so that it includes each cyclically
         e#   adjacent set of three points.
  3ew    e#   Get all sublists of length 3, i.e. all sets of three consecutive
         e#   points (with two duplicates).
  {      e#   Filter these sets of three points...
    )    e#     Pull off the last point.
    f.-  e#     Subtract it from the other two, giving vectors from it to
         e#     to those.
    ~    e#     Unwrap the array dumping both vectors on the stack.
    W%   e#     Reverse one of them.
    .*   e#     Element-wise multiplication.
    :-   e#     Subtract the second element from the first. This completes
         e#     the projection.
    V>   e#     Check whether it's greater than 0. This is *false* for right-
         e#     turning sets of three points.
  },     e#   If all corners are right-turning, this will result
         e#   in an empty array.
  !      e#   Logical NOT - hence, only quadrilaterals where all corners
         e#   are right-turning give something truthy.
}=


x86-64 Machine code - 23 22 20 19 bytes

Uses the AES-NI instruction set

66 0F 6E C1          movd        xmm0,ecx
66 0F 38 DD C1       aesenclast  xmm0,xmm1
0F 57 C1             xorps       xmm0,xmm1
66 0F 3A 14 C0 00    pextrb      eax,xmm0,0
C3                   ret

Using Windows calling conventions, takes in a byte and outputs a byte. It is not necessary to reverse the ShiftRows as it does not affect the first byte.


Python 2, sequence A138147 by xnor
Original:

print 10

Cracked:
print "1%s0"%10
      ^^^^^^^

Try it online!


Python, 27,797,402
Just to set the bar a little higher...
from sys import argv
verbose = len(argv) > 1
found = 0
for x in xrange(67108864, 94906266):
    found += 1
    if verbose:
        print "(%d, 0) (%d, 1)" % (x, x)
print found

It's easy to verify that for all 67,108,864 <= x <= 94,906,265 = floor(sqrt(253)) the pairs (x, 0) and (x, 1) are false positives.
Why it works: 67,108,864 = 226. Therfore, all numbers x in the above range are of the form 226 + x' for some 0 <= x' < 226.
For all positive e, (x + e)2 = x2 + 2xe + e2 = x2 + 227e + 2x'e + e2.
If we want to have  (x + e)2 = x2 + 1 we need at least 227e <= 1, that is, e <= 2-27
However, since the mantissa of double-precision floating point numbers is 52-bit wide, the smallest e such that x + e > x is e = 226 - 52 = 2-26.
In other words, the smallest representable number greater than x is x + 2-26 while the result of sqrt(x2 + 1) is at most x + 2-27.
Since the default IEEE-754 rounding mode is round-to-nearest; ties-to-even, it will always round to x and never to x + 2-26 (where the tie-break is really only relevant for x = 67,108,864, if at all. Any larger number will round to x regardless).

C++, 75,000,000+
Recall that 32 + 42 = 52.
What this means is that the point (4, 3) lies on the circle of radius 5 centered around the origin.
Actually, for all integers n, (4n, 3n) lies on such circle of radius 5n.
For large enough n (namely, such that 5n >= 226), we already know a false-positive for all points on this circle: (5n, 1).
Great! That's another 27,797,402 / 5 free false-positive pairs right there!
But why stop here? (3, 4, 5) is not the only such triplet.
This program looks for all positive integer triplets (a, b, c) such that a2 + b2 = c2, and counts false-positives in this fashion.
It gets to 70,000,000 false-positives pretty fast but then slows down considerably as the numbers grow.
Compile with g++ flspos.cpp -oflspos -std=c++11 -msse2 -mfpmath=sse -O3.
To verify the results, add -DVERIFY (this will be notably slower.)
Run with flspos. Any command-line argument for verbose mode.
#include <cstdio>
#include <cmath>
#include <cfloat>

using namespace std;

/* Make sure we actually work with 64-bit precision */
#if defined(VERIFY) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1
#   error "invalid FLT_EVAL_METHOD (did you forget `-msse2 -mfpmath=sse'?)"
#endif

template <typename T> inline long long sqr(T x) { return 1ll * x * x; }
template <typename T>
T gcd(T a, T b) { while (b) { T t = a; a = b; b = t % b; } return a; }

int main(int argc, const char* argv[]) {
    const bool verbose = argc > 1;

    const int min = 1 << 26;
    const int max = sqrt(1ll << 53);

    int found = 0;
    auto add = [=, &found] (int x1, int y1, int x2, int y2) {
#ifdef VERIFY
        auto n1 = sqr(x1) + sqr(y1), n2 = sqr(x2) + sqr(y2);
        if (n1 == n2 || sqrt(n1) != sqrt(n2)) {
            fprintf(stderr, "Wrong false-positive: (%d, %d) (%d, %d)\n",
                    x1, y1, x2, y2);
            return;
        }
#endif
        if (verbose) printf("(%d, %d) (%d, %d)\n", x1, x2, y1, y2);
        ++found;
    };

    for (int x = min; x <= max; ++x) add(x, 0,    x, 1);

    for (int a = 1; a < max; ++a) {
        auto a2b2 = sqr(a) + 1;
        for (int b = 1; b <= a; a2b2 += 2 * b + 1, ++b) {
            int c = sqrt(a2b2);
            if (a2b2 == sqr(c) && gcd(a, b) == 1) {
                int max_c = max / c;
                for (int n = (min + c - 1) / c; n <= max_c; ++n)
                    add(n * a, n * b,    n * c, 1);
            }
        }

        if (a % 512 == 0) printf("%d\n", found), fflush(stdout);
    }

    printf("%d\n", found);
}


Python 2, 182 bytes

x=p=6637
while~-p:x=p/2*x/p+2*10**999;p-=2
s="MThd\0\0\0\6\0\1\0\1\342\4MTrk\0\0\13\301\0\220"
for i in`x`:s+="JHGECA@><L\260"[~ord(i)%29]+'{<'
open('p.mid','w').write(s+"\0\377/\0")

`x` will produce 31415926...20198L. The trailing L is used to produce the final channel message byte, via the mapping ~ord(i)%29.
Outputs a single track Type 1 Midi file, named p.mid to the current working directory.
0000: 4d 54 68 64 00 00 00 06  MThd....  # Midi header, 6 bytes to follow
0008: 00 01 00 01              ....      # Type 1, 1 track
000c: e2 04                    â.        # (-)30 ticks per beat, 4 beats per second

000e: 4d 54 72 6b 00 00 0b c1  MTrk...Á  # Track header, 3009 bytes to follow
0016: 00 90 40 7b              ..@{      # Wait  0 ticks, play E4 (3), 97% volume
001a: 3c 3c 7b                 <<{       # Wait 60 ticks, play C4 (1), 97% volume
001d: 3c 41 7b                 <A{       # Wait 60 ticks, play F4 (4), 97% volume
0020: 3c 3c 7b                 <<{       # Wait 60 ticks, play C4 (1), 97% volume
0023: 3c 43 7b                 <C{       # Wait 60 ticks, play G4 (5), 97% volume
...
0bcf: 3c b0 7b 3c              <°{<      # Wait 60 ticks, all notes off
0bd3: 00 ff 2f 00              .ÿ/.      # End of track marker


Break tokens with comments
A neat fact I discovered a little while ago (and the impetus for this sort of tips question in the first place), is that a block comment allows you to split tokens apart without a space.
For example if you want to write
main=interact tail

Without using whitespace, parentheses or $ you can do the following:
main=interact{--}tail

Here {--} is a block comment, which normally would do nothing, however here placed between interact and tail it serves to prevent the two as being parsed as a single token, interacttail.
This could also be used to split other kinds of tokens for example:
main=print${--}-3

Here we split the $ and the - without using spaces or parentheses.
data{--}K=K

Here we split a keyword from a type declaration (which unlike the earlier example cannot be done with $).
Pretty much anywhere you would use a space outside a String or Char literal you can use a block comment instead.


Convert from binary to unary in 7x7 Manufactoria

21 20 19 parts! Ha!

http://pleasingfungus.com/Manufactoria/?lvl=32&code=q12:9f0;c12:8f3;g9:8f1;q9:9f4;b10:8f3;p10:9f0;r10:10f1;y11:9f0;g12:5f3;c12:6f3;r9:6f3;c9:7f2;r10:6f0;p10:7f2;q11:7f1;i12:7f7;p13:7f6;r13:6f0;c13:8f0;&ctm=Razors;Treat_the_input_as_a_binary_number_and_output_that_number_of_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0;

Edit 2: Back to the original design, but with two parts shaved off by creative reuse of conveyors.  The 7 × 7 board really does start to feel confining — I've come up with several ways to shrink this further, if I only had one more row of vertical space...


Chop off the matrix to get the desired sum

K (ngn/k), 39 bytes

{a@&y=x{+//x*(&/'b)&\:&/b:~x=y}/:a:,/x}

Try it online!

thanks @Adám for this explanation:

{…} function, x is M and y is S

 ,/x flatten M (these are the k candidates)

 a: assign to a

 x{…}/: apply the following function to each while using M as fixed left argument (x):

  x=y Boolean matrix indicating where elements of M equal the current k candidate

  ~ negate that

  b: assign that to b

  &/ AND reduction (finds columns without that k)

  (…)&\: AND that with each of the following:

   &/'b AND reduction of each (finds rows without that k)

  x* multiply M by that

  +// grand sum

 y= list of Booleans indicating where S equals those sums

 & indices of Trues

 a@ use that to index into the elements (the k candidates)


A small puzzle. Why does this code work the way it does?

First of all, the line *(&a-1) += a; is undefined behavior, so this could do anything depending on compiler version, flags used, alignment of the stars, etc.

That said, the reason why it works in your case is probably because &a-1 happens to point to the return address of x, and incrementing it by 8 causes the i = 0; to be skipped.


APL (Dyalog Extended), 8 7 6 bytesSBCS

Anonymous infix function. Takes s as left argument and w as a list of strings as right argument.

∪⍛⍳⍨↑¨

Try it online!

↑ take the first s characters from…
 ¨ each string in w

∪⍛…⍨ in the list of the ∪nique strings in that…
 ⍳ find the ɩndex of the first occurrence of each string


AWK -vn=, 9
a[$1]++<n

This is so competitive with the golfing-language answers, I feel like I might have misunderstood the question - did I?
The limit n is passed as a variable at the command line with -vn=<value>. The array is read from STDIN.
Try it online!


JavaScript (ES6), 29 bytes

a=>n=>a.map(b=>b.map(c=>c&n))

Input is a 2D array of 24-bit integers (e.g. [[0x0000ff,0x00ff00],[0xff0000,0xffffff]]) and 16711680 for red, 65280 for green, 255 for blue. If this isn't valid, try this instead:

JavaScript (ES6), 48 bytes

a=>n=>a.map(b=>b.map(c=>c.map((d,i)=>i==n?d:0)))

Input is a 3D array of color values and 0 for red, 1 for green, 2 for blue.


Java

Reflection is indeed the right way to go with abusing Java... but you need to go deeper than just tweaking some values.

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] array = (Integer[]) c.get(cache);
        array[132] = array[133];

        System.out.printf("%d",2 + 2);
    }
}

Output:

5

Explanation:

   You need to change it even deeper than you can typically access.  Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.Deep within the Integer class is a Flyweight of Integers.  This is an array of Integers from −128 to +127.  cache[132] is the spot where 4 would normally be.  Set it to 5.

Warning: Doing this in real code will make people very unhappy.

Code demo on ideone.


Mathematica, 142 bytes

Graphics[{Circle[],Line/@{{{c=Cos@t,0},{c,s=Sin@t},{0,s}},{{0,0},{1/c,0},{0,1/s},{0,0},{c,s}}},},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi}

I'm plotting for angles between 0.01 and 2π which conveniently skips any angles where one of the lines would become actually infinite. You can make a GIF from it by replacing Animate with Table, adding a step width of 0.1 say and then using Export on the result:

So I got a bit bored and thought I'd give the full-blown thing a go (with all lines and colours). I omitted the labels, because they are really annoying to position and just clutter everything up.

Animate[
  c = Cos@t;
  s = Sin@t;
  h = Sign@c;
  v = Sign@s;
  i = .1 h;
  j = .1 v;
  Graphics[{
    Thick,
    Circle[],
    Line /@ {{{c, -s}, {0, 0}, {c, s}}, {{-i, 0}, {-i, j}, {0,
        j}}, {{-i + c, 0}, {-i + c, j}, {c, j}}, {{c - .1 s,
        s + .1 c}, {1.1 c - .1 s, 1.1 s + .1 c}, 1.1 {c, s}}},
    Circle[{0, 0}, 0.1, {t, Round[t, Pi]}],
    Blue,
    Line /@ {{{0, 0}, {c, 0}}, {{0, s}, {c, s}}},
    Red,
    Line /@ {{{0, 0}, {0, s}}, {{c, 0}, {c, s}}},
    Darker@Green,
    Line[{{c, 0}, {h, 0}}],
    Cyan,
    Line[{{0, s}, {0, v}}],
    Lighter@Lighter@Magenta,
    Line[{{h, 0}, {1/c, 0}}],
    Darker@Darker@Green,
    Line[{{0, v}, {0, 1/s}}],
    Orange,
    Line[{{0, 1/s}, {c, s}}],
    Lighter@Brown,
    Line[{{1/c, 0}, {c, s}}],
    Gray,
    Line[{{c, 0}, {c, -s}}],
    Lighter@Gray,
    Line[{{c, s}, {h, 0}}],
    Lighter@Pink,
    Line /@ {{{-.45 h, 0}, {-.55 h, 0}}, {{-.45 h, 1/s}, {-.55 h,
        1/s}}},
    Arrowheads[{-.05, .05}],
    Arrow[{{-.5 h, 0}, {-.5 h, 1/s}}],
    Darker@Cyan,
    Line /@ {{{0, -.45 v}, {0, -.55 v}}, {{1/c, -.45 v}, {1/
         c, -.55 v}}},
    Arrow[{{0, -.5 v}, {1/c, -.5 v}}],
    Dashed,
    Black,
    Line[{{c, s}, 1.3 {c, s}}],
    Lighter@Pink,
    Line /@ {{{0, 0}, {-.5 h, 0}}, {{0, 1/s}, {-.5 h, 1/s}}},
    Darker@Cyan,
    Line /@ {{{0, 0}, {0, -.5 v}}, {{1/c, 0}, {1/c, -.5 v}}}
    }, PlotRange -> {r = {-2, 2}, r}],
  {t, 0.01, 2 Pi}
  ];

Enjoy!

And because this is still a code-golf question I golfed this down as well, to see how short I could get it. Currently, 719 bytes:

Graphics[{Thick,Arrowheads@{-.05,.05},(z=Circle)[],(n=Line)/@{{p={c=Cos@t,s=Sin@t},o={0,0},{c,-s}},{-{i=.1(h=Sign@c),0},{-i,j=.1(v=Sign@s)},{0,j}},{{-i+c,0},{-i+c,j},{c,j}},{p+(q={-.1s,.1c}),1.1p+q,1.1p}},z[o,0.1,{t,Round[t,Pi]}],{e=Dashed,n[{p,1.3p}]},Blue,n/@{{o,a={c,0}},{b={0,s},p}},Red,n/@{{o,b},{a,p}},g=(d=Darker)@Green,n@{a,{h,0}},y=Cyan,n@{b,{0,v}},(l=Lighter)@l@Magenta,n@{{h,0},f={1/c,0}},d@g,n@{{0,v},u={0,1/s}},Orange,n@{u,p},l@Brown,n@{f,p},r=Gray,n@{a,{c,-s}},l@r,n@{p,{h,0}},l@Pink,n/@{q={{-.45h,0},{-.55h,0}},{u,u}+q},Arrow@{q={-.5h,0},u+q},{e,n/@{{o,q},{u,u+q}}},d@y,n/@{q={{0,-.45v},{0,-.55v}},{f,f}+q},Arrow@{q={0,-.5v},f+q},{e,n/@{{o,q},{f,f+q}}}},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi,0.05}


Frequency Distribution of Multiple Dice Rolls

Octave, 38 bytes

@(a,b)round(ifft(fft((a:a*b<a+b)).^a))

Try it online!
Explanation
Adding independent random variables corresponds to convolving their probability mass functions (PMF), or multiplying their characteristic functions (CF). Thus the CF of the sum of a independent, identically distributed variables is given by that of a single variable raised to the power of a.
The CF is essentially the Fourier transform of the PMF, and can thus be computed via a FFT. The PMF of a single b-sided die is uniform on 1, 2, ..., b. However, two modifications are required:

1 is used instead of the actual probability values (1/b). This way the result will be de-normalized and will contain integers as required.
Padding with zeros is needed so that the FFT output has the appropriate size (a*b-a+1) and the implicit periodic behaviour assumed by the FFT doesn't affect the results.

Once the characteristic function of the sum has been obtained, an inverse FFT is used to compute the final result, and rounding is applied to correct for floating-point inaccuracies.
Example
Consider inputs a=2, b=6. The code a:a*b<a+b builds a vector with b=6 ones, zero-padded to size a*b-a+1:
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

Then fft(...) gives
[36, -11.8-3.48i, 0.228+0.147i, -0.949-1.09i, 0.147+0.321i, -0.083-0.577i, -0.083+0.577i, 0.147-0.321i, -0.949+1.09i, 0.228-0.147i, -11.8+3.48i]

One can almost recognize the sinc function here (Fourier transform of a rectangular pulse).
(...).^a raises each entry to a and then ifft(...) takes the inverse FFT, which gives
[1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]

Although the results in this case are exactly integers, in general there may be relative errors of the order of 1e-16, which is why round(...) is needed.


War is peace. Freedom is slavery. Ignorance is strength

05AB1E, 30 bytes

05AB1E uses CP-1252.

“ignorance¤í‡î—™šÔÃÒry“#DIk1^è

Try it online! or as a Test suite

Explanation

The straight forward approach

Push the string ignorance strength war peace freedom slavery
Split on spaces
Get the index of the input in the list
XOR the index with 1
Get the element in the list at that index


Jelly, 3 bytes

FṢṁ

Try it online!

Explanation:

Flatten the list
Ṣort the flattened list
ṁold the sorted flatten list in the shape of the input.


Given a number, print out its "collective sum"

05AB1E,  4  3 bytes

-1 thanks to Kevin Cruijssen (use of € avoiding a })

€£O

Try it online!

How?

€£O - implicit input   e.g. 2315
€   - map with:
 £  -   head to             23, 231, 2, 2315
  O - sum                   2571


Ruby, 153 147 140 characters

h,*d=s=gets.chop.split(?|)
puts"/%s\\
|%s|
|%s|"%[e=?=*k=2+l=s.map(&:size).max,h.center(k),e]
d.map{|x|puts"| %%-%ds |"%l%x}
$><<?\\+?-*k+?/

Double format string in the second-to-last line :D


CJam (15 + 4 = 19 bytes)

Mq~{1$0+<))+}%`

Online demo

To reverse,

q~:,


Python 2, 249 248 244 239 237 bytes

D={}
m=X=Y=0
for s in input().split(","):d=ord(s[0])%10%7;exec"a,b=X,Y;E=D[Y]=D.get(Y,{});E[X]='<^>v'[d];m=min(m,X);%c+=d-2|1;"%(88+d%2)*int(s[1:])
D[b][a]="X"
for Y in sorted(D):print"".join(D[Y].get(n," ")for n in range(m,max(D[Y])+1))

Input like "E2,N4,E5,S2,W1,S3".

NSEW is mapped to [1, 3, 2, 0] by d=ord(c)%10%7. Whether to change y or x is then decided by d%2, and whether to increment or decrement is decided by d-2|1. The first and third expressions were found by brute force.

Other than that, it's a simple usage of a nested dictionary of the form {y: {x: char}}.

(Thanks to @joriki for help with mapping)


CJam (60 bytes)

1-4{"(- +sqrt( * -4*
))/2"S/@a*N/\a*}:F~'-\+WF'-\+W-4FWFF'/2

Online demo

Output (with added newlines to avoid wrapping):

(--(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/2-4*-1)
)/2+sqrt(-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/
2-4*-1))/2*-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4)
)/2-4*-1))/2-4*(-(--1+sqrt(-1*-1-4*-4))/2+sqrt((--1+sqrt(-1*-1-4*-4))/2*(--1+sqrt(-1
*-1-4*-4))/2-4*-1))/2))/2/2

I suspect this is the kind of answer OP was secretly hoping for. Rather than apply general-purpose compression to a string, it uses the field structure which Gauss first exploited to present this value in surds, in his Disquisitiones Arithmeticae.

I worked from this presentation (pages 18 and 19) but adapted it slightly in order to only ever require the positive root of a quadratic. Unrolled and in pseudo-code, the expression breaks down as

# Positive root of x^2 + bx + c = 0
F(b, c) = (-b + sqrt(b*b - 4*c))/2
# (8,1)
p = F(1, -4)
# (4,1)
q = F(-p, -1)
# -(8,3)
r = F(-1, -4)
# (4,3)
s = F(r, -1)
# Result
F(-q, s)/2


CJam, 13 bytes

{ffff*::.+:~}

This is an unnamed block that expects two matrices on top of the stack and leaves their Kronecker product in their place.

Test suite.

Explanation

This is just the Kronecker product part from the previous answer, therefore I'm here just reproducing the relevant parts of the previous explanation:

Here is a quick overview of CJam's infix operators for list manipulation:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.
: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.
. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

ffff*  e# This is the important step for the Kronecker product (but
       e# not the whole story). It's an operator which takes two matrices
       e# and replaces each cell of the first matrix with the second matrix
       e# multiplied by that cell (so yeah, we'll end up with a 4D list of
       e# matrices nested inside a matrix).
       e# Now the ffff* is essentially a 4D version of the standard ff* idiom
       e# for outer products. For an explanation of ff*, see the answer to
       e# to the Kronecker sum challenge.
       e# The first ff maps over the cells of the first matrix, passing in the
       e# second matrix as an additional argument. The second ff then maps over
       e# the second matrix, passing in the cell from the outer map. We
       e# multiply them with *.
       e# Just to recap, we've essentially got the Kronecker product on the
       e# stack now, but it's still a 4D list not a 2D list.
       e# The four dimensions are:
       e#   1. Columns of the outer matrix.
       e#   2. Rows of the outer matrix.
       e#   3. Columns of the submatrices.
       e#   4. Rows of the submatrices.
       e# We need to unravel that into a plain 2D matrix.
::.+   e# This joins the rows of submatrices across columns of the outer matrix.
       e# It might be easiest to read this from the right:
       e#   +    Takes two rows and concatenates them.
       e#   .+   Takes two matrices and concatenates corresponding rows.
       e#   :.+  Takes a list of matrices and folds .+ over them, thereby
       e#        concatenating the corresponding rows of all matrices.
       e#   ::.+ Maps this fold operation over the rows of the outer matrix.
       e# We're almost done now, we just need to flatten the outer-most level
       e# in order to get rid of the distinction of rows of the outer matrix.
:~     e# We do this by mapping ~ over those rows, which simply unwraps them.


APL (Dyalog Unicode), 46 44 bytes

'/(80-)63+92145*7'[16|43|25⊥¨(×⊆⊢)2⊥' .\'⍳⎕]

Try it online!

⎕ evaluated input, must be a character matrix

' .\'⍳ replace spaces with 0, .s with 1, \s with 2, and everything else with 3

2⊥ base-2 decode the columns

(×⊆⊢) split on zeroes

25⊥¨ base-25 decode each group

16|43| mod 43, mod 16

'/(80-)63+92145*7'[ ] use as indices in the given string


Day of the week for a given date of this year. Do not use any date tools

C++   (142) (135)    (129 chars)

main(){string s[]={"Mon","Tue","Wen","Thu","Fri","Sat","Sun"};int d,m,t[]={0,5,1,1,4,6,2,4,0,3,5,1,3};cin>>d>>m;cout<<s[(d+t[m]+15-(m<3))%7];}

The requirement that the letters Mon, Tue etc. appear made it quite bad, otherwise it would be only 84 chars. I'll search a golf for the strings...

Hm, trying to golf the string only made it 2 chars longer, but I find it more aesthetically pleasing.

main(){char s[]={"MonTueWenThuFriSatSun"};int d,m,t[]={0,5,1,1,4,6,2,4,0,3,5,1,3};cin>>d>>m;d=((d+t[m]+15-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);}

Well, this for my first entry at a golf contest, I have still much to learn...

HA! Got it!

main(){char s[]={"MonTueWenThuFriSatSun"},t[]={"0511462403513"};int d,m;cin>>d>>m;d=((d+t[m]-33-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);}

with a well set compiler and some luck we might chop another 3 characters, by using char* instead of char[], but it will crash on most systems. Anyway, it doesn't matter, as I believe soon someone will post a solution in J or K with less than 10 characters, as usual :P

I'll never give up!

main(){char s[]={"MonTueWenThuFriSatSun0511462403513"};int d,m;cin>>d>>m;d=((d+s[m+21]-33-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);}


How do I convert a word document to a pdf?

Ok this is a little tricky but not too bad because pdf uses the same graphics model as postscript which means that once you have postscript it is quite trivial to convert it to pdf and postscript is way to drive printers all you have to do is print to get postscript.

Now you could write a program to convert postscript to pdf, but we don't have to there is ghostscript, which was written for unix and works just fine on linux (no major differences for this project). Unfortunately word only runs on windows, so you need two computers, and to convince windows that the linux computer is a printer you need a serial cable and a null modem. If your computer(s) don't have serial ports usb to rs232 converters work just fine (I recommend ones with a fttdi chipset). Now hook up the two computers with the serial cable and the null modem and verify that you can communicate (make sure that your parameters match).

Ok now that you have them talking it is time to convince your windows box that the linux box is a printer: just install the printer driver for the applewriter II and say it is connected to the serial port. Now when you print you send postscript to the linux box. the next step is to save it as a file.

Now scoot over to your linux box and use this simple command:

dd -if=/dev/ttyS0 -of=- -bs=1 | ps2pdf - - | sed -e '' >tmpfile && mv tmpfile file.pdf

and as simple as that you are done.

This can actually be made to work (if you send a signal to dd when you are finished) but there are easier ways like printing to a file and running gostscript on your windows box, and although fttdi makes good quality usb to serial converters it is a royal pain to install the drivers.


Tips for golfing in x86/x64 machine code

mov-immediate is expensive for constants

This might be obvious, but I'll still put it here. In general it pays off to think about the bit-level representation of a number when you need to initialize a value.

Initializing eax with 0:

b8 00 00 00 00          mov    $0x0,%eax

should be shortened (for performance as well as code-size) to

31 c0                   xor    %eax,%eax

Initializing eax with -1:

b8 ff ff ff ff          mov    $-1,%eax

can be shortened to

31 c0                   xor    %eax,%eax
48                      dec    %eax

or

83 c8 ff                or     $-1,%eax

Or more generally, any 8-bit sign-extended value can be created in 3 bytes with push -12 (2 bytes) / pop %eax (1 byte).  This even works for 64-bit registers with no extra REX prefix; push/pop default operand-size = 64.

6a f3                   pushq  $0xfffffffffffffff3
5d                      pop    %rbp

Or given a known constant in a register, you can create another nearby constant using lea 123(%eax), %ecx (3 bytes).  This is handy if you need a zeroed register and a constant; xor-zero (2 bytes) + lea-disp8 (3 bytes).

31 c0                   xor    %eax,%eax
8d 48 0c                lea    0xc(%eax),%ecx

See also Set all bits in CPU register to 1 efficiently


Retina, 80 74 73 71 74 64 65 62 78 72 bytes

 *([.,;!? ])(\1| )*
$1
T`l`L`[.!?].|^.
([.,;!?])(\w|')
$1 $2
[^.!?]$
$&.

Try it online!

This is my first Retina answer.

-12 bytes thanks to @BusinessCat!

-3 bytes thanks to @Neil.


Homework time! Find me the lowest even digit in a string

Golfscript, 26 (28) characters

'#{gets}'.'246'&8+$1<.@\?

Example:

;'583746'
.'246'&8+$1<.@\?
#44

;'53771'
.'246'&8+$1<.@\?
#8-1

live test: http://golfscript.apphb.com/?c=Oyc1Mzc3MScKLicyNDYnJjgrJDE8LjA9QD8%3D

Explanation:

'#{gets}' is an escape to ruby to satisfy the I/O requirements; STDIN is assumed to be empty
. clones the input
'246'&8+ finds which even digits are present in the input, except 8 is always retained
$1< sorts the list, then takes the first digit, but keeps it as a string
.@\? orders the stack {digit, input, digit}, then finds the digit in the input; thanks @peterTaylor for noticing me of the [array, array] signature of ?.

I've been very bold with the spec interpretation this time; namely:

The spec does not mandate in which order the integers are output; Use the other @peter's suggestion :x?x to fix (I don't like temporary variables.
The spec does not require any delimiter between the two integers; since the digit found is always a single digit, this does not matter much. If it does, append n@ (which also performs the swap), n\ (which doesn't), or ]` (which formats the output as ["8" -1]).


Exponentiation of natural numbers using only primitive integer operations

Java, 84
A boring "addition in a double loop" method. One loop is to multiply, the other makes it happen more than once. Works until overflow on int types. The -10 bonus just isn't worth it in Java ;)
int p(int x,int y){int r=1,p,i=0,j;for(;i++<y;r=p)for(p=0,j=0;j++<x;)p+=r;return r;}


Python 2.x  - 368 283

Interesting challenge. Of course we need to get present rankings from the FIFA.
Brazil have the so-called "12th man" as they have home advantage therefore the weighting 12/11.

a='BRA CHI COL URU FRA NGA ALG GER MEX NED CRC GRE ARG SUI BEL USA'.split()
d=[1242*12/11,1026,1137,1147,913,640,858,1300,882,981,762,1064,1175,1149,1074,1035]
m={}
for n in[16,8,4,2]:
 j=0
 for k in range(0,n,2):
  s=a[k] if d[k]>d[k+1] else a[k+1]
  m[a[k]+' '+a[k+1]]=s
  a[j]=s
  j+=1
def f(s):
 try: print m[s]
 except: print 'no result'

Tips to shorten the above are welcome :-).

Improvements thanks to @TheRare and @MrLemon

a='BRA CHI COL URU FRA NGA ALG GER MEX NED CRC GRE ARG SUI BEL USA'.split()
d=15,6,10,11,4,0,2,14,3,5,1,8,13,12,9,7
m={}
for n in 16,8,4,2:
 j=0
 for k in range(0,n,2):s=a[k]if d[k]>d[k+1]else a[k+1];m[a[k]+' '+a[k+1]]=s;a[j]=s;j+=1
def f(s):print s in m and m[s]or'no result'

This leads to the following results:

BRA CHI: BRA
COL URU: URU
FRA NGA: FRA
ALG GER: GER
MEX NED: NED
CRC GRE: GRE
ARG SUI: ARG
BEL USA: BEL
------------
BRA URU: BRA
FRA GER: GER
NED GRE: GRE
ARG BEL: ARG
------------
BRA GER: BRA
GRE ARG: ARG
------------
BRA ARG: BRA

Example calls:

f('BRA MEX')
no result
f('BRA CHI')
BRA


Python, 899 chars

import sys,random
raw_input()
X,Y=map(int,raw_input().split())
input()
I=[' x'[v<'~']for v in sys.stdin.read()]
M={196:' ',168:'$',148:'*',388:'.',52:'0',97:'2',49:'4',112:'6',292:'8',73:'B',25:'D',88:'F',268:'H',28:'J',67:'L',19:'N',82:'P',262:'R',22:'T',193:'V',145:'X',208:\
'Z',42:'%',138:'+',133:'-',162:'/',289:'1',352:'3',304:'5',37:'7',100:'9',265:'A',328:'C',280:'E',13:'G',76:'I',259:'K',322:'M',274:'O',7:'Q',70:'S',385:'U',448:'W'\
,400:'Y'}
N=500
for w in' '*30000:
 a,b,c,d=eval('random.random(),'*4);A=''.join(I[int((a+(c-a)*i/N)*X)+X*int((b+(d-b)*i/N)*Y)]for i in range(N)).lstrip();T=A.count(' x')+1;K=A.count('x')/T;L=A.count\
(' ')/T;s='';z=c=0
 while A:
  z*=2;y=A.find(' ')
  if y<0:y=len(A)
  z+=y>K;A=A[y:]
  z*=2;y=A.find('x')
  if y<0:y=len(A)
  z+=y>L;A=A[y:];c+=2
  if c>9:
   if z/2in M:s+=M[z/2];z=c=0
   else:break
 if s and'*'==s[0]and'*'==s[-1]and'*'!=s:print s[1:-1];break

This code takes a pnm format image as input, so I normally run it like:

pngtopnm s01.png | ./barcode.py

The code itself just picks lots of random scanlines and tries to match the black and white runs on that scanline to the code39 patterns.  It is randomized so it can fail to find barcodes on occasion.  (I get about a 20% false negative failure rate on the test images.)  When it fails it takes about a minute to run, when it succeeds it often does so much quicker than that.  I've never seen a false positive.


Python 2, 18 16 bytes

+beauty thanks to @Sarge Borsch

`99066**2`.strip

Try it online!

99066**2 is just a shorter way to generate a string that contains 0~9