RLE Brainfuck dialect RLE Brainfuck

(related to BF-RLE)

The hypothetical RLE (Run-Length Encoding) dialect of Brainfuck accepts the symbols for the 8 commands and also accepts digits. The digits are used to represent the number of successive repetitions of a command, thus allowing run-length encoding of the source code.

8> is equal to >>>>>>>>.

The length is always on the left side of the command.

Your task is to write the shortest program/function that translates the input string (RLE Brainfuck fragment) into a regular Brainfuck program.

For example:

Input:

10+[>+>3+>7+>10+4<-]3>2+.>+.7+2.3+.2<2+.>15+.>.3+.6-.8-.2<+.<.

Ouptut:

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

The shortest code in byte count in each language will win.

Python 2, 62 61 bytes

lambda s:eval(re.sub('(\d*)(.)',r'+1*\1*1*"\2"',s))
import re

Try it online!

The regex substitution expands 3<2+- into the string:

+1*3*1*"<"+1*2*1*"+"+1**1*"-"

which is then evaled. (Note how when \1 is empty, we get 1**1 = 1.) The first + is a unary operator which binds to the first number, and the other +s are string concatenation. This beats the more obvious

lambda s:re.sub('(\d+)(.)',lambda m:int(m.group(1))*m.group(2),s)
import re

by 14 bytes. Ordinarily "\2" wouldn’t always work, but thankfully \ and " aren’t brainfuck commands.

xnor saved a byte, supplying the 1*\1*1 trick. Previously I had \1L in the regex, and defined L=1 as a lambda argument, which is also pretty cool: 3L is a long int literal and L is a variable.


Circular Keyboard Spiral This is a QWERTY keyboard.

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

We can "spiral out" on this keyboard, starting from G. The spiral will start at G, go to H, then to Y, then to T, then F, then V, then B, then N, then J, then U, then R, then D, then C,... etc. Your challenge is to, given a number 1 ≤ N ≤ 26, output the first N characters in this spiral. (If you are confused, refer to the pictures at the end of the post.)

The catch? Your program's score is proportional to the indices of characters found inside the spiral!

Scoring

For every letter (case-insensitive) in your code, add the index of that character in the spiral to your score (starting from 1).
For every character not in the spiral, add 10 to your score.
The lowest score wins.

For example, the program print("Hello, World!") has a score of 300.

For your convenience, I have written an automatic program grader.

var SPIRAL = "GHYTFVBNJURDCMKIESXLOWAZPQ";
function grade(program) {
    var score = 0;
    for(var i = 0; i < program.length; i++) {
        if(/^[A-Za-z]$/.test(program[i])) {
            score += SPIRAL.indexOf(program[i].toUpperCase()) + 1;
        }
        else {
            score += 10;
        }
    }
    return score;
}

input.oninput = function() {
    output.value = "Your program's score is: " + grade(input.value);
}
textarea { width: 500px; height: 6em; font-style: monospace; }
<textarea id="input"></textarea>
<textarea disabled id="output"></textarea>

Other rules

Your submission may be a program or function.
You may take N starting at 0 or 1 and ending at 25 or 26, respectively, but the outputs should still begin with "G" and end with "GHYTFVBNJURDCMKIESXLOWAZPQ".
You must output the characters in the spiral in order.
If a function, you may return a list of characters instead of a string.
You may have one trailing newline following the output.
You may use lowercase letters instead of uppercase letters, or a combination of both.

Test cases

number -> output
1 -> G
2 -> GH
5 -> GHYTF
12 -> GHYTFVBNJURD
15 -> GHYTFVBNJURDCMK
24 -> GHYTFVBNJURDCMKIESXLOWAZ
26 -> GHYTFVBNJURDCMKIESXLOWAZPQ

Pictures

The spiral superimposed:

Japt, 304 264 162 points

Saved 40 points thanks to @ConorO'Brien

;î"历锋㫿鮹㿬崴ꨜꎋΞ"csG

Test it online!

In order to save as many points as possible, the entire string is condensed into 9 Unicode chars by interpreting each run of 3 letters as a base-36 number, then converting to a code point. The program itself takes this compressed string (which costs 110 points, including the quotes) and maps each charcode by converting it to a string in base-36 (G after the ; at the beginning). î takes the first {input} chars of this, which is implicitly printed.


Write the implementation to pass this test Given the following test, implement an addOne function in C# so it passes, without any modification to the test. TIP: Yes, it is possible.

[TestMethod]
public void TheChallenge()
{
    int a = 1;

    addOne(a);

    Assert.IsTrue(a == 2);
}

EDIT: clarified the Assert to avoid confusion. The value of a should be 2; there's no trick there.

Ummm, simply provide an implementation of AssertTrue that doesn't throw anything?

void addOne(int a){}

void AssertTrue(bool b) { }

You never specified what testing framework is used here. It looks like MSTest, but I fired up a new test project and AssertTrue doesn't exist, so I took the liberty of implementing it myself.

EDIT

This solution might be what you were fishing for:

void addOne(int x)
{
  unsafe
  {
    int* i = &x;
    i += 4;
    *i += 1;
  }
}

I feels pretty fragile, but it works on my box consistently. It probably depends heavily on the compiler, so hopefully it is reproducible elsewhere.


Verify the inequality! Left in sandbox for at least 3 days.
I want to verify if this inequality is true:
for \$n\geq4\$, if \$a_1,a_2,a_3,\dots,a_n\in R_+\cup\{0\}\$ and \$\sum_{i=1}^na_i=1\$, then \$a_1a_2+a_2a_3+a_3a_4+\dots+a_{n-1}a_n+a_na_1\leq\frac{1}{4}\$.
Challenge
Write a piece of program which takes an integer n as input. It does the following:

Generate a random array a which consists of n non-negative reals. The sum of all elements should be 1.

By saying random, I mean, every array satisfiying the requirements in 2 should have a non-zero probability of occurrence. It don't need to be uniform. See this related post.

Calculate a[0]a[1]+a[1]a[2]+a[2]a[3]+...+a[n-2]a[n-1]+a[n-1]a[0].

Output the sum and the array a.

For I/O forms see this post.

Rules
(Sorry for the late edit...) All numbers should be rounded to at least \$10^{-4}\$.
Standard loopholes should be forbidden.
Example
The following code is an ungolfed Python code for this challenge, using library numpy. (For discussion about using libraries, see This Link.)
import numpy as np

def inequality(n):
    if n < 4:
       raise Exception
    a = np.random.rand(n)
    sum_a = 0
    for i in range(n):
        sum_a += a[i]
    for i in range(n):
        a[i] /= sum_a
    sum_prod = 0
    for i in range(n):
       sum_prod += a[i % n] * a[(i + 1) % n]
    print(a)
    return sum_prod, a

Tip
You could assume that input n is a positive integer greater than 3.

Your score is the bytes in your code. The one with the least score wins.

APL(Dyalog Unicode), 21 bytes SBCS
(+/⊢×1∘⌽)⎕←(⊢÷+/)?⎕⍴0

Try it on APLgolf!
A tradfn submission which prints the list and returns the sum.
                  ⎕⍴0 ⍝ create a vector with input-many 0's
                 ?    ⍝ for each 0, get a random number between 0 and 1
            ⊢÷        ⍝ divide each number by
              +/      ⍝ the sum of all numbers
         ⎕←           ⍝ print the resulting vector
   ⊢×                 ⍝ multiply the vector element-wise
     1∘⌽              ⍝ with the vector rotated to the left by 1
 +/                   ⍝ take the sum of all products

If appending the sum to the list is fine as output, this could be 20 bytes: x,+/x×1⌽x←(⊢÷+/)?⎕⍴0


Solve Subset-Sum in polynomial time (...if P = NP) Shocking news: Dr. Mad J Scientist has released a proof of P = NP to the world. But the proof is nonconstructive, and she's keeping the algorithm to herself.

Worry not. Without even looking at her proof, we can still (almost) write a computer program that solves NP-complete problems in polynomial time.

The Problem

Input a list of integers, such as [-10, -4, 1, 1, 2, 6, 8]. Output a nonempty sublist that sums to 0, such as [-10, 1, 1, 2, 6]. The output list can be in any order. Ignore any integer overflow issues in your language.

If P = NP, your program must provably run in polynomial time on solvable inputs. Your program may act arbitrarily on inputs with no solution. This is code-golf; shortest code wins.

Yes, this challenge is possible. One approach is as follows:

  Enumerate all possible computer programs \$P_0, P_1, P_2, \dots\$
  Repeat as \$i\$ goes from 0 to \$\infty\$:
  ----- Run the first \$i\$ programs on the input list, for \$i\$ steps each.
  ----- For each output you get, check whether it's a valid subset sum solution. If so, return it.

This works because, if P = NP, then some program \$P_m\$ solves subset-sum in some polynomial time \$O(n^k)\$. Therefore, the above algorithm will output a solution on the \$\max(m, O(n^k))\$th iteration of the loop, if not before. Therefore, the above algorithm runs in polynomial time on solvable inputs.

Note: A proof that P ≠ NP would allow a 0-byte solution to this problem. Good luck with that :)

Notes

Before you start evaling all strings in a language like Python, let me point out that some of those strings will reformat your hard drive.

This challenge does not run afoul of the no famous open questions rule, because although it is related to P vs NP, this challenge is solvable.

Python 3.8 (on Unix), 429 bytes

Since nobody else has posted an answer yet, I thought I'd have a go, though I not 100% certain I haven't missed something important (and I am 100% certain the code could be shrunk down significantly).

As noted in the question, evaluating arbitrary Python strings is dangerous. Fortunately, it's easy to come up with a safe subset of strings whose evaluation is still Turing complete, by embedding the Turing complete While Programming Language, summarised below:

This can be embedded into Python using only strings that match the following regex:

^([0-9 \n():_=+-]|while)+$

To reduce the number of necessary characters, we use a few embedding hacks:

variable names are built only of underscores
if B then C1 else C2 is emulated using while loops (and temporary variables x and y, which hang around afterwards but that's ok):

x=B;y=not x
while x:C1;x=False
while y:C2;y=False

skip is emulated using any constant expression, e.g. 0
true is emulated using e.g. 0==0
false is emulated using e.g. 0==1
B & C is emulated using a pre-evaluated if-then-else (and another temporary variable x):

if B then x=C else x=False

¬ B is emulated using 1-B

To make our life easier, we also allow [ and ], as this permits direct operations on lists (including slicing and concatenation) which avoids having to translate the problem from one on lists into one on integers.

Update: as noted by @ØrjanJohansen, it's also necessary to include < to ensure basic arithmetic remains polynomial.

I claim that any program with just those characters will either execute, or (far more likely) fail to execute, or raise an exception, but will not crash the interpreter or change any global state. Please correct me if I'm wrong.

The rest of the solution is now similar to the prototype presented in the question. We generate all strings of increasing lengths n and execute them, prepopulating the input in variable _ and checking and validating any output from the same variable. We catch any raised exceptions and continue.

The main tricky bit is ensuring polynomial complexity (and termination). We do this by breaking out of each execution after n seconds, using Unix signals and a handler that raises an exception (which the string executions themselves have no way of catching). Since every program will appear repeatedly (eg with trailing whitespace), we don't need to worry about breaking out too soon from a correct program. One tricky bit here is to make sure that the program doesn't crash if the signal is received after the execution completed (successfully or not) but before the signal has been reset; this explains the nested try-catch.

from itertools import*
from re import*
from signal import*
I=eval(input())
signal(SIGALRM,0)
for n in count():
 for p in product(*[set(map(chr,range(128)))]*n):
  if match("([0-9 \n()[\]:_=<+-]|while)+$",(s:="".join(p))):
   try:
    try:
     g={'_':I[::]};alarm(n);exec(s,g);h=g['_']
     if h and all(h.count(x)<=I.count(x)for x in h)and sum(h)==0:
      print(h);n=-1;break
    except:0
    alarm(0)
   except:0
 if n<0:break

Try it online! (though don't expect an actual result; it may be P but it's obscenely slow)


The centers of a triangle Circles and squares have a single, definite center point. However, the notion of the center of a triangle has long been discussed. Four different centers were known to the Ancient Greeks:

Incenter: The intersection of the angle bisectors of the triangle
Centroid: The intersection of the lines from each vertex of the triangle to the middle of its opposite side
Circumcenter: The intersection of the perpendicular bisectors of the sides
Orthocenter: The intersection of the altitudes of the triangle

Euler later proved that the centroid, circumcenter and orthocenter are collinear in any triangle. The line that these three points are on in a triangle is called the Euler Line. It is defined for every triangle except an equilateral triangle, where all the points coincide.

Your challenge is to create the shortest program or function that, when given two inputs, outputs a specific center or the Euler Line of the triangle. The first specifies the coordinates of each vertex of a triangle. The second is an integer from 1 to 5, determining what to output.

1 - Incenter
2 - Centroid
3 - Circumcenter
4 - Orthocenter
5 - Equation of Euler Line
    (if the Euler Line is vertical, output the `x` value of the line
      (e.g. output `5` if the equation of the line is `x = 5`))

You may assume that the given vertices will never be collinear, and that they will always be integer coordinates (this also excludes the possibility of having an equilateral triangle as an input, as per @R.Kap's comment).

The input array should be a valid nested array in your language, and input should be in any reasonable format. Any float values should be displayed to at least 3 decimal places, but no less. An outputted point should be a valid array in your language, matching with the input format.

Test cases:

Input: [(-2, 0), (1, 0), (0, 1)] 1
Output: (-0.089, 0.451)

Input: [(-2, 0), (1, 0), (0, 1)] 2
Output: (-0.333, 0.333)

Input: [(-2, 0), (1, 0), (0, 1)] 3
Output: (-0.5, -0.5)

Input: [(-2, 0), (1, 0), (0, 1)] 4
Output: (0, 2)

Input: [(-2, 0), (1, 0), (0, 1)] 5
Output: 5x + 2

Clarification: The input can either be from stdin, either space or new-line separated, or as the arguments to a function. The output, however, must be written to stdout.


Who Took My Toilet Paper? You step into the restroom, and notice that the toilet paper has missing! It occurs to you that someone had stolen it. Strangely enough, the first thing you would like to know is the amount of toilet paper the thief stole.

Task

You are given three integers \$ I \$, \$ R \$, and \$ G \$, the details of the toilet paper, where \$ I \$ is the radius of the inner ring, \$ R \$ is the number of rotations, and \$ G \$ is the thickness. The task is to return/output out the length of the toilet paper.

The toilet paper can be viewed as an Archimedes' spiral, which starts at coordinate \$ (I, 0) \$, and rotates a total of \$ R \$ times in the counterclockwise direction, with a distance of \$ G \$ between each gap.

More formally, the Archimedes' spiral here is defined as the set of all points whose locations over time move away from the origin counterclockwise at a constant speed and with constant angular velocity.

Due to potential precision issues, your answer will be judged correct if they pass all the sample cases below when rounded to \$ 1 \$ decimal place.

In the diagram below, \$ I = 5 \$, \$ R = 3 \$, \$ G = 4 \$, and the total length is \$ \approx 207.7 \$.

Test Cases

I R G -> answer rounded to 1 decimal place (note that the answer does not have to be rounded)
0 1 1 -> 3.4
5 3 4 -> 207.7
12 9 2 -> 1187.7

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

J, 66 bytes

1#.2|@-/\1e3&((-:@[%:_1:)^[:i.1+[*0{])((*{:)+[*(1{])*1e3%~i.@#@[)]

Try it online!

This could be golfed more, but I'm putting it away for now.

Instead of taking an analytic approach I am using complex number arithmetic to break the spiral down into 1000 straight line segments per rotation, and then summing those segments.

I find the 500th root of -1, and keep multiplying it by itself to rotate it and get an approximation to the next spiral point.

Because the spiral also moves outward, we need to take the new vector, normalize it, multiply the normal vector by 1/1000 of the thickness, and then add that little correction to the new vector.

Conceptually, we're doing something similar to approximating a circle's circumference with the short sides of many triangles.

The idea is simple, but the golf part of it boils down to boring bookkeeping and argument parsing which isn't worth going into.  In theory the realization of this method could be a lot shorter.


Make a haystack (with a needle) (Essentially the inverse of Find the needle in the haystack)

Given two tuples, (w, h) and (x, y), generate a haystack composed of a single random printable ASCII character of w width and h height with a needle made of a different random printable ASCII character at (x, y) when measured from the upper-left.

For example, when given (5,4) for the width and height, and (3,1) (zero-indexed) for the location of the needle, a possible haystack could be the following:

#####
###N#
#####
#####

Another possibility could be

*****
***$*
*****
*****

among hundreds of others.

Rules and Clarifications

Input and output can be given by any convenient method. This means you can take input as a list of list of integers, as a single string, as two integers via command-line and a tuple via function argument, etc.
You can print the result to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
You can choose whether the (x, y) tuple is zero-indexed or one-indexed, but please specify in your solution which you're using.
You do not get to pick which characters to use. That's part of the challenge - randomly selecting the characters.
Every possible output for a given input must have a non-zero chance of appearing, but the randomness doesn't need to be uniform.
The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay.
There is only ever one needle, and it's only ever one character in size, and it's guaranteed to be within the boundaries of the haystack.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

JavaScript (Node.js),  122 120 106  103 bytes
Recursively builds the output character by character. The coordinates are 0-indexed.

(w,h,x,y)=>(s=new Date%9023,g=X=>Y<h?Buffer([X-w?(x-X|y-Y?s+1:s%96)%95+32:13])+g(X<w?X+1:!++Y):'')(Y=0)

Try it online!
How?
Problem
To generate the haystack and the needle, we could either:

generate a random haystack and process some loop to generate a random needle until it's different from the haystack
shuffle the whole range of printable characters and pick the first 2 of them

Unfortunately, both approaches are rather lengthy in JS.
Solution
We use instead a method that guarantees to generate 2 distinct characters with a single random number and without any loop.
We pick a random seed \$s\$ in \$[0..9022]\$ and define the haystack \$h\$ and needle \$n\$ as:
$$\begin{align}&h=(s+1)\bmod 95\\
&n=(s\bmod 96)\bmod 95\end{align}$$
(we then need to add \$32\$ to turn them into printable ASCII codes)
Basically, \$h\$ follows the pattern:
$$1,2,3,...,94,0,1,2,3,...$$
while \$n\$ follows the pattern:
$$0,1,2,3,...,94,\color{red}0,0,1,2,3,...$$
The sequences are progressively shifted relative to each other because of the extra \$0\$ in the needle pattern.
This code shows that it does eventually lead to all possible pairs \$(h,n)\$ with \$h\neq n\$ (there are \$95\times 94=8930\$ of them).
And because we need only one random number, we can afford to use the current timestamp in milliseconds as our entropy source with new Date%9023 instead of the longer Math.random()*9023.
Commented
(w, h, x, y) => (      // w = width, h = height, (x, y) = coordinates
  s = new Date % 9023, // s = random seed in [0..9022]
  g = X =>             // g = recursive function taking X
    Y < h ?            //   if we've not reached the end of the grid:
      Buffer([         //     append the next character:
        X - w ?        //       if we haven't reached the end of the line:
          ( x - X |    //         if this is not the position of the needle:
            y - Y ?    //
              s + 1    //           append the haystack character
            :          //         else:
              s % 96   //           append the needle character
          ) % 95 + 32  //
        :              //       else:
          13           //         append a linefeed
      ]) +             //
      g(X < w ? X + 1  //     append the result of a recursive call
              : !++Y)  //     with either (X+1, Y) or (0, Y+1)
    :                  //   else:
      ''               //     stop recursion
)(Y = 0)               // initial call to g with X = Y = 0


Finding limits of functions A limit in math determines the value that a function f(x) approaches as x gets closer and closer to a certain value.

Let me use the equation f(x)=x^2/x as an example.
Obviously, f(x) is undefined if x is 0 (x=0, x2=0, 0/0 is undefined).
But, what happens when we calculate f(x) as x approaches 0?

x=0.1, f(x)=0.01/0.1 = 0.1
x=0.01, f(x)=0.0001/0.01 = 0.01
x=0.00001, f(x)=0.0000000001/0.00001 = 0.00001
We can easily see that f(x) is approaching 0 as x approaches 0.

What about when f(x)=1/x^2, and we approach 0?

x=0.1, f(x)=1/0.01=100
x=0.01, f(x)=1/0.0001=10000
x=0.00001, f(x)=1/0.0000000001=10000000000
As x approaches 0, f(x) approaches positive infinity.

You will be given two things in whatever input format you like:

f(x) as an eval-able string in your language
a as a floating point

Output the value that f(x) approaches when x approaches a. Do not use any built-in functions that explicitly do this.

Input Limitations:

The limit of f(x) as x approaches a will always exist.
There will be real-number values just before and just after f(a): you will never get f(x)=sqrt(x), a=-1 or anything of the sort as input.

Output Specifications:

If f(x) approaches positive or negative infinity, output +INF or -INF, respectively.
If f(a) is a real number, then output f(a).

Test Cases:

f(x)=sin(x)/x, a=0; Output: 1
f(x)=1/x^2, a=0; Output: +INF
f(x)=(x^2-x)/(x-1), a=1; Output: 1
f(x)=2^x, a=3; Output: 8

Shortest code wins. Good luck!

C, 402 bytes

Plenty of room for golfing, just proof of concept to begin with :P

Compiles under clang, osx.

Note: For linux you may have to change the code to use something like: "ld -shared f.o -o f.so -lm"

#include<dlfcn.h>
#include<stdio.h>
float e,r;
main(int i,char**v){
    // create and compile temporary c file for 'f(x)'
    // note: include offset within function
    FILE*s=fopen("f.c","w");
    fprintf(s,"#include<math.h>\nfloat f(float x){x+=%s;return %s;}",v[2],v[1]);
    fclose(s);
    system("cc -fPIC -c f.c;ld -bundle f.o -o f.so -lm");
    float(*f)(float)=dlsym(dlopen("f.so",0),"f");

    for(i=0;1;e=(e==0)?1e-37:e*2){
        r=f(e);
        if(isinf(r))i=1;else if(!isnan(r)){
            i?printf("%cINF\n",r>0?43:45):printf("%f\n",r);
            break;
        }
    }
}

Run as:

./a.out "sin(x)/x" 0
./a.out "1/(x*x)" 0
./a.out "(x*x-x)/(x-1)" 1
./a.out "pow(2,x)" 3

Results:

1.000000
+INF
1.000000
8.000000


The Tenacious Thai Calendar In the Thai calendar the year 2017 corresponds to 2560. The Thai calendar is always 543 years ahead of the Gregorian calendar.
Observant coders will note that 2560 is equal to \$2^9 \times 5\$, in other words it has 10 prime factors. This will not happen again for another 896 years! We call a year tenacious if it has exactly ten prime factors.
Write a program which outputs a truthy value if the current year using the Thai calendar, based on the system clock, is tenacious, and a falsey value otherwise.
Test cases:

If the program is run during 2017, true
If the program is run during any of the years 2018 to 2912, false
If the program is run during 2913, true (\$2913+543 = 2^7 \times 3^3\$)

Bash + coreutils, 35 bytes

factor $[`date +%Y`+543]|awk NF==11

Output is either a non-empty string (truthy) or an empty string (falsy).
Try it online!
Alternate version: 37 bytes.
date -d 543year +%Y|factor|awk NF==11

Not as golfy, but I like this one.
Try it online!
How it works
The arithmetic expansion
$[`date +%Y`+543]
executes date +%Y to get the current (full) year and adds 543 to the year.
Factor takes the sum as an argument and prints it prime factorization: first the number to be factored, then a list of individual prime factors.
Finally, awk filters the input, printing only lines with exactly 11 fields (the number plus 10 prime factors).


Hide evil code - print files containing a given string anywhere in a directory tree The point of this puzzle is to learn how a malicious code can be hidden and discovered in a program.

A person is asking the question:

  Plz give me some code that how can I search a file may be in Present
  Directory or in its Sub-Directories.

(This is a variant of a real question I've seen posted on one site.)

To be more specific: The OP wants you to write a program that accepts a string and a directory. It will traverse all files in the directory and recursively all its subdirectories. For each file it will check if the file contains the string, and if it does, will print the name of the file. (The program can have additional features as long as they are relevant to the main goal, if you wish.) There are no requirements on the traversal order.

However, the main task of this puzzle is to hide into the program additional code that will make a fool of the person that asks for the program in the eyes of its users/colleagues/boss/etc. For example, print a humiliating text at some point, such as: The author of the program doesn't know how to program, should return his/her diploma and get fired. Be creative.

Rules:

The solution must not be harmful (except making fool of the OP, of course). It must not do any irreversible damage to end users (no stuff like rm -rf)! Such solutions will be disqualified.
The trolling stuff should be hidden so that the OP won't find it easily.
It shouldn't be obvious that you're trolling the OP. The code should look genuine.
The solution must come with a proper explanation how it trolls the OP so that everybody can learn something from your solution. The explanation should be hidden in a hidden-until-you-click text (spoilers). When judging, try to discover the trolling without looking at the explanation and vote for those that are difficult to discover.
Also try to hide the trolling from the OP if (s)he tries to run the code a few times. Perhaps start trolling only after a particular date, or under some conditions that a sloppy programmer won't test. Be creative and don't forget to explain the trick.
Don't just create a script using existing tools such as grep or find. Write the program from scratch. Better avoid libraries and prefer low-level calls - this will make the code more complex and gives you the opportunity to hide the evil stuff there.

This is a popularity-contest. Please judge according the above points.

Here is my solution (in Perl):

#! /usr/bin/perl -w

use Cwd 'abs_path';

# Check the command line arguments
my $F = abs_path($0);
if ($#ARGV!=1) {
    print "Usage: ".$F." <dir> <expr>\n";
    exit(1);
}

# The first argument is the directory
my @u = (abs_path($ARGV[0]));
# Check for trailing slash
my $c = substr $u[0], -1, 0;

# Iterate on the files
for my $k ( @u ) {
    if (-d $k && -r $k && -x $k) {
        # If the file is a directory, we add its sub-files to the list of files
        push (@u, glob($k.($c eq "/" ? "*" : "/*")));
    } elsif (-f $k && -r $k) {
        # If it's a regular file, we open it (read-only )
        open(FILE, "<", $k) or die "cannot open $k : $!";
        # Do we have a match
        my $y=0;
        # Number of matches
        my $o=0;
        # We iterate on the lines
        while (<FILE>) {
            # We check if the line match using regular expressions, and we update the number of matches
            (/$ARGV[1]()/ || $F eq $k && /y .([F c-y])/) && (($c,$y,$o)=($c.$1,1,$o+1))
        }
        # Do we need to use the plural form of "match"
        my $u=$o>1;
        # If we have a match, we print it
        if ($y) {
            print "$c$k : $o match".($u?"es\n":"\n");
        }
        # Close the file (opened read-only )
        close(FILE) or die "cannot close $k : $!";
    }
}

The first argument of the program is the directory and the second argument is the string we are looking for. The program also show the number of matches in each file.

Here is how to search "VGA" in /etc:

$ ./mygrep.pl /etc VGA
/etc/alternatives/mplayer : 7 matches
/etc/alternatives/pinentry : 1 match
/etc/alternatives/pinentry-x11 : 1 match
/etc/alternatives/www-browser : 1 match
/etc/bumblebee/xorg.conf.nouveau : 2 matches
/etc/bumblebee/xorg.conf.nvidia : 2 matches
/etc/default/console-setup : 2 matches
/etc/htdig/english.0 : 1 match
/etc/X11/X : 6 matches
/etc/laptop-mode/conf.d/video-out.conf : 3 matches
$

And now, here is the trick :

   The program works exactly as advised as long as it doesn't encounter itself in the files. As soon as it encounters itself, it starts to prefix each file found with insanity.
 Let's copy some files in the current directory and try again :
 $ cp /etc/default/console-setup /etc/bumblebee/xorg.conf.nouveau /etc/bumblebee/xorg.conf.nvidia /etc/htdig/english.0 ./
$ ./mygrep.pl ./ VGA
/tmp/mygrep/console-setup : 2 matches
/tmp/mygrep/english.0 : 1 match
Fuck you /tmp/mygrep/mygrep.pl : 9 matches
Fuck you /tmp/mygrep/xorg.conf.nouveau : 2 matches
Fuck you /tmp/mygrep/xorg.conf.nvidia : 2 matches
$
 This is due to this code:
 $F eq $k && /y .([F c-y])/
 It tests if the current file is the running program, and if it is, it extract some part of the program with a regexp and affects it to $c with
 $c = $c.$1
 What is extracted by the regexp are the variable declarations (variables are named $F, @u, $c, $k, $y, $o, $u) and two spaces from the comments.
 I had to do that to keep it hidden, even if the program is relatively short.


Solving Secret Swapping Sequences This is a cops-and-robbers challenge, the cops thread can be found here.

This is the robbers thread, your job here is to take submissions on the cops thread and try to find the hidden sequences.  If you find any sequence that can be substituted into the original code to compute that sequence that is a valid crack.  Please notify the cops of your cracks as they happen so they can update their answers.

Scoring

Your score will be the number of successful cracks you have made, with more cracks being better.

Japt, Shaggy, A000290

p#A000290uCnG

Try it online!


Optimally reach a number in deadfish! Goal:
Given any natural number k such that k<256, produce an deadfish program that gives the smallest solution possible.
Background:
Deadfish is a joke esoteric programming language. It has a single unsigned byte of memory, called the accumulator, initialized at 0. There are four commands which form a string.

i = accumulator += 1
d = accumulator -= 1
s = accumulator = accumulator * accumulator
o = print(accumulator)

For example, the string iiisis would produce 100, as this would be the memory after each command:

i -> 1
i -> 2
i -> 3
s -> 9
i -> 10
s -> 100

Specification:

Read a number through any reasonable means (from a file, STDIO, or a function argument), and output an optimal string of commands producing that number.
A solution is considered optimal if there are no solutions that use fewer commands.
Output through any reasonable means (to a file, STDIO, or a return value).
The accumulator may not exceed 256.

Examples:
0 -> (Empty string, nothing, or error)
1 -> i
4 -> iis
8 -> iiisd
35 -> iisiisd
150 -> iiisiiisiiiiii
256 -> (Empty string, nothing, or error)

Mathematica, 164 bytes

a=#~Mod~256&;Switch[#2,#+1,"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1/.256->#,#-1,If[#<16,#^2,#]}]&)/@0~Range~255],0,#],2,1]&

Anonymous function. Takes a number as input and returns a list of instructions as output. Previous solution before requirements were changed:

Mathematica, 148 bytes

a=#~Mod~256&;Switch[#2,a[#+1],"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1,#-1,#^2}]&)/@0~Range~255],0,#],2,1]&

Anonymous function. Takes a number as input and returns a list of instructions as output. First, the edges for a graph of value transitions are generated. Then, FindShortestPath is used to find the shortest path from 0 to the requested value. Finally, pairs of values are taken and compared to find the instructions used. All outputs of this program can be found here.


Code Golf Image Downloader In many image-processing challenges, the post contains images, which must be saved to a file in order to be able to work on the problem. This is an especially tedious manual task. We programmers should not have to be subjected to such drudgery. Your task is to automatically download all the images contained in a Code Golf.SE question.
Rules

Your program may connect to any part of stackexchange.com, but may not connect to any other domains, excepting the locations of the images (i.e., don't bother with a URL shortener).
An integer N is given as input, on the command line or stdin.
The URL http://codegolf.stackexchange.com/questions/N is guaranteed to be a valid link to a Code Golf question.
Each image displayed in the body of question N must be saved to a file on the local computer. Either of the following locations is acceptable:

The current directory
A directory input by the user

Your program must not save files other than the images in the question body (e.g. user avatars, or images contained in answers).
Images must be saved with the same file extension as the original.

This is a code-golf — write the shortest program you can.
Validity criterion for answers
There are various possible edge cases with multiple images of the same name, text with the same name as HTML elements, etc. An answer will be invalidated only if it can be shown to fail on some revision of a question posted before January 10, 2015.

Mathematica, 211 210 bytes

i=Import;FileNameTake@#~Export~i@#&/@ImportString["body"/.("items"/.i["http://api.stackexchange.com/2.2/questions/"<>InputString[]<>"?site=codegolf&filter=!*Lgp.gEWHA6BNP.l","JSON"])[[1]],{"HTML","ImageLinks"}]

Ungolfed:

i = Import;
FileNameTake@#~Export~i@# & /@
 ImportString[
  "body" /. (
    "items" /.
      i["http://api.stackexchange.com/2.2/questions/" <>
        InputString[] <> "?site=codegolf&filter=!*Lgp.gEWHA6BNP.l",
       "JSON"]
  )[[1]],
  {"HTML", "ImageLinks"}
 ]

It's pretty straightforward. I've set up a filter for the StackExchange API, which returns only the body of a question. The code retrieves the question information with that filter and parses it as JSON. I select the correct element (the body), and use ImportString to parse the HTML and filter out all image URLs. FileNameTake@#~Export~Import@# then downloads each of the images and stores it in the current working directory with the same file name as that in the URL.

You can find out the current working directory with Directory[].

In principle, there's a much shorter version, because ImportString can actually download all the files right away, instead of just giving me the URLs. But then I lose information about the original file type (since they are converted to Image objects upon download), so I can only save them all as the same type (PNG, say).


Fastest semiprime factorization Write a program to factorize a semi-prime number in the shortest amount of time.
For testing purposes, use this:
\$38!+1\$ (\$523022617466601111760007224100074291200000001\$)
It is equal to:
\$14029308060317546154181 × 37280713718589679646221\$

Python (w/ pypy2 v7.3.1) ~0.9s
Using a Multiple Polynomial Quadratic Sieve. I took this to be a code challenge, so I opted not to use any external libraries (other than the standard log function, I suppose). When timing, the PyPy JIT should be used, as it results in timings 4-5 times faster than that of cPython.
Update (2013-07-29):
Since originally posting, I've made several minor, but significant changes which increase the overall speed by a factor of about 2.5x.
Update (2014-08-27):
As this post is still receiving attention, I've updated my_math.py correcting two errors, for anyone who may be using it:

isqrt was faulty, sometimes producing incorrect output for values very close to a perfect square. This has been corrected, and the performance increased by using a much better seed.
is_prime has been updated. My previous attempt to remove perfect square 2-sprps was half-hearted, at best. I've added a 3-sprp check - a technique used by Mathmatica - to ensure that the tested value is square-free.

Update (2014-11-24):
If at the end of the calculation no non-trivial congruencies are found, the progam now sieves additional polynomials. This was previously marked in the code as TODO.
Update (2020-08-29):
A few improvements resulting in minor performance gains, including:

Calculating the average contributation of the skipped primes, rather than roughly approximating.
Actually sieving powers of the prime factor base. The modular square root of each power can be computed efficiently through use of Hensel Lifting.
Reusing the sieve array in subsequent iterations, rather than creating a new one.

mpqs.py
import math
import my_math
import time

# Multiple Polynomial Quadratic Sieve
# assumes n is composite
def mpqs(n, verbose=False):
  if verbose:
    time1 = time.time()

  root_n = my_math.isqrt(n)
  root_2n = my_math.isqrt(n+n)

  # formula chosen by experimentation
  # seems to be close to optimal for n < 10^50
  bound = int(7.5 * math.log(n, 10)**2)

  prime = []
  mod_root = []
  log_p = []
  num_prime = 0

  # size of the sieve
  x_max = bound * 5
  x_max_2 = x_max+x_max

  # maximum value on the sieved range
  m_val = (x_max * root_2n) >> 1

  # find a number of small primes for which n is a quadratic residue
  pg = my_math.primes()
  p = pg.next()
  while p < bound or num_prime < 3:

    # legendre (n|p) is only defined for odd p
    if p > 2:
      leg = my_math.legendre(n, p)
    else:
      leg = n & 1

    if leg == 1:
      prime += [p]
      log_p += [math.log(p, 10)]
      r = int(my_math.mod_sqrt(n, p))
      roots = [r]
      q = p
      while q < x_max:
        # find all square roots mod p^n via Hensel Lifting
        r = int((r + (n - r*r)*my_math.mod_inv(r+r, q))%q)
        #assert r*r%q == n%q
        roots += [r]
        q *= p
      mod_root += [roots]
      num_prime += 1
    elif leg == 0:
      if verbose:
        print 'trial division found factors:'
        print p, 'x', n/p
      return p

    p = pg.next()

  # fudging the threshold down a bit makes it easier to find powers of partial-partial
  # relationships, but it also makes the smoothness check slower. reducing by twice the log
  # of the largest prime in the factor base results in cofactors less than that value squared
  thresh = math.log(m_val, 10) - log_p[-1]*2

  # skip small primes. they contribute very little to the log sum
  # and add a lot of unnecessary entries to the table
  # instead, fudge the threshold down a bit, according to expected number of factors
  min_prime = int(thresh*2)
  sp_idx = my_math.binary_search(prime, min_prime)
  sieve_primes = prime[sp_idx:]

  fudge = sum([log_p[i]/(prime[i]-1) for i in xrange(sp_idx)])

  sums = [fudge]*x_max_2

  if verbose:
    print 'smoothness bound:', bound
    print 'sieve size:', x_max
    print 'log threshold:', thresh
    print 'skipping primes less than:', min_prime

  smooth = []
  used_prime = set()
  partial = {}
  num_smooth = 0
  prev_num_smooth = 0
  num_used_prime = 0
  num_partial = 0
  num_poly = 0
  root_A = my_math.isqrt(root_2n / x_max)

  if verbose:
    print 'sieving for smooths...'
  while True:
    # find an integer value A such that:
    # A is =~ sqrt(2*n) / x_max
    # A is a perfect square
    # sqrt(A) is prime, and n is a quadratic residue mod sqrt(A)
    while True:
      root_A = my_math.next_prime(root_A)
      leg = my_math.legendre(n, root_A)
      if leg == 1:
        break
      elif leg == 0:
        if verbose:
          print 'dumb luck found factors:'
          print root_A, 'x', n/root_A
        return root_A

    A = root_A * root_A

    # solve for an adequate B
    # B*B is a quadratic residue mod n, such that B*B-A*C = n
    # this is unsolvable if n is not a quadratic residue mod sqrt(A)
    b = my_math.mod_sqrt(n, root_A)
    B = (b + (n - b*b) * my_math.mod_inv(b + b, root_A))%A

    # B*B-A*C = n <=> C = (B*B-n)/A
    C = (B*B - n) / A

    num_poly += 1

    # sieve for prime factors
    i = sp_idx
    for p in sieve_primes:
      logp = log_p[i]

      e = 0
      q = p
      while q < x_max:
        inv_A = my_math.mod_inv(A, q)
        # modular root of the quadratic
        a = int(((mod_root[i][e] - B) * inv_A)%q)
        b = int(((q - mod_root[i][e] - B) * inv_A)%q)

        amx = a+x_max
        bmx = b+x_max

        apx = amx-q
        bpx = bmx-q

        k = q
        while k < x_max:
          sums[apx+k] += logp
          sums[bpx+k] += logp
          sums[amx-k] += logp
          sums[bmx-k] += logp
          k += q

        q *= p
        e += 1

      i += 1

    # check for smooths
    x = -x_max
    i = 0
    while i < x_max_2:
      v = sums[i]
      if v > thresh:
        vec = set()
        sqr = []
        # because B*B-n = A*C
        # (A*x+B)^2 - n = A*A*x*x+2*A*B*x + B*B - n
        #               = A*(A*x*x+2*B*x+C)
        # gives the congruency
        # (A*x+B)^2 = A*(A*x*x+2*B*x+C) (mod n)
        # because A is chosen to be square, it doesn't need to be sieved
        sieve_val = (A*x + B+B)*x + C

        if sieve_val < 0:
          vec = {-1}
          sieve_val = -sieve_val

        for p in prime:
          while sieve_val%p == 0:
            if p in vec:
              # keep track of perfect square factors
              # to avoid taking the sqrt of a gigantic number at the end
              sqr += [p]
            vec ^= {p}
            sieve_val = int(sieve_val / p)

        if sieve_val == 1:
          # smooth
          smooth += [(vec, (sqr, (A*x+B), root_A))]
          used_prime |= vec
        elif sieve_val in partial:
          # combine two partials to make a (xor) smooth
          # that is, every prime factor with an odd power is in our factor base
          pair_vec, pair_vals = partial[sieve_val]
          sqr += list(vec & pair_vec) + [sieve_val]
          vec ^= pair_vec
          smooth += [(vec, (sqr + pair_vals[0], (A*x+B)*pair_vals[1], root_A*pair_vals[2]))]
          used_prime |= vec
          num_partial += 1
        else:
          # save partial for later pairing
          partial[sieve_val] = (vec, (sqr, A*x+B, root_A))
      x += 1

      # reset the value for the next go
      sums[i] = fudge
      i += 1

    prev_num_smooth = num_smooth
    num_smooth = len(smooth)
    num_used_prime = len(used_prime)

    if verbose:
      print 100 * num_smooth / num_prime, 'percent complete\r',

    if num_smooth > num_used_prime and num_smooth > prev_num_smooth:
      if verbose:
        print '%d polynomials sieved (%d values)'%(num_poly, num_poly*x_max_2)
        print 'found %d smooths (%d from partials) in %.3f seconds'%(num_smooth, num_partial, time.time()-time1)
        print 'solving for non-trivial congruencies...'

      # set up bit fields for gaussian elimination
      masks = []
      mask = 1
      bit_fields = [0]*num_used_prime
      for vec, vals in smooth:
        masks += [mask]
        i = 0
        for p in used_prime:
          if p in vec: bit_fields[i] |= mask
          i += 1
        mask += mask

      # row echelon form
      col_offset = 0
      null_cols = []
      for col in xrange(num_smooth):
        pivot = col-col_offset == num_used_prime or bit_fields[col-col_offset] & masks[col] == 0
        for row in xrange(col+1-col_offset, num_used_prime):
          if bit_fields[row] & masks[col]:
            if pivot:
              bit_fields[col-col_offset], bit_fields[row] = bit_fields[row], bit_fields[col-col_offset]
              pivot = False
            else:
              bit_fields[row] ^= bit_fields[col-col_offset]
        if pivot:
          null_cols += [col]
          col_offset += 1

      # reduced row echelon form
      for row in xrange(num_used_prime):
        # lowest set bit
        mask = bit_fields[row] & -bit_fields[row]
        for up_row in xrange(row):
          if bit_fields[up_row] & mask:
            bit_fields[up_row] ^= bit_fields[row]

      # check for non-trivial congruencies
      for col in null_cols:
        all_vec, (lh, rh, rA) = smooth[col]
        lhs = lh   # sieved values (left hand side)
        rhs = [rh] # sieved values - n (right hand side)
        rAs = [rA] # root_As (cofactor of lhs)
        i = 0
        for field in bit_fields:
          if field & masks[col]:
            vec, (lh, rh, rA) = smooth[i]
            lhs += list(all_vec & vec) + lh
            all_vec ^= vec
            rhs += [rh]
            rAs += [rA]
          i += 1

        factor = my_math.gcd(my_math.list_prod(rAs)*my_math.list_prod(lhs) - my_math.list_prod(rhs), n)
        if 1 < factor < n:
          break
      else:
        if verbose:
          print 'none found.'
        continue
      break

  if verbose:
    print 'factors found:'
    print factor, 'x', n/factor
    print 'time elapsed: %.3f seconds'%(time.time()-time1)
  return factor

if __name__ == "__main__":
  import argparse
  parser = argparse.ArgumentParser(description='Uses a MPQS to factor a composite number')
  parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
  parser.add_argument('--verbose', dest='verbose', action='store_true', help="enable verbose output")
  args = parser.parse_args()

  if args.verbose:
    mpqs(args.composite, args.verbose)
  else:
    time1 = time.time()
    print mpqs(args.composite)
    print 'time elapsed: %.3f seconds'%(time.time()-time1)

my_math.py
import math
import mpqs

# primes less than 212
small_primes = [
    2,  3,  5,  7, 11, 13, 17, 19, 23, 29, 31, 37,
   41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
   97,101,103,107,109,113,127,131,137,139,149,151,
  157,163,167,173,179,181,191,193,197,199,211]

# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
    1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
   53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,
  107,109,113,121,127,131,137,139,143,149,151,157,
  163,167,169,173,179,181,187,191,193,197,199,209]

# distances between sieve values
offsets = [
  10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
   6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
   2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
   4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]

# tabulated, mod 105
dindices =[
  0,10, 2, 0, 4, 0, 0, 0, 8, 0, 0, 2, 0, 4, 0,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 6, 0, 0, 2,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 2,
  0, 6, 6, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 4, 2,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 6, 2,
  0, 6, 0, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 8,
  0, 0, 2, 0,10, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2]

max_int = 2147483647

# returns the index of x in a sorted list a
# or the index of the next larger item if x is not present
# i.e. the proper insertion point for x in a
def binary_search(a, x):
  s = 0
  e = len(a)
  m = e >> 1
  while m != e:
    if a[m] < x:
      s = m
      m = (s + e + 1) >> 1
    else:
      e = m
      m = (s + e) >> 1
  return m

# divide and conquer list product
def list_prod(a):
  while len(a) > 1:
    a = [m*n for m,n in zip(a[::2], a[1::2] + [1])]
  return a[0]

# greatest common divisor of a and b
def gcd(a, b):
  while b:
    a, b = b, a%b
  return a

# extended gcd
def ext_gcd(a, m):
  a = int(a%m)
  x, u = 0, 1
  while a:
    x, u = u, x - (m/a)*u
    m, a = a, m%a
  return (m, x, u)

# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
  return pow(a, (m-1) >> 1, m)

# modular inverse of a mod m
def mod_inv(a, m):
  return ext_gcd(a, m)[1]

# modular sqrt(n) mod p
# p must be prime
def mod_sqrt(n, p):
  a = n%p
  if p%4 == 3:
    return pow(a, (p+1) >> 2, p)
  elif p%8 == 5:
    v = pow(a << 1, (p-5) >> 3, p)
    i = ((a*v*v << 1) % p) - 1
    return (a*v*i)%p
  elif p%8 == 1:
    # Shanks' method
    q = p-1
    e = 0
    while q&1 == 0:
      e += 1
      q >>= 1

    n = 2
    while legendre(n, p) != p-1:
      n += 1

    w = pow(a, q, p)
    x = pow(a, (q+1) >> 1, p)
    y = pow(n, q, p)
    r = e
    while True:
      if w == 1:
        return x

      v = w
      k = 0
      while v != 1 and k+1 < r:
        v = (v*v)%p
        k += 1

      if k == 0:
        return x

      d = pow(y, 1 << (r-k-1), p)
      x = (x*d)%p
      y = (d*d)%p
      w = (w*y)%p
      r = k
  else: # p == 2
    return a

#integer sqrt of n
def isqrt(n):
  c = (n << 2)/3
  d = c.bit_length()

  a = d>>1
  if d&1:
    x = 1 << a
    y = (x + (n >> a)) >> 1
  else:
    x = (3 << a) >> 2
    y = (x + (c >> a)) >> 1

  if x != y:
    x = y
    y = (x + n/x) >> 1
    while y < x:
      x = y
      y = (x + n/x) >> 1
  return x

# integer cbrt of n
def icbrt(n):
  d = n.bit_length()

  if d%3 == 2:
    x = 3 << d/3-1
  else:
    x = 1 << d/3

  y = (2*x + n/(x*x))/3
  if x != y:
    x = y
    y = (2*x + n/(x*x))/3
    while y < x:
      x = y
      y = (2*x + n/(x*x))/3
  return x

# strong probable prime
def is_sprp(n, b=2):
  if n < 2: return False
  d = n-1
  s = 0
  while d&1 == 0:
    s += 1
    d >>= 1

  x = pow(b, d, n)
  if x == 1 or x == n-1:
    return True

  for r in xrange(1, s):
    x = (x * x)%n
    if x == 1:
      return False
    elif x == n-1:
      return True

  return False

# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
  P = 1
  Q = (1-D) >> 2

  # n+1 = 2**r*s where s is odd
  s = n+1
  r = 0
  while s&1 == 0:
    r += 1
    s >>= 1

  # calculate the bit reversal of (odd) s
  # e.g. 19 (10011) <=> 25 (11001)
  t = 0
  while s:
    if s&1:
      t += 1
      s -= 1
    else:
      t <<= 1
      s >>= 1

  # use the same bit reversal process to calculate the sth Lucas number
  # keep track of q = Q**n as we go
  U = 0
  V = 2
  q = 1
  # mod_inv(2, n)
  inv_2 = (n+1) >> 1
  while t:
    if t&1:
      # U, V of n+1
      U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
      q = (q * Q)%n
      t -= 1
    else:
      # U, V of n*2
      U, V = (U * V)%n, (V * V - 2 * q)%n
      q = (q * q)%n
      t >>= 1

  # double s until we have the 2**r*sth Lucas number
  while r:
    U, V = (U * V)%n, (V * V - 2 * q)%n
    q = (q * q)%n
    r -= 1

  # primality check
  # if n is prime, n divides the n+1st Lucas number, given the assumptions
  return U == 0

## Baillie-PSW ##
# this is technically a probabalistic test, but there are no known pseudoprimes
def is_bpsw(n):
  if not is_sprp(n, 2): return False

  # idea shamelessly stolen from Mathmatica's PrimeQ
  # if n is a 2-sprp and a 3-sprp, n is necessarily square-free
  if not is_sprp(n, 3): return False

  a = 5
  s = 2
  # if n is a perfect square, this will never terminate
  while legendre(a, n) != n-1:
    s = -s
    a = s-a
  return is_lucas_prp(n, a)

# an 'almost certain' primality check
def is_prime(n):
  if n < 212:
    m = binary_search(small_primes, n)
    return n == small_primes[m]

  for p in small_primes:
    if n%p == 0:
      return False

  # if n is a 32-bit integer, perform full trial division
  if n <= max_int:
    p = 211
    while p*p < n:
      for o in offsets:
        p += o
        if n%p == 0:
          return False
    return True

  return is_bpsw(n)

# next prime strictly larger than n
def next_prime(n):
  if n < 2:
    return 2

  n += 1
  if n < 212:
    m = binary_search(small_primes, n)
    return small_primes[m]

  # find our position in the sieve rotation via binary search
  x = int(n%210)
  m = binary_search(indices, x)
  i = int(n + (indices[m] - x))

  # adjust offsets
  offs = offsets[m:] + offsets[:m]
  while True:
    for o in offs:
      if is_prime(i):
        return i
      i += o

# an infinite prime number generator
def primes(start = 0):
  for n in small_primes[start:]: yield n
  pg = primes(6)
  p = pg.next()
  q = p*p
  sieve = {221: 13, 253: 11}
  n = 211
  while True:
    for o in offsets:
      n += o
      stp = sieve.pop(n, 0)
      if stp:
        nxt = n/stp
        nxt += dindices[nxt%105]
        while nxt*stp in sieve:
          nxt += dindices[nxt%105]
        sieve[nxt*stp] = stp
      elif n < q:
        yield n
      else:
        sieve[q + dindices[p%105]*p] = p
        p = pg.next()
        q = p*p

# true if n is a prime power > 0
def is_prime_power(n):
  if n > 1:
    for p in small_primes:
      if n%p == 0:
        n /= p
        while n%p == 0: n /= p
        return n == 1

    r = isqrt(n)
    if r*r == n:
      return is_prime_power(r)

    s = icbrt(n)
    if s*s*s == n:
      return is_prime_power(s)

    p = 211
    while p*p < r:
      for o in offsets:
        p += o
        if n%p == 0:
          n /= p
          while n%p == 0: n /= p
          return n == 1

    if n <= max_int:
      while p*p < n:
        for o in offsets:
          p += o
          if n%p == 0:
            return False
      return True

    return is_bpsw(n)
  return False

max_trial = 1e10
max_pollard = 1e22

def factor(n):
  if n < max_trial:
    return factor_trial(n)
  for p in small_primes:
    if n%p == 0:
      return [p] + factor(n/p)
  if is_prime(n):
    return [n]
  if n < max_pollard:
    p = pollard_rho(n)
  else:
    p = lenstra_ecf(n) or mpqs.mpqs(n)
  return factor(p) + factor(n/p)

def factor_trial(n):
  a = []
  for p in small_primes:
    while n%p == 0:
      a += [p]
      n /= p
  i = 211
  while i*i < n:
    for o in offsets:
      i += o
      while n%i == 0:
        a += [i]
        n /= i
  if n > 1:
    a += [n]
  return a

def pollard_rho(n):
  # Brent's variant
  y, r, q = 0, 1, 1
  c, m = 9, 40
  g = 1
  while g == 1:
    x = y
    for i in range(r):
      y = (y*y + c) % n
    k = 0
    while k < r and g == 1:
      ys = y
      for j in range(min(m, r-k)):
        y = (y*y + c) % n
        q = q*abs(x-y) % n
      g = gcd(q, n)
      k += m
    r *= 2
  if g == n:
    ys = (ys*ys + c) % n
    g = gcd(n, abs(x-ys))
    while g == 1:
      ys = (ys*ys + c) % n
      g = gcd(n, abs(x-ys))
  return g

def ec_add((x1, z1), (x2, z2), (x0, z0), n):
  t1, t2 = (x1-z1)*(x2+z2), (x1+z1)*(x2-z2)
  x, z = t1+t2, t1-t2
  return (z0*x*x % n, x0*z*z % n)

def ec_double((x, z), (a, b), n):
  t1 = x+z; t1 *= t1
  t2 = x-z; t2 *= t2
  t3 = t1 - t2
  t4 = 4*b*t2
  return (t1*t4 % n, t3*(t4 + a*t3) % n)

def ec_multiply(k, p, C, n):
  # Montgomery ladder algorithm
  p0 = p
  q, p = p, ec_double(p, C, n)
  b = k >> 1
  while b > (b & -b):
    b ^= b & -b
  while b:
    if k&b:
      q, p = ec_add(p, q, p0, n), ec_double(p, C, n)
    else:
      q, p = ec_double(q, C, n), ec_add(p, q, p0, n),
    b >>= 1
  return q

def lenstra_ecf(n, m = 5):
  # Montgomery curves w/ Suyama parameterization.
  # Based on pseudocode found in:
  # "Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware"
  # Gaj, Kris et. al
  # http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
  # Phase 2 is not implemented.
  B1, B2 = 8, 13
  for i in range(m):
    pg = primes()
    p = pg.next()
    k = 1
    while p < B1:
      k *= p**int(math.log(B1, p))
      p = pg.next()
    for s in range(B1, B2):
      u, v = s*s-5, 4*s
      x = u*u*u
      z = v*v*v
      t = pow(v-u, 3, n)
      P = (x, z)
      C = (t*(3*u+v) % n, 4*x*v % n)
      Q = ec_multiply(k, P, C, n)
      g = gcd(Q[1], n)
      if 1 < g < n: return g
    B1, B2 = B2, B1 + B2

if __name__ == "__main__":
  import argparse
  import time
  parser = argparse.ArgumentParser(description='Uses a various methods to factor a composite number')
  parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
  args = parser.parse_args()

  time1 = time.time()
  print factor(args.composite)
  print 'time elapsed: %.3f seconds'%(time.time()-time1)

Sample I/O:
$ pypy mpqs.py --verbose 523022617466601111760007224100074291200000001
smoothness bound: 14998
sieve size: 74990
log threshold: 18.7325510316
skipping primes less than: 37
sieving for smooths...
230 polynomials sieved (34495400 values)
found 849 smooths (242 from partials) in 0.786 seconds
solving for non-trivial congruencies...
factors found:
37280713718589679646221 x 14029308060317546154181
time elapsed: 1.011 seconds

Note: not using the --verbose option will give slightly better timings:
$ pypy mpqs.py 523022617466601111760007224100074291200000001
37280713718589679646221
time elapsed: 0.902 seconds

Basic Concepts
In general, a quadratic sieve is based on the following observation: any odd composite \$n\$ may be represented as:
\$n=(x+d)(x-d)=x^2-d^2\Rightarrow d^2=x^2-n\$
This is not very difficult to confirm. Since \$n\$ is odd, the distance between any two cofactors of \$n\$ must be even \$2d\$, where \$x\$ is the mid point between them. Moreover, the same relation holds for any multiple of \$n\$
\$abn=(ax+ad)(bx-bd)=abx^2-abd^2\Rightarrow abd^2=abx^2-abn\$
Note that if any such \$x\$ and \$d\$ can be found, it will immediately result in a (not necessarily prime) factor of \$n\$, since \$x+d\$ and \$x-d\$ both divide \$n\$ by definition. This relation can be further weakened - at the consequence of allowing potential trivial congruencies - to the following form:
\$d^2\equiv x^2\mod n\$
So in general, if we can find two perfect squares which are equivalent mod \$n\$, then it's fairly likely that we can directly produce a factor of \$n\$ a la \$\gcd(x±d,n)\$. Seems pretty simple, right?
Except it's not. If we intended to conduct an exhaustive search over all possible \$x\$, we would need to search the entire range from \$\sqrt{n}\$ to \$\sqrt{2n}\$, which is marginally smaller than full trial division, but also requires an expensive is_square operation each iteration to confirm the value of \$d\$. Unless it is known beforehand that \$n\$ has factors very near \$\sqrt{n}\$, trial division is likely to be faster.
Perhaps we can weaken this relation even more. Suppose we chose an \$x\$, such that for
\$y\equiv x^2\mod n\$
a full prime factorization of \$y\$ is readily known. If we had enough such relations, we should be able to construct an adequate \$d\$, if we choose a number of \$y\$ such that their product is a perfect square; that is, all prime factors are used an even number of times. In fact, if we have more such \$y\$ than the total number of unique prime factors they contain, a solution is guaranteed to exist; It becomes a system of linear equations. The question now becomes, how do we chose such \$x\$? That's where sieving comes into play.
The Sieve
Consider the polynomial:
\$y(x)=x^2-n\$
Then for any prime \$p\$ and integer \$k\$, the following is true:
\$y(x+kp)=(x+kp)^2-n\\y(x+kp)=x^2+2xkp+(kp)^2-n\\y(x+kp)=y(x)+2xkp+(kp)^2\equiv y(x)\mod p\$
This means that after solving for the roots of the polynomial mod \$p\$ - that is, you've found an \$x\$ such that \$y(x)\equiv 0\mod p\$, ergo \$y\$ is divisible by \$p\$ - then you have found an infinite number of such \$x\$. In this way, you can sieve over a range of \$x\$, identifying small prime factors of \$y\$, hopefully finding some for which all prime factors are small. Such numbers known as \$k-smooth\$, where \$k\$ is the largest prime factor used.
There's a few problems with this approach, though. Not all values of \$x\$ are adequate, in fact, there's only very few of them, centered around \$\sqrt{n}\$. Smaller values will become largely negative (due to the \$-n\$ term), and larger values will become too large, such that it is unlikely that their prime factorization consists only of small primes. There will be a number of such \$x\$, but unless the composite you're factoring is very small, it's highly unlikely that you'll find enough smooths to result in a factorization. And so, for larger \$n\$, it becomes necessary to sieve over multiple polynomials of a given form.
Multiple Polynomials
So we need more polynomials to sieve? How about this:
\$y(x)=(Ax+B)^2-n\$
That'll work. Note that \$A\$ and \$B\$ could literally be any integer value, and the math still holds. All we need to do is choose a few random values, solve for the root of the polynomial, and sieve the values close to zero. At this point we could just call it good enough: if you throw enough stones in random directions, you're bound to break a window sooner or later.
Except, there's a problem with that too. If the slope of the polynomial is large at the x-intercept, there'll only be a few suitable values to sieve per polynomial. It'll work, but you'll end up sieving a whole lot of polynomials before you get what you need. Can we do better?
We can do better. An observation, as a result of Montgomery is as follows: if \$A\$ and \$B\$ are chosen such that there exists some \$C\$ satisfying
\$B^2-n=AC\$
then the entire polynomial can be rewritten as
\$y(x)=(Ax+B)^2-n=(Ax)^2+2ABx+B^2-n=A(Ax^2+2Bx+C)\$
Furthermore, if \$A\$ is chosen to be a perfect square, the leading \$A\$ term can be neglected while sieving, resulting in much smaller values, and a much flatter curve. For such a solution to exist, \$n\$ must be a quadratic residue mod \$\sqrt{A}\$, which can be known immediately by computing the Legendre symbol:
\$(n|\sqrt{A})=1\$. Note that in order to solve for \$B\$, a complete prime factorization of \$\sqrt{A}\$ needs to be known (in order to take the modular square root \$\sqrt{n}\mod\sqrt{A}\$), which is why \$\sqrt{A}\$ is typically chosen to be prime.
It can then be shown that if \$A\approx\frac{\sqrt{2n}}{M}\$, then for all values of \$x\in[-M,M]\$:
\$|y(x)|\le\frac{M\sqrt{2n}}{2}\$
And now, finally, we have all the components necessary to implement our sieve. Or do we?
Powers of Primes as Factors
Our sieve, as described above, has one major flaw. It can identify which values of \$x\$ will result in a \$y\$ divisible by \$p\$, but it cannot identify whether or not this \$y\$ is divisible by a power of \$p\$. In order to determine that, we would need to perform trial division on the value to be sieved, until it is no longer divisible by \$p\$.

Edit: This is incorrect. The roots of \$n\$ mod \$p^k\$ can be computed directly from the roots mod \$p\$ through the use of Hensel Lifting. This current implementation does precisely this.

We seemed to have reached an impasse: the whole point of the sieve was so that we didn't have to do that. Time to check the playbook.
\$\ln(a\cdot b\cdot c\cdot d\cdot\ldots)=\ln(a)+\ln(b)+\ln(c)+\ln(d)+\ln(\ldots)\$
That looks pretty useful. If the sum of the \$\ln\$ of all of the small prime factors of \$y\$ is close to the expected value of \$\ln(y)\$, then it's almost a given that \$y\$ has no other factors. In addition, if we adjust the expected value down a little bit, we can also identify values as smooth which have several powers of primes as factors. In this way, we can use the sieve as a 'pre-screening' process, and only factor those values which are likely to be smooth.
This has a few other advantages as well. Note that small primes contribute very little to the \$\ln\$ sum, but yet they require the most sieve time. Sieving the value 3 requires more time than 11, 13, 17, 19, and 23 combined. Instead, we can just skip the first few primes, and adjust the threshold down accordingly, assuming a certain percentage of them would have passed.
Another result, is that a number of values will be allowed to 'slip through', which are mostly smooth, but contain a single large cofactor. We could just discard these values, but suppose we found another mostly smooth value, with exactly the same cofactor. We can then use these two values to construct a usable \$y\$; since their product will contain this large cofactor squared, it no longer needs to be considered.
Putting it all together
The last thing we need to do is to use these values of \$y\$ construct an adequate \$x\$ and \$d\$. Suppose we only consider the non-square factors of \$y\$, that is, the prime factors of an odd power. Then, each \$y\$ can be expressed in the following manner:
\$y_0=p_0^0\cdot p_1^1\cdot p_2^1\cdots p_n^0\\y_1=p_0^1\cdot p_1^0\cdot p_2^1\cdots p_n^1\\y_2=p_0^0\cdot p_1^0\cdot p_2^0\cdots p_n^1\\y_3=p_0^1\cdot p_1^1\cdot p_2^0\cdots p_n^0\\\vdots\$
which can be expressed in the matrix form:
\$M=\begin{bmatrix}0&1&1&\cdots&0\\1&0&1&\cdots&1\\0&0&0&\cdots&1\\1&1&0&\cdots&0\\\vdots\end{bmatrix}\$
The problem then becomes to find a vector \$v\$ such that \$vM=\vec{0}\mod 2\$, where \$\vec{0}\$ is the null vector. That is, to solve for the left null space of \$M\$. This can be done in a number of ways, the simplest of which is to perform Gaussian Elimination on \$M^T\$, replacing the row addition operation with a row xor. This will result in a number of null space basis vectors, any combination of which will produce a valid solution.
The construction of \$x\$ is fairly straight-forward. It is simply the product of \$Ax+B\$ for each of the \$y\$ used. The construction of \$d\$ is slightly more complicated. If we were to take the product of all \$y\$, we will end up with a value with 10s of thousands, if not 100s of thousands of digits, for which we need to find the square root. This calcuation is impractically expensive. Instead, we can keep track of the even powers of primes during the sieving process, and then use and and xor operations on the vectors of non-square factors to reconstruct the square root.
I seem to have reached the 30000 character limit. Ahh well, I suppose that's good enough. Saved a bunch of bytes by switching to \$MathJax\$.


Write a continuous quine (quine-variant) Let's define a 2-quine as a program that prints its source code two times. For example, if the program ABC printed ABCABC, it would be a 2-quine.
Let's define a 3-quine as a program that prints its source code three times. For example, if the program ABC printed ABCABCABC, it would be a 3-quine.
Let's define a n-quine as a program that prints its source code n times.

Your task is to write a 2-quine, that prints a 3-quine, that prints a 4-quine, that prints a 5-quine, etc...
For example, here is an example of a valid submission (which is fictional of course):
AB

which prints
ABAB

which prints
ABABABABABAB

which prints
ABABABABABABABABABABABABABABABABABABABABABABABAB

etc.
Remember, this is code-golf, so the program with the fewest bytes wins.

QBasic (224 bytes incl. trailing CR+LF)

(Tested with QBasic/MS-DOS on a virtual machine as well as with FreeBASIC with "-lang qb" setting)

a$="a$=:l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend":l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend


The Spain license plates game This question is based on a question I asked in Spanish language. Yes, I asked for an algorithm in Spanish Language. :)

In Spain, current license plates have this pattern:

  1234 XYZ

where XYZ are three consonants taken from the full set of Spanish consonants (except the 'Ñ', I think).

Sometimes, when traveling with my wife, we use to play a game. When we see a license plate, we take its three consonants and try to form a word that contains those three consonants, appearing in the same order as in the license plate. Examples (in Spanish):

BCD
    BoCaDo (valid)
    CaBezaDa (not valid)
FTL
    FaTaL (valid)
    FLeTar (not valid)
FTR
    FleTaR (valid, wins)
    caFeTeRa (valid, loses)

The winner is the one who uses the least number of characters, as you can see in the last example.

The challenge

Write the shortest program or function that receives a list of words and a set of three consonants and finds the shortest word in the list that contains the three consonants in the same order. For the purposes of this game, case does not matter.

The input for the word list (first parameter) will be an array of your language string type. The second parameter (the three consonants) will be another string. If it's better for your language, consider the string with the three consonants the last item of the whole list of parameters. The output will be another string.
The words in the word list won't be invented or infinite words, they will word that appear in any standard dictionary. If you need a limit, suppose no word in the word list will be longer than 50 characters.
If there are several words with the same lenght that could be the valid answer, you can return any one of them. Just make sure you return just one word, or an empty string if no words match the pattern of three consonants.
You can repeat consonants in the group, so valid inputs for the three consonants are both FLR and GGG.
The Spanish consonants are exactly the same as English, with the addition of the "Ñ". The vowels are the same with the adition of the stressed vowels: "áéíóúü". There won't be any other kind of marks such as "-" or "'".
You can suppose the case will always be the same in both the word list and the three consonants.

If you want to test your algorithm with a real collection of Spanish words, you can download a file (15.9 MB) from Dropbox with more than a million words.

Test cases

Input: 'psr', {'hola' 'repasar' 'pasarais' 'de' 'caída' 'pequeñísimo' 'agüeros'}
Output: 'repasar'

Input: 'dsd', {'dedos' 'deseado' 'desde' 'sedado'}
Output: 'desde'

Input: 'hst', {'hastío' 'chest'}
Output: 'chest'

This is code-golf, so may the shortest program that helps me to always beat my wife wins! :)

05AB1E, 10 8 bytes

Saved 2 bytes thanks to Leo

ʒæså}éR`

Try it online!

Explanation

ʒ         # filter list, keep only members for which the following is true
  så      # input is in the
 æ        # powerset of the current word
    }     # end filter
     é    # sort by length
      R   # reverse
       `  # push separately (shortest on top)

I would have used head at the end saving a byte but that would output an empty list if there isn't a match.


Is this number a repdigit? Challenge
A repdigit is a non-negative integer whose digits are all equal.
Create a function or complete program that takes a single integer as input and outputs a truthy value if the input number is a repdigit in base 10 and falsy value otherwise.
The input is guaranteed to be a positive integer.
You may take and use input as a string representation in base 10 with impunity.
Test cases
These are all repdigits below 1000.
1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
111
222
333
444
555
666
777
888
999

A larger list can be found on OEIS.
Winning
The shortest code in bytes wins. That is not to say that clever answers in verbose languages will not be welcome.

Brachylog, 1 byte

=

Try it online!

This acts on integers.

From src/predicates.pl#L1151:

brachylog_equal('integer':0, 'integer':0, 'integer':0).
brachylog_equal('integer':0, 'integer':I, 'integer':I) :-
    H #\= 0,
    integer_value('integer':_:[H|T], I),
    brachylog_equal('integer':0, [H|T], [H|T]).


Am I an insignificant array? An insignificant array is an array of positive integers, where the absolute differences between consecutive elements are all smaller than or equal to 1.
For example, the following array is insignificant:
[1, 2, 3, 4, 3, 4, 5, 5, 5, 4]

Because the corresponding (absolute) differences are:
[1, 1, 1, 1, 1, 1, 0, 0, 1]

Which are all smaller than or equal to 1.

Your task is to determine whether a given array of integers is insignificant.

You may assume that the array always contains at least two elements.
Standard input and output rules apply. You may take input (and output) in any reasonable format.
Default Loopholes are forbidden.
The truthy / falsy values have to be distinct and consistent.
This is code-golf, so shortest answer in bytes wins.

Test cases

Input -> Output

[1, 2, 3, 4, 3, 4, 5, 5, 5, 4] -> true
[1, 2, 3, 4, 5, 6, 7, 8, 9, 8] -> true
[3, 3, 3, 3, 3, 3, 3]          -> true
[3, 4, 4, 4, 3, 3, 3, 4, 4, 4] -> true
[1, 2, 3, 4]                   -> true
[5, 4, 3, 2]                   -> true
[1, 3, 5, 7, 9, 7, 5, 3, 1]    -> false
[1, 1, 1, 2, 3, 4, 5, 6, 19]   -> false
[3, 4, 5, 6, 7, 8, 7, 5]       -> false
[1, 2, 4, 10, 18, 10, 100]     -> false
[10, 20, 30, 30, 30]           -> false

I used the values true and false.

Jelly, 3 bytes
IỊẠ

Try it online!
How?
Just the perfect challenge for Jelly.

IỊẠ   Full program.

I     Increments; Get the difference between consecutive elements.
 Ị    Insignificant; return abs(number) ≤ 1.
  Ạ   All; returns 1 if all the elements are truthy, 0 otherwise.


Simulate D Flip-Flop Objective

Simulate an edge-triggered D Flip-Flop.

What is D Flip-Flop?

A D flip-flop is an electronic digital device that outputs an inputted data (abbr. D) with synchronization to a clock (abbr. CLK). Usually CLK is a uniform pulse, but in this challenge, CLK may be not uniform.

Input

A bitstring with length \$n\$ will be given as CLK and another bitstring with length \$n-1\$ will be given as D. A bit represents the state of an input during a unit time (tick). CLK leads D by half a tick.

Output

The output (abbr. Q) is a bitstring with same length and starting timepoint as D. If CLK doesn't start with 01, the starting bit of Q is implementation-defined. Q is updated upon a rising moment of CLK to the bit of D at the time. On the other times, Q retains its state.

Examples

The red line indicates a rising moment of CLK.

Example 1:

Example 2:

Rules

If CLK isn't a tick longer than D, the entire challenge falls into don't care situation.
Though defined as bitstrings, the actual elements of CLK, D, and Q doesn't matter. In this case, if a string is not binary (that is, contains a third character), the entire challenge falls into don't care situation.

J, 27 23 bytes

-4 bytes thanks to Bubbler!

;@(<@({.\);.1~1,2</\}.)

Try it online!

CLK is the left argument; D is the right one. When CLK doesn't start with 01, the starting bits are the same as the first bit of D.

                       ;.1  - cut
                          ] - the right argument (D)
   (          )             - where
         2 /\               - the previous element
             [              - of the left argument (CLK)
          <                 - is smaller than the next one
       }.                   - drop
      1                     - the first item
    1,                      - prepend with 1 (for cutting)
               (     )      - for each cut group
                   $        - make a list
                #           - of the same length as the group
                    {.      - with elements same as the first one
                 <@         - and box the list
  ;                         - unbox the sublists and flatten them
[:                          - function composition

K (oK), 27  23bytes

-4 bytes thanks to ngn!

{,/&\'|\'(0,&1_>':x)_y}

Try it online!


Generate Random Boggle Board Generate a 4x12 grid of letters / spaces:

Each die should appear precisely once, location randomly chosen.  Locations should be approximate a uniform random permutation of the dice.  Display a random (again, approximately uniform) face of each die.  Left-justify the face in the 3-character window.  For example,

A  E  A  A
E  C  D  E
D  A  Qu E
E  A  H  D

Is a non-randomized board in the format I want.  Trailing space is allowed.

The dice:

A  A  E  E  G  N
E  L  R  T  T  Y
A  O  O  T  T  W
A  B  B  J  O  O
E  H  R  T  V  W
C  I  M  O  T  U
D  I  S  T  T  Y
E  I  O  S  S  T
D  E  L  R  V  Y
A  C  H  O  P  S
H  I  M  N  Qu U
E  E  I  N  S  U
E  E  G  H  N  W
A  F  F  K  P  S
H  L  N  N  R  Z
D  E  I  L  R  X

Amusing fact: there is only 1 K in the set.  What other letter exclusively shares that die?

This is code-golf so the program with the shortest bytecount wins!

GolfScript, 116 bytes

Since the scoring is in bytes, I figure that means we can use all bytes in the solution.  Going outside the printable ASCII set allows a somewhat shorter solution than Peter Taylor's, at the cost of making the code harder to display here.  Without the unprintable data, my code looks like this:

'57 BYTES OF BINARY DATA HERE'256base 26base 6/{;9.?rand}${6rand=65+.81='  u '2/=}%8/n*

It's pretty similar to Peter Taylor's solution, and I admit to shamelessly borrowing bits of it (such as the .81='  u '2/= trick), although I think I managed to shorten his shuffle slightly, even after spending an extra char byte for better randomness.

The binary string in the beginning of the script contains unprintable characters, and so cannot be directly pasted here.  Instead, I'll provide the script as a hex dump:

0000000: 2701 8302 7c56 97d5 ec9c 52e3 462e 44d7  '...|V....R.F.D.
0000010: a8d2 81c9 6115 fc80 4da4 6cd3 b06f a6d8  ....a...M.l..o..
0000020: 4e7e 2029 12a9 f331 0b83 3481 de36 81e2  N~ )...1..4..6..
0000030: 41b4 534d dee8 13f7 ccfd 2732 3536 6261  A.SM......'256ba
0000040: 7365 2032 3662 6173 6520 362f 7b3b 392e  se 26base 6/{;9.
0000050: 3f72 616e 647d 247b 3672 616e 643d 3635  ?rand}${6rand=65
0000060: 2b2e 3831 3d27 2020 7520 2732 2f3d 7d25  +.81='  u '2/=}%
0000070: 382f 6e2a                                8/n*

On Linux, or any system with the xxd utility installed, this hex dump can be turned back into a working 116-byte GolfScript program by passing it through xxd -r.

Edit: Replaced 999rand with 9.?rand for much better randomness.  The shuffle should now be about as close to perfect as the underlying RNG allows.


Lorem Ipsum Random Code Generation An IDE developer has hired you to write a program that generates (by printing to stdout) n lines of randomly generated code. They will use your program to create sample code for use in marketing their newest compiler.

Rules:

Your randomly generated output code:

must not be the same each execution (for the same n parameter)
must be written in the same language as your program
must be able to be successfully compiled without errors or warnings (including "variable not used" messages, if your language includes them)
should use a variety of the language's built-in features
should (where appropriate) follow the language's most popular style guide. For example, PEP-8 for Python
should, if n is larger than 20, have functions. Functions should be limited to a length that follows the language's style guide
does not have to have comments (but the developer will be impressed if it does!)
may include a single blank line between code blocks for clarity

You can use an external dictionary to allow generation of function/variable names, and lists of standard functions/libraries for your language. If your program uses these, please include a link (to a pastebin if your dictionary is custom written for this task)

Please include a few sample outputs to demonstrate your program's capabilities.

Winning:

The winning program should implement all the above features, and generate realistic code without sacrificing execution time or program length (to a huge degree - this isn't golf).

The winner will be chosen by community vote from entries received before 1st May 2012. Voting should be based upon realism, variety, creativity and adherence to the criteria above.

Good luck!


Collect and place items The goal of this challenge is to collect selected items in a list and move them to a certain location in the list.

As a visual example, take the input values (represented by black boxed integers) and a corresponding list of truthy values where true denotes the item is selected (represented by blue boxes, where T is truthy and F is falsy):

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

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

The final solution is then 2,3,6,1,4,5,7.

Note that this logical diagram depicts one way this could be done; your program does not need to take the same logical steps as long as the output always produces the same observable result.

Input

Your program is given 3 inputs:

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

The input may come from any source desired (stdio, function parameter, etc.)

Output

The output is a list representing the final sequence of items. This can be to any source desired (stdio, return value, function output parameter, etc.). You are allowed to modify any of the inputs in-place (for example, given a modify-able list as a function parameter, and having your function operate in-place on that list).

Test cases

All of the following test cases assume 0-based indexing. I've used 0 and 1 to indicate falsy/truthy values respectively for the selection mask.

Test cases happen to have lists formatted as [a,b,c], but as long as your input lists represent a finite ordered sequence that's fine.

Input:

[]
[]
0

Output:

[]

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Scoring

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

MATL, 9 bytes
&)i:&)bwv

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


Make Bracket Squares Every programmer knows that brackets []{}()<> are really fun.  To exacerbate this fun, groups of interwoven brackets can be transformed into cute and fuzzy diagrams.

Let's say that you have a string that contains balanced brackets, like [{][<(]})>(()).  Step one is to rotate the string 45 degrees clockwise. (In Mathematica, this can be almost done with Rotate[ur_string,-pi/4]). Here is the result of the first step:

[
 {
  ]
   [
    <
     (
      ]
       }
        )
         >
          (
           (
            )
             )

Next add a diagonal space between each character.

[

  {

    ]

      [

        <

          (

            ]

              }

                )

                  >

                    (

                      (

                        )

                          )

Next, start with the left-most bracket and draw a square between it and its partner in crime.

+---+
|   |
| { |
|   |
+---+

      [

        <

          (

            ]

              }

                )

                  >

                    (

                      (

                        )

                          )

Repeat this process with each pair of brackets, overwriting previous characters with +s if need be.

+---+
|   |
| +-+---------+
| | |         |
+-+-+         |
  |           |
  |   [       |
  |           |
  |     <     |
  |           |
  |       (   |
  |           |
  |         ] |
  |           |
  +-----------+

                )

                  >

                    (

                      (

                        )

                          )

Continue until you have made everything nice and square.

+---+
|   |
| +-+---------+
| | |         |
+-+-+         |
  |           |
  |   +-----+ |
  |   |     | |
  |   | +---+-+---+
  |   | |   | |   |
  |   | | +-+-+-+ |
  |   | | | | | | |
  |   +-+-+-+ | | |
  |     | |   | | |
  +-----+-+---+ | |
        | |     | |
        | +-----+ |
        |         |
        +---------+

                    +-----+
                    |     |
                    | +-+ |
                    | | | |
                    | +-+ |
                    |     |
                    +-----+

Input

Input will be a single line of balanced brackets and no other characters, with each bracket being one of []{}()<>.  Each type of bracket is balanced individually, though different types may overlap (this is what makes the squares look interesting).  A trailing newline is optional.

Output

Output will be the interlocking square pattern generated from the bracket string.  Trailing spaces and trailing newline are optional, but there mustn't be leading whitespace.

Goal

This is code-golf, fewest bytes wins.


Scientist Seals Stranded upon an Iceberg Introduction

A family of seals are stranded upon an iceberg in the Arctic Circle. There is a radio transmitter located on the iceberg which the seals can use to call for help. However, only the daddy seal knows how to operate the radio transmitter. And worse, the ice is very slippery this time of year, so the seals will slide uncontrollably until they hit another seal or slide off the edge of the iceberg, making it very difficult for the daddy seal to reach the radio transmitter. Luckily, one of the seals is a computer scientist, so she decides to write a program to figure out how to manoeuvre the daddy seal to the radio transmitter. As there is not much space on the ice to write a program, she decides to make the program use as little bytes as possible.

Input Description

The seal's program will take input in from STDIN, command line arguments, or user input functions (such as raw_input()). It cannot be preinitialised in a variable (e.g. "This program expects the input in a variable x").

The first line of the input consists of two comma separated integers in the form

A,B

Following that is B lines consisting of A characters each. Each line can only contain characters out of the following:

.: The cold, cold, ocean. The map will always have this as a border.
#: A part of the iceberg.
a...z: A seal that is not the daddy seal on the iceberg.
D: The daddy seal on the iceberg.
*: The radio transmitter.

(Note that the daddy seal is always notated with an uppercase D. A lowercase d is simply a regular seal.)

Output Description

According to the following rules regarding how the seals can move, output a list of instructions for the seals on how they should move to get the daddy seal to the radio transmitter.

Rule: All seals can move up (U), down (D), left (L), and right (R). They cannot slide diagonally.
Rule: Upon moving, a seal will continue to move in the same direction until it collides with another seal or falls into the sea.

If a seal collides with another seal, it will stop moving. The seal it collided with will not move.
If a seal falls into the sea, it will drown and disappear from the map. That is, it does not act as a collider for other seals and it cannot be moved again.

Rule: Two seals cannot move at the same time, neither can a seal be moved while another one is still moving. The next seal can only be moved once the previous seal has stopped moving.
Rule: There is no restriction regarding moving a seal multiple times, or the number of seals that drown.
Rule: A correct solution will have the daddy seal end at the radio transmitter. The daddy seal cannot simply pass the transmitter while sliding.

The output will consist of several lines, each in the form

A,B

Where A is the seal to move (D for the daddy seal, a...z for others), and B is the direction to move the seal (either U, D, L, or R). Note that you do not need to find the shortest route. Any route that gets the daddy seal to the goal is an acceptable output.

Example Inputs and Outputs

Input:

25,5
.........................
.#######################.
.####D#############*k###.
.#######################.
.........................

Output:

D,R

Input:

9,7
.........
.a#####b.
.#####d#.
.##l*###.
.###m#p#.
.#D#.#c#.
.........

Output (one possible output out of many):

m,R
b,L
D,U
D,R
D,D
D,L

Input:

26,5
..........................
.###..................###.
.l*##########v#########D#.
.###..................###.
..........................

Output (one possible output out of many):

v,D
D,L

If you have any other questions, please ask in the comments.

Python 3, 520 bytes

R=range
g=[list(input())for i in R(int(input().split(',')[1]))]
f=set(sum(g,[]))-set(".#*")
L=8
def P(p,g):
 if len(p)>L:return
 for s in f:
  c=sum(y.index(s)for y in g if s in y)
  if c<1:continue
  r,=[n for n in R(len(g))if s in g[n]]
  for d in R(4):
   m=p+s+",%s\n"%"LURD"[d];G=[y[:]for y in g];o="#";i,j=I,J=r,c
   while"#"==o:G[i][j]="#";G[I][J]=s;i,j=I,J;I,J=i+d%2*(d-2),j+(~d%-2&d-1);o=G[I][J]
   if"."==o:G[i][j]="#"
   if"D"==s:
    if"."==o:continue
    if"*"==o:print(m);1/0
   P(m,G)
while 1:P("",g);L+=4

I may do a more detailed explanation later if people want, but basically this runs a depth-first search with iterative deepening on the state space of possible moves. If a move causes the daddy seal to fall off, it is immediately rejected. If the daddy ends up next to the transmitter, the sequence of moves is printed, and the program divides by zero to force an exit.

I can make the code run significantly faster by adding if G!=g: at the beginning of the second-last line, for 8 extra bytes--this rejects moves that don't change anything, such as k,L in the first test case.

The runtime varies noticeably from one run to the next, even with the same input--evidently a result of the fact that I pick the next seal to move by iterating over a set, which is an unordered type. I timed the second test case at 5 minutes 30 seconds, though it didn't seem that long the first time I ran it. With the optimization mentioned above, it's more like 40 seconds.


1, 2, 4, 8, 16, ... 33? Challenge

Write a function/program that outputs either the n'th element, or the first n elements, in the well known number sequence:

         1, 2, 4, 8, 16 ...

Oh, wait... I forgot the first few numbers:

1, 1, 1, 1, 2, 4, 8, 16 ...

Heck, I'll add a few more for good measure:

1, 1, 1, 1, 2, 4, 8, 16, 33, 69, 146, 312, 673, 1463, 3202, 7050, 15605, 34705 ...

The numbers are Generalized Catalan numbers given by the (zero-indexed) formula:

$$a(n+1)= a(n) + \sum_{k=2}^{n-1} a(k)\cdot a(n-1-k)$$

where

$$a(0)= a(1)= a(2)= a(3) = 1$$

This is OEIS A004149.

You may choose if you want to have the sequence zero- or one-indexed. The sequence must of course be the same, so you must rewrite the formula if you have it one-indexed.

Python, 51 bytes

f=lambda n,k=2:n<3or k<n and f(k)*f(n-k-2)+f(n,k+1)

Try it online!

Simplifies the formula a bit:

$$a(n) =  \sum_{k=2}^{n-1} a(k)\cdot a(n-2-k)$$

$$ a(-1) = a(0)= a(1)= a(2) = 1$$


Write a Chat Ping Counter Your task is to write a program, that given a list of chat messages, count how many times each person gets pinged, so I can know how popular everyone is.  But, since I have to do it surreptitiously, I need it to be as small as possible so I can hide the code.
Specs

The input comes in a list of 2-tuples, with each item being of the form ("username", "message").
A ping to another user is defined as an @ followed by 3 or more letters that unambiguously refers to that user.
However, you also have to consider replies, which have to start with :messageid followed by a space.
Assume the first message has id 0 and proceed sequentially.
Output each user and say how many times each one got pinged.
The output can be in any order/reasonable format.
This is code-golf, so shortest code in bytes wins!

Test Cases
[["AlexA.", "I am wrong"], ["Quartatoes", "@Alex you are very wrong"], ["AlexA.", ":1 I am only slightly wrong"]]
AlexA.: 1
Quartatoes: 1

[["Doorknob", "I have never eaten an avocad."], ["AquaTart", ":0 I will ship you an avocad"], ["AlexA.", ":0 this is shocking"]]
Doorknob: 2
AquaTart: 0
AlexA.: 0

[["Geobits", "I like causing sadness through downvotes."], ["Flawr", "I want to put random message ids in my chat messages :0 askjdaskdj"]]
Geobits: 0
Flawr: 0

[["Downgoat", "goatigfs.com/goatgif"], ["Downotherthing", "@Downgoat cool gifs"], ["Dennis", "@Down cool gifs this is an ambiguous ping"]]
Downgoat: 1
Downotherthing: 0
Dennis: 0

JavaScript (ES6), 245 210 bytes
a=>(p={},a.map(b=>p[b[0]]=0),(a.map(b=>b[1].match(/@[a-z]{3,}|^:\d+/gi)||[]).map(c=>c.map(d=>(z=(d[0]=='@'?(y=Object.keys(p).filter(e=>e.startsWith(d.slice(1)))).length<2?y:0:a[d.slice(1)[0]]))&&p[z[0]]++))),p)

Uses an object to create a unique list of names alongside pings. Then it looks through the messages for matches to either ping condition. If a name, it looks through the list of names to find if there is only one match, and then increments. If a reply, it simply references that index in the message array and pulls the name to be incremented. Finally, it returns the object.


When do I get my sandwich? Given one of the following inputs: Sweet Onion Chicken Teriyaki
Oven Roasted Chicken
Turkey Breast
Italian BMT
Tuna
Black Forest Ham
Meatball Marinara output a number from 1-7 (or 0-6) representing the day of the week that you get that deal, starting with Monday as the lowest number. Input can be all lowercase or uppercase if preferred (i.e "italian bmt"). No internet allowed.


Score a game of Bowling Your task is to sum up and output one player's score in a game of 10-pin bowling after up to 21 rolls.

The rolls are represented as a sequence of integers in your preferred method of input.
Each integer corresponds to the number of pins that were knocked down in that roll.

Scoring

After each round the number of pins knocked down in that round is counted into the final score.
If a player knocks down all ten pins in the first roll of a round, this is a strike, and the round is over.
Otherwise, the round lasts for one more roll. If the second roll of a round knocks down all the remaining pins, this is a spare.

For each strike there is a bonus equal to the sum of pins knocked down in the two next rolls.
For each spare there is a bonus equal to the number of pins knocked down in the next roll.

The 10th and final round, the player may be granted extra rolls:
In case of a strike, the player gets two more rolls to make up his strike bonus.
In case of a spare, the player gets one more roll.

Examples

Input: 4 3 8 2 7 1 10 7 3 0 10 2 2 10 10 5 4
Output: 131

Input: 10 10 9 1 7 3 2 7 10 1 9 10 7 1 10 10 10
Output: 183

Rules

You may assumed that the input is valid.
As per Mego's comment I have loosened the requirements for the input/output methods to meet our current standard.
Answers in languages that are newer than the challenge are allowed
Shortest code wins!

GolfScript, 50 41 characters
~0]-1%~0{\.9>{+1$3$}{@+.9>3$*}if++}10*p];

Another attempt in GolfScript (run it online).
An explanation of the code follows. The solution utilises the stack nature of the problem (consume rolls one after another) but therefore the input has to be reversed.
~0          # Take the input and evaluate to single numbers on the stack. Add zero.
]-1%~       # Reverse the stack (make array, reverse array, dump array)

0           # Start with a sum of zero
{           # Perform this block 10 times (once for each round)
  \         #   Take the next roll
  .9>{      #   If it is a strike
    +       #     Add the value of the roll to the sum
    1$3$    #     and duplicate top two members of the stack (i.e. next two rolls).
  }{        #   ... else ...
    @+      #     Take the next roll and add with first roll in round.
    .9>     #     Does this sum show a spare?
    3$*     #     Get next roll (potential bonus) and multiply with yes/no.
            #     Since we pushed an additional 0 in the beginning
            #     there is a spare roll even for the last round.
  }if       #   endif
  ++        #   Add top three stack entries together
            #   (i.e. sum+2 bonus rolls for strike, sum+rolls+bonus else)
}10*        # Loop ten times

p];         # Sum is top of stack. Print sum and discard any leftover rolls.

Previous version:
~].1>.1>]zip{((.10<{@(0=@+@1>1$9><}*@}10*;]{+}.@**