text:
Reading Code in 8 Ways to Output 8 Numbers
The English language and most programming languages are written and read from left-to-right, top-to-bottom, but that needn't be the case.
In fact for the block of text
ABC
DEF

I can think of eight related ways it might be read:

Left-to-right, top-to-bottom (LTR-TTB): ABCDEF
Top-to-bottom, left-to-right (TTB-LTR): ADBECF
Left-to-right, bottom-to-top (LTR-BTT): DEFABC
Bottom-to-top, left-to-right (BTT-LTR): DAEBFC
Right-to-left, top-to-bottom (RTL-TTB): CBAFED
Top-to-bottom, right-to-left (TTB-RTL): CFBEAD
Right-to-left, bottom-to-top (RTL-BTT): FEDCBA
Bottom-to-top, right-to-left (BTT-RTL): FCEBDA

Challenge
Write a rectangular block of text that can be read in each of the eight ways above as eight single line programs in your language of choice. Each of these programs should output a different integer from one to eight.
It doesn't matter which reading direction outputs which number, they do not have to match the numbers above. For example, if your text block were still
ABC
DEF

then the program ABCDEF might output 5 and FEDCBA might output 2, and the other six programs would output 1, 3, 4, 6, 7, and 8 in some order.
The text block may contain any characters except line terminators.
Output should go to stdout or a similar alternative if your language doesn't have a proper stdout. There is no input. You may assume the programs are run in a REPL environment.
Pietu1998 charitably wrote a JSFiddle that gives the 8 different single line programs when given a block of text. I've made it into a stack snippet:

<textarea onkeyup="f(this.value)" id="c" placeholder="Code"></textarea>
<input type="checkbox" id="b" onchange="f(document.getElementById('c').value)" checked/> Show directions

You can still find Martin's CJam version here.
Scoring
Your score is the area of your block of text (the width times the height). The submission with the lowest score wins. (Essentially the smallest code wins, hence the code-golf tag.) Tiebreaker goes to the earlier posted submission.
The example is 2 by 3 so its score is 6. A score less than 4 (2 by 2) is impossible because then some of the 8 programs would be identical and couldn't output two different values.

Why the "only printable ascii" rule? It means APL can't compete in this challenge. :(

I made a fiddle that converts a code block to the 8 programs. Could be included as a snippet, want OP's opinion on this though.

@MartinBüttner All right, I fixed it. It seems String.prototype.repeat() is still kinda new. Also confirmed to work in IE now. new fiddle

@MorisZucca All characters besides line terminators are now allowed.

@Pietu1998 Thanks for the Fiddle, I've added it as a snippet.

I am wondering if it might be possible to solve this using a solution of the form:
a+b (line break) +c+ (line break) d+e
where any or all of the +'es can be changed to any of the fundamental arithmetic operations. If so, that solution would be valid in many languages. But I guess that's more a mathematical problem than a codegolf :-)

I'm curious why "1" isn't a valid answer, (score 1), given that your language always evaluates and prints the result to stdout?  I'm thinking of programs like "pyth" or "bc"?  If there are some minimum number of rows and columns, then wouldn't that result in an automatic win with no thinking?

@swstephe It needs to output the numbers 1-8.

J, 3 * 3 = 9
1[2
+2+
2+2

Executing all directions:
       ". '1[2+2+2+2','2+2+2+1[2','1+2[2+2+2','2+2[2+1+2','2+2+2+2[1','2[1+2+2+2','2+2+2[2+1',:'2+1+2[2+2'
1 7 3 4 8 2 6 5

Explanation:

In J execution goes from right to left and there is no operator precedence.
The [ (left) takes the left side of its two operand so it essentially cancels the whole right side of our expression e.g. 1+2[2+2+2 becomes 1+2[6 and then 1+2.
The left expressions are additions with a total of 1, 2, 3 and 4 operands. There are two of each n-operand expressions one with the number 1 and one with only 2s. The additions with 1 generate the odd numbers and the others generate the even ones.

This is really nice. Replace [ with ; and it should work in most languages' REPL environment.

Befunge-98, 5x5 = 25 5x3 = 15
1+4+2
$.@.$
3+4+4

I wrote a little script that found the correct numbers for me. It took a while, but hey, I just beat GolfScript! :D
The scripts I used are here and here, but I don't suggest looking at them since the code style is extremely carcinogenic.
Subprograms
1+4+2$.@.$3+4+4   LTR-TTB   5
3+4+4$.@.$1+4+2   LTR-BTT   7
1$3+.+4@4+.+2$4   TTB-LTR   3
2$4+.+4@4+.+1$3   TTB-RTL   4
4+4+3$.@.$2+4+1   RTL-BTT   8
2+4+1$.@.$4+4+3   RTL-TTB   6
4$2+.+4@4+.+3$1   BTT-RTL   2
3$1+.+4@4+.+4$2   BTT-LTR   1

Old version
 1.6
3 @ 4
.@ @.
8 @ 7
 2.5

Subprograms
Output the numbers 1-8 respectively.
 1.6 3 @ 4.@ @.8 @ 7 2.5    LTR-TTB
 2.5 8 @ 7.@ @.3 @ 4 1.6    LTR-BTT
 3.8 1 @ 2.@ @.6 @ 5 4.7    TTB-LTR
 4.7 6 @ 5.@ @.1 @ 2 3.8    TTB-RTL
 5.2 7 @ 8.@ @.4 @ 3 6.1    RTL-BTT
 6.1 4 @ 3.@ @.7 @ 8 5.2    RTL-TTB
 7.4 5 @ 6.@ @.2 @ 1 8.3    BTT-RTL
 8.3 2 @ 1.@ @.5 @ 6 7.4    BTT-LTR

Brainfuck$, 4x3 = 12
Brainfuck$ is very similar to Brainfuck, but has some more commands, including a command to output the current cell value as numeric output, which was very useful for this challenge.
++:+
  ++
++++

One-line commands:
++:+  ++++++   LTR-TTB, outputs 2
++++  ++++:+   LTR-BTT, outputs 8
+ ++ +:+++++   TTB-LTR, outputs 4
+++:+++ ++ +   TTB-RTL, outputs 3
++++++  +:++   RTL-BTT, outputs 7
+:++++  ++++   RTL-TTB, outputs 1
+++++:+ ++ +   BTT-RTL, outputs 5
+ ++ +++:+++   BTT-LTR, outputs 6

I'd argue you don't need Brainfuck$'s ; command. I'd consider using simply . and outputting 0x01-0x08 perfectly valid. It's Brainfuck, for (brain)fuck's sake. +1.

I'd be ok with binary output.

TECO, 3*5 = 15
 +4 5
+2=4
 +1 \

= prints the value of the last numerical expression. \ is used to read or write numbers from strings, but I use it only as a discard here.

 +4 5+2=4  +1 \ 7
 + +2+4=1 4 5 \ 6
 + +2+1=4 4 \ 5 3
 +1 \+2=4  +4 5 2
\ 1+  4=2+5 4+  5
\ 5 4 1=4+2+ +  1
5 \ 4 4=1+2+ +  4
5 4+  4=2+\ 1+  8

piet - 12x12 = 144

Since a one line program can never terminate, assume it terminates after first output.
8 subprograms in a single image:

GolfScript, 4x4 = 16
1})7
)  }
}  )
3)}5

Makes use of the good old "super comment": an unmatched } ignores the rest of the code (in fact, in this case a normal comment # would have worked just as well, since all the code is run as a single line). So from each corner there's either only a single number, or (in the other direction) that number incremented by 1, because execution terminates and the stack contents are printed. The 8 programs are
1})7)  }}  )3)}5  # LTR-TTB
1)}3}  ))  }7})5  # TTB-LTR
3})1)  }}  )5)}7  # BTT-LTR
3)}5}  ))  }1})7  # LTR-BTT
5})3)  }}  )7)}1  # RTL-BTT
5)}7}  ))  }3})1  # BTT-RTL
7})5)  }}  )1)}3  # TTB-RTL
7)}1}  ))  }5})3  # RTL-BTT

Haskell, 26x26 = 676
Uses comments (--) to hide the backwards and sideways bits. This makes it terribly long
main=print 1--2 tnirp=niam
a                        a
i                        i
n                        n
=                        =
p                        p
r                        r
i                        i
n                        n
t                        t

3                        4
-                        -
-                        -
5                        6

t                        t
n                        n
i                        i
r                        r
p                        p
=                        =
n                        n
i                        i
a                        a
main=print 7--8 tnirp=niam

It seems to me that this can be extended to most languages with inline comments

Prelude, 5x3 = 15
12 34
  !
56 78

This assumes the Python interpreter, which prints values as numbers instead of character codes.
This doesn't beat Befunge$, but it does beat my GolfScript submission, and I like its simplicity. Note also that it uses only 9 non-space characters, which is less than any other submission so far (J strikes again :)). In Prelude, each digit is pushed onto the stack individually, and depending on the path, there's a different digit right before the !, which just prints the top stack element. The 8 programs are:
12 34  !  56 78   LTR-TTB   4
56 78  !  12 34   LTR-BTT   8
1 52 6 ! 3 74 8   TTB-LTR   6
4 83 7 ! 2 61 5   TTB-RTL   7
87 65  !  43 21   RTL-BTT   5
43 21  !  87 65   RTL-TTB   1
8 47 3 ! 6 25 1   BTT-RTL   3
5 16 2 ! 7 38 4   BTT-LTR   2

Alternatively, there's also
 1 3
1+!+1
 5 7

Which pushes the odd numbers on the vertical paths, and increments them by 1 on the horizontal paths:
 1 3 1+!+1 5 7    LTR-TTB   4
 5 7 1+!+1 1 3    LTR-BTT   8
 1 1+5 ! 3+7 1    TTB-LTR   5
 1 3+7 ! 1+5 1    TTB-RTL   7
 7 5 1+!+1 3 1    RTL-BTT   6
 3 1 1+!+1 7 5    RTL-TTB   2
 1 7+3 ! 5+1 1    BTT-RTL   3
 1 5+1 ! 7+3 1    BTT-LTR   1

CJam - 7×7
Not impressive, but there was no CJam answer and I like the way it looks :)
 8;];1
7     2
;  0  ;
] 0 0 ]
;  0  ;
6     3
 5;];4

It mainly uses the fact that ]; clears the stack.
Try it online

R, 9x9
No white space, no comments.
75%%99299
99%%99699
%%299%%41
%%699%%06
995999997
11%%999%%
99%%799%%
39719%%99
59519%%16

I guess this could be expanded to whatever size you want. I thought the modulo operator was most the most flexible of available operators, since it prevents values from being too large regardless of data size, and there's no effect from having really large numbers in between.
75%%9929999%%99699%%299%%41%%699%%0699599999711%%999%%99%%799%%39719%%9959519%%16   LTR-TTB  2
59519%%1639719%%9999%%799%%11%%999%%995999997%%699%%06%%299%%4199%%9969975%%99299   LTR-BTT  3
79%%9193559%%91999%%265%%75%%999%%1199999979999%%999%%26%%999%%99409%%9199167%%96   TTB-LTR  4
99167%%9699409%%9126%%999%%99%%999%%999999799%%999%%11%%265%%7559%%9199979%%91935   TTB-RTL  1
61%%9159599%%91793%%997%%99%%999%%1179999959960%%996%%14%%992%%99699%%9999299%%57   RTL-BTT  5
99299%%5799699%%9914%%992%%60%%996%%799999599%%999%%11%%997%%9999%%9179361%%91595   RTL-TTB  6
69%%7619919%%90499%%999%%62%%999%%9999799999911%%999%%57%%562%%99919%%9553919%%97   BTT-RTL  7
53919%%9799919%%9557%%562%%11%%999%%997999999%%999%%99%%999%%6219%%9049969%%76199   BTT-LTR  8

Ruby - 7x7
Not impressive either, same tactic as the Haskell answer.
p 1#2 p

3     7
#     #
4     8

p 5#6 p

This Programming Language, 5 * 9 = 45
1i;i2
2   2
+   +
i   i
;   ;
i   i
+   +
2   2
5i;i6

Which translates into this:
1i;i22   2+   +i   i;   ;i   i+   +2   25i;i6
5i;i62   2+   +i   i;   ;i   i+   +2   21i;i2
12+i;i+25i       i;       ;i       i22+i;i+26
22+i;i+26i       i;       ;i       i12+i;i+25
6i;i52   2+   +i   i;   ;i   i+   +2   22i;i1
2i;i12   2+   +i   i;   ;i   i+   +2   26i;i5
62+i;i+22i       i;       ;i       i52+i;i+21
52+i;i+21i       i;       ;i       i62+i;i+22

Since ; terminates the program, the above translates into this:
1i;   - outputs 1
5i;   - outputs 5
12+i; - outputs 3
22+i; - outputs 4
6i;   - outputs 6
2i;   - outputs 2
62+i; - outputs 8
52+i; - outputs 7

Explanation: any number from 0 to 9 pushes the corresponding digit onto the stack. + pops the top two values x and y off the stack and pushes x + y onto the stack. i outputs the stack as an integer.


text:
Sometimes I need a Lossless Screenshot Resizer
Sometimes I need to write more documentation than just comments in code. And sometimes, those explanations need screenshots. Sometimes the conditions to get such a screenshot are so weird that I ask a developer to take a screenshot for me. Sometimes the screenshot does not fit my specifications and I have to resize it so that it looks nicely.
As you can see, the circumstances for a need for the magic "Lossless Screenshot Resizer" are very unlikely. Anyway, for me it seems I need it every day. But it doesn't exist yet.
I've seen you here on PCG solve awesome graphical puzzles before, so I guess this one is rather boring for you...
Specification

The program takes a screenshot of a single window as input
The screenshot does not make use of glass effects or similar (so you don't need to deal with any background stuff that shines through)
The input file format is PNG (or any other lossless format so that you don't have to deal with compression artifacts)
The output file format is the same as the input file format
The program creates a screenshot of different size as output. Minimum requirement is shrinking in size.
The user shall specify the expected output size. If you can give hints about the minimum size your program can produce from the given input, that's helpful.
The output screenshot must not have less information if interpreted by a human. You shall not remove text or image content, but you shall remove areas with background only. See examples below.
If it is not possible to get the expected size, the program should indicate that and not simply crash or remove information without further notice.
If the program indicates the areas which will be removed for verification reasons, that should increase its popularity.
The program may need some other user input, e.g. to identify the starting point for optimization.

Rules
This is a popularity contest. The answer with most votes on 2015-03-08 gets accepted.
Examples
Windows XP screenshot. Original size: 1003x685 pixels.

Example areas (red: vertical, yellow: horizontal) that can be removed without losing any information (text or images). Note that the red bar isn't contiguous. This example doesn't indicate all possible pixels that could potentially be removed.

Losslessly resized: 783x424 pixels.

Windows 10 screenshot. Original size: 999x593 pixels.

Example areas which can be removed.

Losslessly resized screenshot: 689x320 pixels.
Note that it is ok that the title text ("Downloads") and "This folder is empty" are not centered any more. Of course, it would be nicer if it is centered, and if your solution provides that, it should become more popular.

Reminds me of Photoshop's "content aware scaling" feature.

What format is the input. Can we chose any standard image format?

@ThomasW said "I guess this one is rather boring". Not true. This is diabolical.

@CarpetPython it has 17 upvotes and no downvotes, so I guess not everyone shares your view.

Does it also need to upscale images? Re-size can be both up and down.

If not consider changing the name to "Sometimes I need a lossless screenshot cropper.

@steveverrill, I meant that it is is very good challenge. It is non-trivial.

@HEGX64: Usually I use PNG because it does not have compression artifacts. But any other format is fine as well.

@Rolfツ: I seldom need to upscale images. But indeed, for my blog I usually take 800x600 pixels, so I upscale some of them.

This question does not receive enough attention, the first answer has been upvoted because it was the only answer for a long time. The amount of votes is at the moment not enough to represent the popularity of the different answers. The question is how can we get more people to vote? Even I voted on a answer.

@Rolfツ: I agree. Also, your answer matches best the requirements like specifying the output size etc. I intend to place a bounty on the question, but wait until Friday, because developing solutions is not so trivial and give others the chance to benefit from the bounty as well.

@Rolfツ: I have started a bounty worth 2/3 of the reputation I have earned from this question so far. I hope that is fair enough.

Pff hope that it will do some good!

I have awarded the bounty to @Rolfツ, because that answer fulfills the requirements best. I would have liked to see more answers though, because the algorithms are very different. Thanks for anyone participating and upvoting the question so that the bounty was possible.

Python
the function delrows deletes all but one duplicate rows and returns the transposed image, applying it twice also deletes the columns and transposes it back. Additionally threshold controls how many pixels can differ for two lines to be still considered the same
from scipy import misc
from pylab import *

im7 = misc.imread('win7.png')
im8 = misc.imread('win8.png')

def delrows(im, threshold=0):
    d = diff(im, axis=0)
    mask = where(sum((d!=0), axis=(1,2))>threshold)
    return transpose(im[mask], (1,0,2))

imsave('crop7.png', delrows(delrows(im7)))
imsave('crop8.png', delrows(delrows(im8)))

Flipping the comparator in mask from > to <= will instead output the removed areas which are mostly blank space.

golfed (because why not)
Instead of comparing each pixel it only looks at the sum, as a side effect this also converts the screenshot to greyscale and has trouble with sum-preserving permutations, like the down-arrow in the address bar of the Win8 screenshot
from scipy import misc
from pylab import*
f=lambda M:M[where(diff(sum(M,1)))].T
imsave('out.png', f(f(misc.imread('in.png',1))),cmap='gray')

Wow, even golfed... (I hope you were aware that this is a popularity contest)

would you mind removing the golf score? This might leave people thinking this is code golf. Thank you.

@ThomasW. removed the score and moved it to the bottom, out of sight.

Java: Try lossless and fallback to content-aware
(Best lossless result so far!)

When I first looked at this question I thought this is not a puzzle or challenge just someone desperately in need of a program and it's code ;) But it is in my nature to solve vision problems so I could not stop my self from trying this challenge!
I came up with the following approach and combination of algorithms.
In pseudo-code it looks like this:
function crop(image, desired) {
    int sizeChange = 1;
    while(sizeChange != 0 and image.width > desired){

        Look for a repeating and connected set of lines (top to bottom) with a minimum of x lines
        Remove all the lines except for one
        sizeChange = image.width - newImage.width
        image = newImage;
    }
    if(image.width > desired){
        while(image.width > 2 and image.width > desired){
           Create a "pixel energy" map of the image
           Find the path from the top of the image to the bottom which "costs" the least amount of "energy"
           Remove the lowest cost path from the image
           image = newImage;
        }
    }
}

int desiredWidth = ?
int desiredHeight = ?
Image image = input;

crop(image, desiredWidth);
rotate(image, 90);
crop(image, desiredWidth);
rotate(image, -90);

Used techniques:

Intensity grayscale
Dilation
Equal column search and remove
Seam-carving
Sobel edge detection
Thresholding

The Program
The program can crop screenshots lossless but has an option to fallback to content-aware cropping which is not 100% lossless. The arguments of the program can be tweaked to achieve better results.
Note: The program can be improved in many ways (I don't have that much spare time!)
Arguments
File name = file
Desired width = number > 0
Desired height = number > 0
Min slice width = number > 1
Compare threshold = number > 0
Use content aware = boolean
Max content aware cycles = number >= 0

Code
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 * @author Rolf Smit
 * Share and adapt as you like, but don't forget to credit the author!
 */
public class MagicWindowCropper {

    public static void main(String[] args) {
        if(args.length != 7){
            throw new IllegalArgumentException("At least 7 arguments are required: (file, desiredWidth, desiredHeight, minSliceSize, sliceThreshold, forceRemove, maxForceRemove)!");
        }

        File file = new File(args[0]);

        int minSliceSize = Integer.parseInt(args[3]); //4;
        int desiredWidth = Integer.parseInt(args[1]); //400;
        int desiredHeight = Integer.parseInt(args[2]); //400;

        boolean forceRemove = Boolean.parseBoolean(args[5]); //true
        int maxForceRemove = Integer.parseInt(args[6]); //40

        MagicWindowCropper.MATCH_THRESHOLD = Integer.parseInt(args[4]); //3;

        try {

            BufferedImage result = ImageIO.read(file);

            System.out.println("Horizontal cropping");

            //Horizontal crop
            result = doDuplicateColumnsMagic(result, minSliceSize, desiredWidth);
            if (result.getWidth() != desiredWidth && forceRemove) {
                result = doSeamCarvingMagic(result, maxForceRemove, desiredWidth);
            }

            result = getRotatedBufferedImage(result, false);

            System.out.println("Vertical cropping");

            //Vertical crop
            result = doDuplicateColumnsMagic(result, minSliceSize, desiredHeight);
            if (result.getWidth() != desiredHeight && forceRemove) {
                result = doSeamCarvingMagic(result, maxForceRemove, desiredHeight);
            }

            result = getRotatedBufferedImage(result, true);

            showBufferedImage("Result", result);

            ImageIO.write(result, "png", getNewFileName(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static BufferedImage doSeamCarvingMagic(BufferedImage inputImage, int max, int desired) {
        System.out.println("Seam Carving magic:");

        int maxChange = Math.min(inputImage.getWidth() - desired, max);

        BufferedImage last = inputImage;
        int total = 0, change;
        do {
            int[][] energy = getPixelEnergyImage(last);
            BufferedImage out = removeLowestSeam(energy, last);

            change = last.getWidth() - out.getWidth();
            total += change;
            System.out.println("Carves removed: " + total);
            last = out;
        } while (change != 0 && total < maxChange);

        return last;
    }

    private static BufferedImage doDuplicateColumnsMagic(BufferedImage inputImage, int minSliceWidth, int desired) {
        System.out.println("Duplicate columns magic:");

        int maxChange = inputImage.getWidth() - desired;

        BufferedImage last = inputImage;
        int total = 0, change;
        do {
            BufferedImage out = removeDuplicateColumn(last, minSliceWidth, desired);

            change = last.getWidth() - out.getWidth();
            total += change;
            System.out.println("Columns removed: " + total);
            last = out;
        } while (change != 0 && total < maxChange);
        return last;
    }

    /*
     * Duplicate column methods
     */

    private static BufferedImage removeDuplicateColumn(BufferedImage inputImage, int minSliceWidth, int desiredWidth) {
        if (inputImage.getWidth() <= minSliceWidth) {
            throw new IllegalStateException("The image width is smaller than the minSliceWidth! What on earth are you trying to do?!");
        }

        int[] stamp = null;
        int sliceStart = -1, sliceEnd = -1;
        for (int x = 0; x < inputImage.getWidth() - minSliceWidth + 1; x++) {
            stamp = getHorizontalSliceStamp(inputImage, x, minSliceWidth);
            if (stamp != null) {
                sliceStart = x;
                sliceEnd = x + minSliceWidth - 1;
                break;
            }
        }

        if (stamp == null) {
            return inputImage;
        }

        BufferedImage out = deepCopyImage(inputImage);

        for (int x = sliceEnd + 1; x < inputImage.getWidth(); x++) {
            int[] row = getHorizontalSliceStamp(inputImage, x, 1);
            if (equalsRows(stamp, row)) {
                sliceEnd = x;
            } else {
                break;
            }
        }

        //Remove policy
        int canRemove = sliceEnd - (sliceStart + 1) + 1;
        int mayRemove = inputImage.getWidth() - desiredWidth;

        int dif = mayRemove - canRemove;
        if (dif < 0) {
            sliceEnd += dif;
        }

        int mustRemove = sliceEnd - (sliceStart + 1) + 1;
        if (mustRemove <= 0) {
            return out;
        }

        out = removeHorizontalRegion(out, sliceStart + 1, sliceEnd);
        out = removeLeft(out, out.getWidth() - mustRemove);
        return out;
    }

    private static BufferedImage removeHorizontalRegion(BufferedImage image, int startX, int endX) {
        int width = endX - startX + 1;

        if (endX + 1 > image.getWidth()) {
            endX = image.getWidth() - 1;
        }
        if (endX < startX) {
            throw new IllegalStateException("Invalid removal parameters! Wow this error message is genius!");
        }

        BufferedImage out = deepCopyImage(image);

        for (int x = endX + 1; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                out.setRGB(x - width, y, image.getRGB(x, y));
                out.setRGB(x, y, 0xFF000000);
            }
        }
        return out;
    }

    private static int[] getHorizontalSliceStamp(BufferedImage inputImage, int startX, int sliceWidth) {
        int[] initial = new int[inputImage.getHeight()];
        for (int y = 0; y < inputImage.getHeight(); y++) {
            initial[y] = inputImage.getRGB(startX, y);
        }
        if (sliceWidth == 1) {
            return initial;
        }
        for (int s = 1; s < sliceWidth; s++) {
            int[] row = new int[inputImage.getHeight()];
            for (int y = 0; y < inputImage.getHeight(); y++) {
                row[y] = inputImage.getRGB(startX + s, y);
            }

            if (!equalsRows(initial, row)) {
                return null;
            }
        }
        return initial;
    }

    private static int MATCH_THRESHOLD = 3;

    private static boolean equalsRows(int[] left, int[] right) {
        for (int i = 0; i < left.length; i++) {

            int rl = (left[i]) & 0xFF;
            int gl = (left[i] >> 8) & 0xFF;
            int bl = (left[i] >> 16) & 0xFF;

            int rr = (right[i]) & 0xFF;
            int gr = (right[i] >> 8) & 0xFF;
            int br = (right[i] >> 16) & 0xFF;

            if (Math.abs(rl - rr) > MATCH_THRESHOLD
                    || Math.abs(gl - gr) > MATCH_THRESHOLD
                    || Math.abs(bl - br) > MATCH_THRESHOLD) {
                return false;
            }
        }
        return true;
    }

    /*
     * Seam carving methods
     */

    private static BufferedImage removeLowestSeam(int[][] input, BufferedImage image) {
        int lowestValue = Integer.MAX_VALUE; //Integer overflow possible when image height grows!
        int lowestValueX = -1;

        // Here be dragons
        for (int x = 1; x < input.length - 1; x++) {
            int seamX = x;
            int value = input[x][0];
            for (int y = 1; y < input[x].length; y++) {
                if (seamX < 1) {
                    int top = input[seamX][y];
                    int right = input[seamX + 1][y];
                    if (top <= right) {
                        value += top;
                    } else {
                        seamX++;
                        value += right;
                    }
                } else if (seamX > input.length - 2) {
                    int top = input[seamX][y];
                    int left = input[seamX - 1][y];
                    if (top <= left) {
                        value += top;
                    } else {
                        seamX--;
                        value += left;
                    }
                } else {
                    int left = input[seamX - 1][y];
                    int top = input[seamX][y];
                    int right = input[seamX + 1][y];

                    if (top <= left && top <= right) {
                        value += top;
                    } else if (left <= top && left <= right) {
                        seamX--;
                        value += left;
                    } else {
                        seamX++;
                        value += right;
                    }
                }
            }
            if (value < lowestValue) {
                lowestValue = value;
                lowestValueX = x;
            }
        }

        BufferedImage out = deepCopyImage(image);

        int seamX = lowestValueX;
        shiftRow(out, seamX, 0);
        for (int y = 1; y < input[seamX].length; y++) {
            if (seamX < 1) {
                int top = input[seamX][y];
                int right = input[seamX + 1][y];
                if (top <= right) {
                    shiftRow(out, seamX, y);
                } else {
                    seamX++;
                    shiftRow(out, seamX, y);
                }
            } else if (seamX > input.length - 2) {
                int top = input[seamX][y];
                int left = input[seamX - 1][y];
                if (top <= left) {
                    shiftRow(out, seamX, y);
                } else {
                    seamX--;
                    shiftRow(out, seamX, y);
                }
            } else {
                int left = input[seamX - 1][y];
                int top = input[seamX][y];
                int right = input[seamX + 1][y];

                if (top <= left && top <= right) {
                    shiftRow(out, seamX, y);
                } else if (left <= top && left <= right) {
                    seamX--;
                    shiftRow(out, seamX, y);
                } else {
                    seamX++;
                    shiftRow(out, seamX, y);
                }
            }
        }

        return removeLeft(out, out.getWidth() - 1);
    }

    private static void shiftRow(BufferedImage image, int startX, int y) {
        for (int x = startX; x < image.getWidth() - 1; x++) {
            image.setRGB(x, y, image.getRGB(x + 1, y));
        }
    }

    private static int[][] getPixelEnergyImage(BufferedImage image) {

        // Convert Image to gray scale using the luminosity method and add extra
        // edges for the Sobel filter
        int[][] grayScale = new int[image.getWidth() + 2][image.getHeight() + 2];
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = (rgb & 0xFF);
                int luminosity = (int) (0.21 * r + 0.72 * g + 0.07 * b);
                grayScale[x + 1][y + 1] = luminosity;
            }
        }

        // Sobel edge detection
        final double[] kernelHorizontalEdges = new double[] { 1, 2, 1, 0, 0, 0, -1, -2, -1 };
        final double[] kernelVerticalEdges = new double[] { 1, 0, -1, 2, 0, -2, 1, 0, -1 };

        int[][] energyImage = new int[image.getWidth()][image.getHeight()];

        for (int x = 1; x < image.getWidth() + 1; x++) {
            for (int y = 1; y < image.getHeight() + 1; y++) {

                int k = 0;
                double horizontal = 0;
                for (int ky = -1; ky < 2; ky++) {
                    for (int kx = -1; kx < 2; kx++) {
                        horizontal += ((double) grayScale[x + kx][y + ky] * kernelHorizontalEdges[k]);
                        k++;
                    }
                }
                double vertical = 0;
                k = 0;
                for (int ky = -1; ky < 2; ky++) {
                    for (int kx = -1; kx < 2; kx++) {
                        vertical += ((double) grayScale[x + kx][y + ky] * kernelVerticalEdges[k]);
                        k++;
                    }
                }

                if (Math.sqrt(horizontal * horizontal + vertical * vertical) > 127) {
                    energyImage[x - 1][y - 1] = 255;
                } else {
                    energyImage[x - 1][y - 1] = 0;
                }
            }
        }

        //Dilate the edge detected image a few times for better seaming results
        //Current value is just 1...
        for (int i = 0; i < 1; i++) {
            dilateImage(energyImage);
        }
        return energyImage;
    }

    private static void dilateImage(int[][] image) {
        for (int x = 0; x < image.length; x++) {
            for (int y = 0; y < image[x].length; y++) {
                if (image[x][y] == 255) {
                    if (x > 0 && image[x - 1][y] == 0) {
                        image[x - 1][y] = 2; //Note: 2 is just a placeholder value
                    }
                    if (y > 0 && image[x][y - 1] == 0) {
                        image[x][y - 1] = 2;
                    }
                    if (x + 1 < image.length && image[x + 1][y] == 0) {
                        image[x + 1][y] = 2;
                    }
                    if (y + 1 < image[x].length && image[x][y + 1] == 0) {
                        image[x][y + 1] = 2;
                    }
                }
            }
        }
        for (int x = 0; x < image.length; x++) {
            for (int y = 0; y < image[x].length; y++) {
                if (image[x][y] == 2) {
                    image[x][y] = 255;
                }
            }
        }
    }

    /*
     * Utilities
     */

    private static void showBufferedImage(String windowTitle, BufferedImage image) {
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)), windowTitle, JOptionPane.PLAIN_MESSAGE, null);
    }

    private static BufferedImage deepCopyImage(BufferedImage input) {
        ColorModel cm = input.getColorModel();
        return new BufferedImage(cm, input.copyData(null), cm.isAlphaPremultiplied(), null);
    }

    private static final BufferedImage getRotatedBufferedImage(BufferedImage img, boolean back) {
        double oldW = img.getWidth(), oldH = img.getHeight();
        double newW = img.getHeight(), newH = img.getWidth();

        BufferedImage out = new BufferedImage((int) newW, (int) newH, img.getType());
        Graphics2D g = out.createGraphics();
        g.translate((newW - oldW) / 2.0, (newH - oldH) / 2.0);
        g.rotate(Math.toRadians(back ? -90 : 90), oldW / 2.0, oldH / 2.0);
        g.drawRenderedImage(img, null);
        g.dispose();
        return out;
    }

    private static BufferedImage removeLeft(BufferedImage image, int startX) {
        int removeWidth = image.getWidth() - startX;

        BufferedImage out = new BufferedImage(image.getWidth() - removeWidth,
                image.getHeight(), image.getType());

        for (int x = 0; x < startX; x++) {
            for (int y = 0; y < out.getHeight(); y++) {
                out.setRGB(x, y, image.getRGB(x, y));
            }
        }
        return out;
    }

    private static File getNewFileName(File in) {
        String name = in.getName();
        int i = name.lastIndexOf(".");
        if (i != -1) {
            String ext = name.substring(i);
            String n = name.substring(0, i);
            return new File(in.getParentFile(), n + "-cropped" + ext);
        } else {
            return new File(in.getParentFile(), name + "-cropped");
        }
    }
}

Results

XP screenshot lossless without desired size (Max lossless compression)
Arguments: "image.png" 1 1 5 10 false 0
Result: 836 x 323

XP screenshot to 800x600
Arguments: "image.png" 800 600 6 10 true 60
Result: 800 x 600
The lossless algorithm removes about 155 horizontal lines than the algorithm falls back to content-aware removal therefor some artifacts can be seen.

Windows 10 screenshot to 700x300
Arguments: "image.png" 700 300 6 10 true 60
Result: 700 x 300
The lossless algorithm removes 270 horizontal lines than the algorithm falls back to content-aware removal which removes another 29. Vertical only the lossless algorithm is used.

Windows 10 screenshot content-aware to 400x200 (test)
Arguments: "image.png" 400 200 5 10 true 600
Result: 400 x 200
This was a test to see how the resulting image would look after severe use of the content-aware feature. The result is heavily damaged but not unrecognizable.

The first output is not completely trimmed. So much can me truncated from right

That's because the arguments (of my program) say that it should not optimize it any further than 800 pixels :)

Since this popcon , you should probably show the best results :)

My program does initial the same as the other answer but it also has a content-aware function for even further down-scaling. It also has the option to crop to a desired width and height (see question).

C#, algorithm like I would do it manually
This is my first image processing program and it took a while to implement with all that LockBits stuff etc. But I wanted it to be fast (using Parallel.For) to get an almost instant feedback.
Basically my algorithm is based on observations on how I remove pixels manually from a screenshot:

I am starting from the right edge, because chances are higher that unused pixels are there.
I define a threshold for edge detection in order to capture the system buttons correctly. For the Windows 10 screenshot, a threshold of 48 pixels works well.
After the edge is detected (marked in red color below), I am looking for pixels of the same color. I take the minimum number of pixels found and apply it to all rows (marked violet).
Then I start over again with edge detection (marked red), pixels of the same color (marked blue, then green, then yellow) and so forth

At the moment I do it horizontally only. The vertical result can use the same algorithm and operate on a 90° rotated image, so in theory it's possible.
Results
This is a screenshot of my application with detected regions:

And this is the result for the Windows 10 screenshot and 48 pixels threshold. The output is 681 pixels wide. Unfortunately it's not perfect (see "Search Downloads" and some of the vertical column bars).

And another one with 64 pixels threshold (567 pixels wide). This looks even better.

Overall result applying rotation to crop from all bottom as well (567x304 pixels).

For Windows XP, I needed to change the code a bit since the pixels are not exactly equal. I am applying a similarity threshold of 8 (difference in RGB value). Note some artifacts in the columns.

Code
Well, my first attempt on image processing. Doesn't look very good, does it? This only lists the core algorithm, not the UI and not the 90° rotation.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace LosslessScreenshotResizer.BL
{
    internal class PixelAreaSearcher
    {
        private readonly Bitmap _originalImage;

        private readonly int _edgeThreshold;
        readonly Color _edgeColor = Color.FromArgb(128, 255, 0, 0);
        readonly Color[] _iterationIndicatorColors =
        {
            Color.FromArgb(128, 0, 0, 255),
            Color.FromArgb(128, 0, 255, 255),
            Color.FromArgb(128, 0, 255, 0),
            Color.FromArgb(128, 255, 255, 0)
        };

        public PixelAreaSearcher(Bitmap originalImage, int edgeThreshold)
        {
            _originalImage = originalImage;
            _edgeThreshold = edgeThreshold;

            // cache width and height. Also need to do that because of some GDI exceptions during LockBits
            _imageWidth = _originalImage.Width;
            _imageHeight = _originalImage.Height;
        }

        public Bitmap SearchHorizontal()
        {
            return Search();
        }

        /// <summary>
        /// Find areas of pixels to keep and to remove. You can get that information via <see cref="PixelAreas"/>.
        /// The result of this operation is a bitmap of the original picture with an overlay of the areas found.
        /// </summary>
        /// <returns></returns>
        private unsafe Bitmap Search()
        {
            // FastBitmap is a wrapper around Bitmap with LockBits enabled for fast operation.
            var input = new FastBitmap(_originalImage);
            // transparent overlay
            var overlay = new FastBitmap(_originalImage.Width, _originalImage.Height);

            _pixelAreas = new List<PixelArea>(); // save the raw data for later so that the image can be cropped
            int startCoordinate = _imageWidth - 1; // start at the right edge
            int iteration = 0; // remember the iteration to apply different colors
            int minimum;
            do
            {
                var indicatorColor = GetIterationColor(iteration);

                // Detect the edge which is not removable
                var edgeStartCoordinates = new PixelArea(_imageHeight) {AreaType = AreaType.Keep};
                Parallel.For(0, _imageHeight, y =>
                {
                    edgeStartCoordinates[y] = DetectEdge(input, y, overlay, _edgeColor, startCoordinate);
                }
                    );
                _pixelAreas.Add(edgeStartCoordinates);

                // Calculate how many pixels can theoretically be removed per line
                var removable = new PixelArea(_imageHeight) {AreaType = AreaType.Dummy};
                Parallel.For(0, _imageHeight, y =>
                {
                    removable[y] = CountRemovablePixels(input, y, edgeStartCoordinates[y]);
                }
                    );

                // Calculate the practical limit
                // We can only remove the same amount of pixels per line, otherwise we get a non-rectangular image
                minimum = removable.Minimum;
                Debug.WriteLine("Can remove {0} pixels", minimum);

                // Apply the practical limit: calculate the start coordinates of removable areas
                var removeStartCoordinates = new PixelArea(_imageHeight) { AreaType = AreaType.Remove };
                removeStartCoordinates.Width = minimum;
                for (int y = 0; y < _imageHeight; y++) removeStartCoordinates[y] = edgeStartCoordinates[y] - minimum;
                _pixelAreas.Add(removeStartCoordinates);

                // Paint the practical limit onto the overlay for demo purposes
                Parallel.For(0, _imageHeight, y =>
                {
                    PaintRemovableArea(y, overlay, indicatorColor, minimum, removeStartCoordinates[y]);
                }
                    );

                // Move the left edge before starting over
                startCoordinate = removeStartCoordinates.Minimum;
                var remaining = new PixelArea(_imageHeight) { AreaType = AreaType.Keep };
                for (int y = 0; y < _imageHeight; y++) remaining[y] = startCoordinate;
                _pixelAreas.Add(remaining);

                iteration++;
            } while (minimum > 1);

            input.GetBitmap(); // TODO HACK: release Lockbits on the original image
            return overlay.GetBitmap();
        }

        private Color GetIterationColor(int iteration)
        {
            return _iterationIndicatorColors[iteration%_iterationIndicatorColors.Count()];
        }

        /// <summary>
        /// Find a minimum number of contiguous pixels from the right side of the image. Everything behind that is an edge.
        /// </summary>
        /// <param name="input">Input image to get pixel data from</param>
        /// <param name="y">The row to be analyzed</param>
        /// <param name="output">Output overlay image to draw the edge on</param>
        /// <param name="edgeColor">Color for drawing the edge</param>
        /// <param name="startCoordinate">Start coordinate, defining the maximum X</param>
        /// <returns>X coordinate where the edge starts</returns>
        private int DetectEdge(FastBitmap input, int y, FastBitmap output, Color edgeColor, int startCoordinate)
        {
            var repeatCount = 0;
            var lastColor = Color.DodgerBlue;
            int x;

            for (x = startCoordinate; x >= 0; x--)
            {
                var currentColor = input.GetPixel(x, y);
                if (almostEquals(lastColor,currentColor))
                {
                    repeatCount++;
                }
                else
                {
                    lastColor = currentColor;
                    repeatCount = 0;
                    for (int i = x; i < startCoordinate; i++)
                    {
                        output.SetPixel(i,y,edgeColor);
                    }
                }

                if (repeatCount > _edgeThreshold)
                {
                    return x + _edgeThreshold;
                }
            }
            return repeatCount;
        }

        /// <summary>
        /// Counts the number of contiguous pixels in a row, starting on the right and going to the left
        /// </summary>
        /// <param name="input">Input image to get pixels from</param>
        /// <param name="y">The current row</param>
        /// <param name="startingCoordinate">X coordinate to start from</param>
        /// <returns>Number of equal pixels found</returns>
        private int CountRemovablePixels(FastBitmap input, int y, int startingCoordinate)
        {
            var lastColor = input.GetPixel(startingCoordinate, y);
            for (int x=startingCoordinate; x >= 0; x--)
            {
                var currentColor = input.GetPixel(x, y);
                if (!almostEquals(currentColor,lastColor))
                {
                    return startingCoordinate-x;
                }
            }
            return startingCoordinate;
        }

        /// <summary>
        /// Calculates color equality.
        /// Workaround for Windows XP screenshots which do not have 100% equal pixels.
        /// </summary>
        /// <returns>True if the RBG value is similar (maximum R+G+B difference is 8)</returns>
        private bool almostEquals(Color c1, Color c2)
        {
            int r = c1.R;
            int g = c1.G;
            int b = c1.B;
            int diff = (Math.Abs(r - c2.R) + Math.Abs(g - c2.G) + Math.Abs(b - c2.B));
            return (diff < 8) ;
        }

        /// <summary>
        /// Paint pixels that can be removed, starting at the X coordinate and painting to the right
        /// </summary>
        /// <param name="y">The current row</param>
        /// <param name="output">Overlay output image to draw on</param>
        /// <param name="removableColor">Color to use for drawing</param>
        /// <param name="width">Number of pixels that can be removed</param>
        /// <param name="start">Starting coordinate to begin drawing</param>
        private void PaintRemovableArea(int y, FastBitmap output, Color removableColor, int width, int start)
        {
            for(int i=start;i<start+width;i++)
            {
                output.SetPixel(i, y, removableColor);
            }
        }

        private readonly int _imageHeight;
        private readonly int _imageWidth;
        private List<PixelArea> _pixelAreas;

        public List<PixelArea> PixelAreas
        {
            get { return _pixelAreas; }
        }
    }
}

+1 Interesting approach, I like it! It would be fun if some of the algorithms posted here, like mine and yours, would be combined to achieve optimal results. Edit: C# is a monster to read, I'm not always sure if something is a field or a function/getter with logic.

Haskell, using naive removal of duplicate sequential lines
Unfortunately, this module only provides a function with the very generic type Eq a => [[a]] -> [[a]], since I have no idea how to edit image files in Haskell, however, I'm certain it's possible to tranform a PNG image to a [[Color]] value and I'd imagine instance Eq Color to be easily definable.
The function in question is resizeL.
Code:
import Data.List

nubSequential []    = []
nubSequential (a:b) = a : g a b where
 g x (h:t)  | x == h =     g x t
            | x /= h = h : g h t
 g x []     = []

resizeL     = nubSequential . transpose . nubSequential . transpose

Explanation:
Note: a : b means element a prefixed to list of type of a, resulting in a list. This is the fundamental construction of lists. [] denotes the empty list.
Note: a :: b means a is of type b. For example, if a :: k, then (a : []) :: [k], where [x] denotes a list containing things of type x.
This means that (:) itself, without any arguments, :: a -> [a] -> [a]. The -> denotes a function from something to something.
The import Data.List simply gets some work some other people did for us and lets us use their functions without rewriting them.
First, define a function nubSequential :: Eq a => [a] -> [a].
This function removes subsequent elements of a list that are identical.
So, nubSequential [1, 2, 2, 3] === [1, 2, 3]. We will now abbreviate this function as nS.
If nS is applied to an empty list, nothing can be done, and we simple return an empty list.
If nS is applied to a list with contents, then actual processing can be done. For this, we need a second function, here in a where-clause, to use recursion, as our nS doesn't keep track of an element to compare to.
We name this function g. It works by comparing its first argument to the head of the list it's been given, and discarding the head if they match and calling itself on the tail with the old first argument. If they don't, it appends the head onto the tail, passed through itself with the head as the new first argument.
To use g, we give it the head of the argument of nS and the tail as its two arguments.
nS is now of type Eq a => [a] -> [a], taking a list and returning a list. It requires that we can check for equality between the elements as this is done in the function definition.
Then, we compose the functions nS and transpose using the (.) operator.
Composing functions means the following: (f . g) x = f (g (x)).
In our example, transpose rotates a table 90°, nS removes all sequential equal elements of the list, in this case other lists (that's what a table is), transpose rotates it back and nS again removes sequential equal elements. This is essentially removing subsequent duplicate rows an columns.
This is possible because if a is checkable for equality (instance Eq a), then [a] is, too.
In short: instance Eq a => Eq [a]

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Finding Programs in the Primes
Let's assign the numbers 0 through 94 to the 95 printable ASCII characters:
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Space is 0, ! is 1, and so on until ~ is 94. We'll also assign 95 to tab (\t) and 96 to newline (\n).
Now consider the infinite string whose Nth character is the character above that the Nth prime number, modulo 97, has been assigned to. We'll call this string S.
For example, the first prime number is 2, and 2 mod 97 is 2, and 2 is assigned to ", so the first character of S is ". Similarly, the 30th prime number is 113, and 113 mod 97 is 16, and 16 is assigned to 0, so the 30th character of S is 0.
The first 1000 characters of S are as follows:
"#%'+-137=?EIKOU[]cgiosy $&*,0>BHJTV\bflrt~
#%1=ACGMOY_ekmswy"046:HNXZ^dlrx|!)-5?AKMSW]eiko{"&.28DFX^hntv|%+139?CEQ[]agmo{  $,6>HPV\`hnrz~+5ACMOSU_mqsw$(*.BFNX`djp~!'-5;GKQS]_eoq{}"48:>DJRX^tv
'17=EQU[aciu    026<>DHJNZ\b#)/7ISaegkqy}   $0:<@BFLXdlx~!'/3;?MQWY]ceku(.24LPR\hjt|!'-?EIKWamu$28<>BDNZ`fxz)+AGOUY[_gmwy"0:@LNRT^jl|~#')3;Meiow&(,4DFJRX^bnp%+-37=KQUW]agsy    ,06BJPTn
)15;=CYegw  ".<FHLTZ`dfjpx|~#-/9AES]ikquw&48>FLPbjtz
'1=KOU[]y{$,0>BJV\hlr%/1A[_amsw"(04<RTXZf!#)/59?AMQ]_ik{},2FV^bdhj
'39CEIOQWacoy{$28<BJPVfrtx%+/7AIOUkqs}*.4FHR`dfp~!);?EGKQS_cw,8:>DJLRhjp
%139EUW[aosu&>HNPZ\fhrxz#%/5=[egqy  (:@LXZlrv|!35?MSWY]uw"(8@FL^nptz|!'17COacim &>BDHNP\`n+5;GU[eqsw}$*46:HNTX^`jl|'/AEKWY_ek&,:>FPXdvz|
7CIK[agu    ,0NTZ`hnrt
%)+1GMOSegkwy   "<BHLT^~-/59;?AKY_cku{.24:X\dntz!'37=?EIOQ[]ms&*6D`fz~/7=AGU[akmw"*46@HT^vx|#)-5GQW]_eo{}&,28@FPVX^djt|39OQcgoy6>PTV`fhnr#+7IY_ams} (*0:HLdfvx!#-AEGKScioq},48>\^hjptz
'-1=CKW[iu  6<HNPfn
)/=ACIS[aek(6@BNXZjl~5GM]ouw(,24>FPV\dhnpz|'+179EIWims&*28<DHV\`nz~
=AY_eq}*046:LR^

Stack Exchange turns tabs into spaces, so here's a PasteBin with the tabs intact.
Challenge
Find a substring of S that is a valid program in your language of choice that outputs the first M prime numbers, one per line, in order, for some positive integer M.
For example, 2 is a substring of S (it occurs in multiple places but any will do), and 2 is a valid CJam program whose output is
2

which is the first M = 1 prime numbers, one per line, in order.
Similarly, the string 2N3N5 may be a substring of S somewhere, and 2N3N5 is a valid CJam program that outputs
2
3
5

which is the first M = 3 prime numbers, one per line, in order.
Scoring
The submission with the highest M wins. Tie breaker goes to the submission posted first.
Details

There should be no additional output besides the single primes on each line, except for an optional trailing newline after the last line. There is no input.

The substring may be any length as long as it's finite.

The substring may occur anywhere within S. (And S may contain it in multiple places.)

The program must be a full-fledged program. You may not assume it is run in a REPL environment.

The program must run and terminate in a finite amount of time without errors.

"Newline" may be interpreted as any common newline representation necessary for your system/interpreter/etc. Just treat it as one character.

You must give the index of S where your substring starts, as well as the length of the substring if not the substring itself. You may not only show that the substring must exist.
Related: Looking for programs in a huge Boggle board

Can you give the code to produce that big string upto any number of characters ? (I suppose you already have one)

If there are 95 printable ASCII characters then why are you doing modulo 97? Ah nevermind, you also use tab and newline.

Considering that 0 mod 97 can only occur once, the lack of space really hurts...

@Sp3000 Shoot, that didn't occur to me. :/

Lenguage, M = ∞
All of the programs start at the beginning of the string. The following poorly written Python program calculates how many characters are needed for a given M.
def program_length(n):
    PLUS, MINUS, DOT = '000', '001', '100'
    i = 1
    s = ''
    while n > 0:
        i += 1
        if all(i%f for f in range(2,i)):
            s += str(i) + '\n'
            n -= 1
    out = '110111'
    ch = 0
    for c in s:
        dif = ord(c) - ch
        if dif > 0: out += PLUS * dif
        else: out += MINUS * -dif
        out += DOT
        ch = ord(c)
    return int(out, 2)

For example, for M = 5, the program is the first 2458595061728800486379873255763299470031450306332287344758771914371767127738856987726323081746207100511846413417615836995266879023298634729597739072625027450872641123623948113460334798483696686473335593598924642330139401455349473945729379748942060643508071340354553446024108199659348217846094898762753583206697609445347611002385321978831186831089882700897165873209445730704069057276108988230177356 characters.

If in doubt, there's a BF variant that'll do it for you.

It's funny how Lenguage was inspired by another challenge of mine. It's like I'm bringing about my own downfall.

CJam, M = 2
Short and sweet:
2NZ

This sequence starts at position 54398, using 1-indexing of the string.  You can test it online here.
I attempted to search for a few possible variations, but this was the first solution I found.
I am currently trying to find an M = 3 version, but I don't expect to find one within a reasonable period of time.  If the sequence is uniformly random (an approximation), then the starting index for a length 5 sequence could be on the order of 10^9.

Verified: 1e6{mp},97f%' f+"2NZ"# link (takes a while :p)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Noel Constant's idiotically simple investment system

Noel Constant did it without genius and without spies.
His system was so idiotically simple that some people can't understand it, no
  matter how often is is explained. The people who can't understand it are people
  who have to believe, for their own peace of mind, that tremendous wealth can be
  produced only by thremendous cleverness.
This was Noel Constant's system:
He took the Gideon Bible that was in his room, and he started with the first
  sentence in Genesis.
The first sentence in Genesis, as some people may know, is: "In the beginning
  God created the heaven and the earth." Noel Constant wrote the sentence in
  capital letters, put periods between the letters, divided the letters into
  pairs, rendering the sentence as follows: "I.N., T.H., E.B., E.G., I.N. N.I.,
  N.G., G.O., D.C., R.E., A.T., E.D., T.H., E.H., E.A., V.E., N.A., N.D., T.H.,
  E.E., A.R., T.H."
And then he looked for corporations with those initials, and bought shares in
  them. His rule at the beginning was that he would own shares in only one
  corporation at a time, would invest his whole nest-egg in it, and would sell the
  instant the value of his shares had doubled.

–Kurt Vonnegut, Sirens of Titan
The investor Noel Constant is getting tired of using his system manually. He
needs the power of computers to pick the companies to invest in.
Noel Constant is willing to learn how to execute a command line script or a
function in the language of your choice. He will provide a single string of
input. He won't bother removing any whitespace, punctuation, or change case for the input string. He doesn't like that kind of work.
In return he expects to see a list of companies he can invest in, produced
according to his idiotically simple system. He wants to see each company on its
own line with the initials in brackets. If there isn't a company with the
initials needed he wants to see three dots (...).
International Nitrate (IN)
Throwbridge Helicopter (TH)
Electra Bakeries (EB)
Eternity Granite (EG)
... (IN)

His company, Magnum Opus, provided a list of company names and their initials
for you: https://gist.github.com/britishtea/2f57710a114cfd79616d.
As you may have guessed, Noel Constant doesn't like reading, so he'll want the
shortest program or function possible.
EDIT
To clarify, the input to the function or program is string (with punctuation and whitespace, case unaltered). An example of such a string is "In the beginning
God created the heaven and the earth." The list of company names and initials is not an input source, it should be read some other way (from disk for example).
The output is a list in the above format. I forgot to mention in the original challenge that the order the company names appear in shouldn't be altered, i.e. if you read the initials in the output from top to bottom it renders the original input (stripped of punctuation and whitespace).
This is no longer a requirement, but if your function or program satisfies this condition, there is a 0.9 bonus (# characters * 0.9) in it for you.

Do we have to consider only the first sentence of the Gideon Bible ?

Do we have to hardcode the companies' names? If not you should specify that the program has to either 1(Download the names from your github page. 2(Assume the names are in a nearby file with such and such name.

@Optimizer In the book, Noel Constant gets a lot further than the first sentence, therefore the program or function should be able to give output company names for (at least) the full bible. I think this invalidates your current solution, I'm sorry about that.

Then you should make your question self sufficient and proper. Right now its not clear at all.

And do you just assume that we put all of the bible in our code ? Is this even kolmogorov-complexity ?

No, the challenge states that "[Noel Constant] will provide a single string of input" as a function argument or as input for the program :)

@TheBestOne The list of company names and their initials is provided for you. You can read it any way you like. Hard-coding it isn't required, but is of course allowed.

Do you only want one stock that is an exact match or all stocks that contain that substring? I'm assuming the former from the example, but the problem description might give a different understanding.

@kris013 Only the company name that has the initials in front of its name in the provided list. Could you tell me where the confusion lies so I can alter the challenge?

Unix tools, 111 * 0.9
(Not counting downloading and parsing the Bible)
$ curl -s https://www.gutenberg.org/cache/epub/10/pg10.txt|grep '^[0-9]:'|cut -d' ' -f2-|sed 's/[^a-z]//gi'|tr -d \\n|fold -w2|xargs -n1 sh -c 'grep -i ^$0 symbols.txt'|sed -r 's/(..) (.*)/\2 \(\1\)/'
Zylog Systems Ltd (IN)
Zynga Inc - Cl A (TH)
Zwahlen & Mayr Sa-br (EB)
Surpapelcorp Sa (EG)
Zylog Systems Ltd (IN)
Nisource Inc. (NI)
Novagold Resources Inc. (NG)
Zealand Pharma A/s (DC)
Everest Re Group, Ltd. (RE)
Atlantic Power Corporation (AT)
^C

I am not a professional investor but I think that the more times a company is mentioned in the Bible the more successful it will be, so I would invest in these:
  10027 th - Zynga Inc - Cl A
   9026 he - Hawaiian Electric Industries, Inc.
   4748 nd - *
   3681 an - Autonation, Inc.
   3150 ha - Hawaiian Holdings, Inc.
   3109 er - *
   2925 re - Everest Re Group, Ltd.
   2829 in - Zylog Systems Ltd
   2665 nt - *
   2519 es - *

(Future founders, consider creating a company with stock symbols I marked with *, they are not yet taken)

Mathematica, 186
Grid[{If[Length[a=FinancialData[#,"Lookup"]]>0,FinancialData[a[[1]],"Company"],"..."],#}&/@StringJoin/@Partition[Select[Characters[ToUpperCase@#],IntersectingQ[{#},CharacterRange["A","Z"]]&],2]]&

The output looks like this:
This actually doesn't quite work, but I think it's pretty neat that Mathematica can do this. For some reason, though, it has trouble finding its own stocks. For example, it finds "NYSE:IN" but then says it's not a known entity:

Still, that's about as far as I think I'll go with it, unless someone knows why it's confused about the NYSE stocks. Feel free to expand or golf.

Python 3, 174 * 0.9 = 156.6 bytes
Rereading the rules, the company names can be in a file. This works with a file named w (No file extension) in the same format as the github.gist in the question. Takes input via stdin and outputs in the format company name (SC) or ... (SC) where SC is the stock code.
a={l[:2]:l[3:-1]for l in open("w").readlines()}
s="".join(c.upper()for c in input()if c.isalpha())
for i in(s[c:c+2]for c in range(0,len(s),2)):print(a.get(i,"..."),"(%s)"%i)

Old version, 248 241 238 * 0.9 = 214.2 bytes
This is the same as above, except it gets the stock codes from the internet.
from urllib.request import*
a={l[:2]:l[3:]for l in urlopen("http://goo.gl/lZVoIE").read().decode().split("\n")}
s="".join(c.upper()for c in input()if c.isalpha())
for i in(s[c:c+2]for c in range(0,len(s),2)):print(a.get(i,"..."),"(%s)"%i)

The goo.gl link is the link to the gist shortened.


text:
Generate a Davenport-Schinzel Sequence
Background
A Davenport-Schinzel sequence has two positive integer parameters d and n. We will denote the set of all Davenport-Schinzel sequences for given parameters by DS(d,n).
Consider all sequences of the natural numbers 1 to n, inclusive, which satisfy:

No two consecutive numbers in the sequence are identical.
There is no subsequence (not necessarily consecutive) of length greater than d, which  alternates between two different numbers.

Let L denote the maximum length of such a sequence (given d and n). Then, DS(d,n) is the set of all such sequences with length L.
Some examples might help. Let d = 4, n = 3. The longest possible sequences with these constraints have L = 8. So the following is a member of DS(4,3):
[1, 2, 1, 3, 1, 3, 2, 3]

There are no consecutive identical numbers and there are alternating subsequences of length 4, but not longer ones:
 1  2  1           2
 1  2        1     2
 1        3  1  3
 1        3  1        3
    2     3        2  3
    2           3  2  3
       1  3  1  3
       1  3  1        3

The following examples are not in DS(4,3):
[1, 2, 2, 3, 1, 3, 2, 3]  # Two consecutive 2's.
[1, 2, 1, 3, 1, 3, 2, 1]  # Contains alternating subsequences of length 5.
[1, 2, 1, 3, 1, 3, 2]     # Longer valid sequences for d = 4, n = 3 exist.

For further information see MathWorld and OEIS and the references they list.
The Challenge
Given two positive integers, n and d, generate any Davenport-Schinzel sequence in DS(d,n). Note that these are not generally unique, so output any single valid result.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and returning the result from the function or printing it to STDOUT (or closest alternative).
You may use any convenient, unambiguous string or list format for output.
This is code golf, so the shortest submission (in bytes) wins.
Sequence Lengths
Since the sequences are not unique, there is not much use for individual examples in this challenge. However, the two general validity problems are fairly easy to check for any output, so the main question is just whether the sequence has the right length (or there's a longer valid sequence). Therefore, here is a list of the known1 L for given d and n:
 \
 d\n 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
   \-----------------------------------------------------------
 1 | 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
 2 | 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
 3 | 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 4 | 1  4  8 12 17 22 27 32 37 42 47 53 58 64 69 75 81 86 92 98
 5 | 1  5 10 16 22 29 ...
 6 | 1  6 14 23 34 ...
 7 | 1  7 16 28 41 ...
 8 | 1  8 20 35 53 ...
 9 | 1  9 22 40 61 ...
10 | 1 10 26 47 73 ...

You must not hardcode any information from this table into your submission.
1 This table is from 1994, so there may have been more progress since then, but I doubt that any submission will be able to handle even the larger entries in this table in a reasonable amount of time.

Python 2: 172
from itertools import*
d,n=input();S=[[1]]
for s in S:
 for v in range(1,n+1):
  if(v!=s[-1])*all(w[2:]!=w[:-2]for w in combinations(s+[v],d+1)):S.append(s+[v])
print S[-1]

Input is simply in the format 4, 3.
I iteratively create all sequences, which start with 1 and satisfy the two properties, and store them in S. Since I create them in sorted order (sorted by length [and by values]), the last entry has to be a Davenport-Schinzel-sequence. Uses the nice fact, that you can iterate over a list while appending to it.

If you're already using python2, you can save a byte by combining (what I assume to be two spaces) into a tab. Correct me if I'm wrong.


text:
Rosetta Stone Code Golf Challenge: Print Certain Numbers; all snippets must be same length
Rosetta Stone Code Challenges are challenges where you must complete the task in as many languages as possible.
The Challenge
You will be given two numbers, n and s, in a list as input. The n will be a number you have to count up to. n will be any number from 2 to 10000. s will be the number you skip by when counting up to n. s will be from 1 to n/2 (half of n). If n was 600, s could not be greater 300. You have to output all of the numbers up to n skipping by s starting with 1. Each output number should either be on a newline, on the same line separated by spaces, or in a list.
The Twist
For this Rosetta Stone Code Challenge, each snippet you write the program in must be the same length. ie: If your Python program has 56 characters then your Java program must also be 56 characters. Spaces and comments do not count as characters. Variable/function names can't be more than 10 characters. Remember, this is also code golf, so try to keep your code short.
Example
Input
[100, 7]

Output
1
8
15
22
29
36
43
50
57
64
71
78
85
92
99

Note: Output could be in single line separated by spaces or list format
Winning Criterion
The winner will be decided by this formula:
numberOfLanguages/codeSize
codeSize is not the total code size but the average code size of a snippet.
The user with the highest score will win. ie: An answer with 4 languages and a size of 31 bytes would win over an answer with 7 languages and a size of 80 bytes. A winner will be chosen at 2:00 UTC on March 9, 2015.
Scoreboard
All scores are rounded to the nearest thousandth
Maltysen - 14 languages / 24 characters = 0.583 ---- Winner
mbomb007 - 15 languages / 29 characters = 0.517
Jakube - 5 languages / 11 characters = 0.455
Teun Pronk - 4 languages / 51 characters = 0.078
captncraig - 1 language / 56 characters = 0.018

Does simply padding out the code with spaces count...? Or simply using the most obtuse variable or function names...?

@deceze Should've thought of that before. Just edited in some things under the twist. spaces do not count and function/variable names have a 10 character limit

It still just becomes a competition of adding some useless padding to fulfil the criteria. E.g., just add "aaaaaaaaaa.."; at the end of every program, which is a valid noop in virtually all languages...

@deceze I see. I made it code golf also, so people will try to keep it short (hopefully).

Maybe score by NumberOfLanguages / CodeSize?

@Ypnypn I can't believe I didn't think of that before. Thanks

@michaelpri I think you cam remove the "all programs must be the same size" requirement since you've changed the scoring rules.  Edit: I must also warn that NumberOfLanguages/Votes will simply encourage responses in a single language.

@PhiNotPi I think the "all programs must be the same size" still adds a lot to the contest.

I think this is still flawed. If I answer only in Whitespace, I get a score of 1/0, i.e. infinity. Otherwise, I'm still better off answering in a single language where this is shortest, because adding any other language (with longer code), reduces my score.

Are these snippets/functions or whole working programs?

@MartinBüttner I would assume whitespace reverses the whitespace rule so only whitespace counts.

I recommend using the sandbox next time, so these issues can be sorted out before the challenge is posted on main.

@captncraig I haven't heard of this being a common policy. But then there's still Lenguage.

How about you amend the scoring rules not to disregard whitespace but to forbid snippets that can be reduced in size trivially where trivial means that no snippet that comes from the posted snippet with some characters removed may solve the task?

For instance, for the task return 2, return 0+2; could be reduced trivially to return 2; but return 1+1; can't since you cannot remove some characters with the effect remaining.

@MartinBüttner How so? In my model whitespace do count towards the score and as far as I know no programming language exists where the empty program has the required semantics.

Also, your point about having longer programs reduces your score is incorrect. If I post one program of length 10, my score is 0.1. If I post three programs of length 20, my score is 0.15, which is higher. Shorter code size doesn't mean higher score automatically.

@FUZxxl, oh I misunderstood the scoring... I thought it was divided by total code size, not the code size of each snippet. That should work then, although it will be hard to verify if submissions satisfy your rules.

-1 for disincentivising just throwing in obscure verbose languages for the fun of it, in a [rosetta-stone].

n must be >= 2, otherwise, s is zero, which doesn't work.

@mbomb007 Good point didn't think of that,

This challenge has prompted me to delve into many languages in the last 2 days. My brain hurts...

Why not change scoring to numberOfLanguages/longestCodeSize? Everyone seems to be padding their shorter codes to match their longest, this will not change scoring only readability.

14 Languages - 24 bytes = 0.58333333333
**Facepalm**.  I forgot not to count the space in my Python answer. So I'm at 24 bytes now.
Learned about a lot of new languages from this challenge, which I will probably using in golfs. A site that really helped me find these languages was http://www.tutorialspoint.com/codingground.htm. Just don't expect my programs to run in it, it requires a full program format, and I just used it to learn about the languages and used other REPLs to run them.
1. Pyth:
Pyth doesn't have a range by step function unlike python, so I used regular range and chopped (thanks @Jakube) used mod operator on it.
M%Hr+Z+Z+Z+Z+Z+Z+Z+Z1+1G

Defines a function g(until, step)
M          Define g(G, H)
 %H        Every H elements
  r1+1G      Range 1->G+1

2. Golfscript:
This is my first golfscript program. Probably not the best way to do it.
000000000000000;\),1>\%p

\         swap
 )        increment
  ,       range
   1>     all but first element
   \      swap
    %     take every top of stack elements
     p    print array

3. Bash Utils:
Uses the seq command which has INCREMENT param.
seq 00000000000000001 $2 $1

4,5. Python, Sage:
Self-explanatory code.
lambda a,b:range(1,a+1,b)

Sage is a language based on Python used for math stuff.
6. Mathematica:
Again, self-explanatory.
r[a_,b_]:=Range[001,a,b]

7. Matlab:
Uses Matlab's range notation and defines an anonymous function.
@(a,b)00000000000001:b:a

8. Livescript:
Like Coffeescript it is a JS derivative. Has cool range syntax. Arrow notation again.
r=((((a,b)->[1 to a by b])))

9. Erlang:
Learned erlang just for this. Pretty self explanatory, defines function r.
r(a,b)->lists:seq(1,a,b)

10. F#:
Kind of obvious, F#'s function definitions are like variables.
let r a b=seq{000001..b..a}

11. Haskell:
Haskell's range notation has you give the first two in the range for the increment, and not an explicit increment.
r a b=[00000000001,a+1..b]

12. R:
Very cool language, even if function definitions are a little verbose.
function(a,b)seq(01,a,b)

13. Julia:
Awesome language, will be using for golfing in the future.
r(a,b)=[00000000001:b:a]

14. CJam:
Like my old golfscript answer except with input parsing and padding.
0000000000000;q~\),1>\%p

How do I run this? Mmhdcr1GH100 7 doesn't work like I thought it would.

@mbomb007 M defines a function g, which you have to call first. Try Mmhdcr1GHg100 7.

% is the same thing as python's [::a]. No need for chopping. And I'm pretty sure your range has to go up to including G, e.g. using r1hG.

@Jakube thanks for the tip

Please put a space before 7. Negative doesn't look right.

@mbomb007 fixed, srry

I think you should have to assign your CoffeeScript function to a variable, same with R. Otherwise it can't be called since it's anonymous. Also, your function doesn't work.

Same with Python too. I'm pretty sure it has to be callable by name.

For the R function it s easy to solve, just get rid of the extra 0 and add f= to assign the function to a name: f=function(a,b)seq(1,a,b). Otherwise you can indeed use it as an anonymous function (i. e. (function(a,b)seq(001,a,b))(100,3) for instance), but here it is unnecessary since you can have 2 additional character without changing your score.

@mbomb007 I don't think it is required since you can call anonymous functions by just doing (function)(a,b), but I will be naming the ones where I have chars left. Also, which one doesn't work?

The thing is that by calling an anonymous function that way, you have to repeat your code or surround it with something, rather than a call on the next line. Defining a function also generally means it's named so it can be called any number of times, in multiple places in your code.

CoffeeScript is the one that doesn't work. Your function would have to be essentially identical to mine. Some of yours feel like you copied them, to me. But I don't really know what the policy on that is or how different a program needs to be...

CoffeeScript has i for x, which can't work.

@mbomb007 srry was away for a week, didn't see your comments. I didn't really copy any of of your's, except I got the idea to do coffeescript from yours. Idk the rules on that, but ill take it down just to be safe.

Congratulations! You won.

Yeah, congrats. yours were shorter, making it harder for me to catch up on score.

23 languages, 15 characters = 1.5333333
+---------------+----------------------+----------------+
|    Language   |         Code         |      Kind      |
+---------------+----------------------+----------------+
|          gs2  |  B/4[RRRRRRRRRRR     |  (stack)       |
|         Pyth  |  M%+Z+Z+Z+Z+ZHSG     |  (definition)  |
|   GolfScript  |  \),000000001>%p     |  (stack)       |
|         CJam  |  \),000000001>%p     |  (stack)       |
|          zsh  |  seq 00000001 $2 $1  |  (script)      |
|         Bash  |  seq 00000001 $2 $1  |  (script)      |
|   FlogScript  |  \),0000001>\%Pa     |  (stack)       |
|          APL  |  {00001+⍵×⍳⌈⍺÷⍵}     |  (lambda)      |
|      Mathics  |  00001~Range~##&     |  (lambda)      |
|  Mathematica  |  00001~Range~##&     |  (lambda)      |
|            J  |  ({.\00001+i.)~-     |  (lambda)      |
|       Matlab  |  @(a,b)00001:b:a     |  (lambda)      |
|       Octave  |  @(a,b)00001:b:a     |  (lambda)      |
|    Burlesque  |  jrojcoq-]m[m]uN     |  (stack)       |
|            K  |  {0001+&~(!x)!y}     |  (lambda)      |
|          Pip  |  {_%b=001FI,++a}     |  (lambda)      |
|      Haskell  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Clean  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Curry  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Frege  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Julia  |  ff(a,b)=[1:b:a]     |  (definition)  |
|       Scotch  |  f(a,b)=[1..a,b]     |  (definition)  |
|        Perl6  |  {1,$^b+1...$^a}     |  (lambda)      |
+---------------+----------------------+----------------+

Since you have Matlab, why not add Octave?

That might work. Would the code be exactly the same?

Yes, it's exactly the same.

Neat. I've added it!

jrojcoq-]m[m]uN would be a Burlesque Version that outputs number and doesn't push dummy data to the stack just to pop it again.

15 languages, 29 characters = (15/29) ≈ 0.517
I've fixed all my code so far. Now I'm searching for other languages.
1. Python (24 golfed)
f=lambda n,s:range(0001,n+1,s)

2. ><> (Fish) - (19 + junk chars)
This program assumes that the number and the step size were are on the stack beforehand, pushed in that order. Uses ao to print newlines between numbers.
1           v
$:@+:{:}(?!;>:nao
~~~~~~~~~~

Explanation (code, stack after preceding code executes, comments):
1               1 s n           start n0=1. stack is (top)1 s n(bottom)
(skip to print code - last line of explanation, then come back)
 $:@            s 1 s n         swap, duplicate, rotate top 3 (this all is OVER in Forth)
   +:           n1 n1 s n       add step to x and dup
    {:}         n n1 n1 s n     compare to n
       (        n1>n n1 s n     if !(n1 > n), JUMP: dup and print (continue)
        ?!;     n1 s n          else exit
          :nao  n1 s n          dup, print n1, newline, loop around

3. APL (19 golfed)
fffffffff←{(⌈⍵÷⍺)↑1+⍺∘.×(⍳⍵)}

Golfed. Paste into here: http://ngn.github.io/apl/web/
f←{(⌈⍵÷⍺)↑1+⍺∘.×⍳⍵}

Call like this: 7 f 100. This creates an array from 1 to n, multiplies every element by s, adds one to each element, then takes the first ceil(n/s) elements.
4-7. Haskell, Clean, Curry, Frege (14 golfed - spaces don't count)
This program is valid in Haskell, Clean, Curry, and Frege.
ffffffffff nnnn s=[1,s+1..nnnn]

Golfed. Run here: https://ideone.com/Ii0pgP
f n s=[1,s+1..n]

8. Scotch (15 golfed)
fffffffff(nnnn,s)=[1..nnnn,s]

9. Jaskell (24 golfed) - Built based on documentation.
Filter the list where the remainder modulo s is 1.
ffffff n s=filter(.%s==1)[1..n]

10. CoffeeScript (25 golfed) Run here
fffff=(n,s)->x for x in[1..n]by s

11. R (25 golfed) Run here: http://www.r-fiddle.org/#/fiddle?id=k3vRnCOW&version=2
fffff=function(n,s)seq(1,n,s)

12. Cobra (26 golfed)
def ffff(n,s)
    for i in 1:n:s
        print i

13. S-Lang (28 golfed)
define ff(n,s){return [1:n:s];}

14. Boo (29)
Not sure if range function can take 3 parameters...
def f(n,s):return range(n)[::s]

15. Funge-98 (29, any help golfing?)
As close as I could get to my ><> program. Since there's no "rotate" stack instruction, I had to use "put" and "get" instead. Befunge really needs some stack rotation/shift instructions, or even an "over" instruction.
22p1v
    >:.a,\:33p\33g+:22g\`!j@

Explanation:
        n s
22p     s           (store n at 2,2)
1       1 s         (push 1)
(v and > are direction changes, so the above only happens once)
\:      s s 1       (swap, dup)
33p     s 1         (store s at 3,3)
\33g    s 1 s       (get s)
+:      n1 n1 s     (add, dup)
22g     n n1 n1 s   (get n)
\`!     !(n1>n) n1 s    (swap, >, not)
j@      n1 s        (conditional exit)
:.a,    n1 s        (print n1, newline)

NOT USING AT THE MOMENT, TOO LONG - My score is improved by not including these.
Ruby (35) Run here: http://ideone.com/yFZELR
def f(n,s)
    (1..n).select{|x|x%s==1}
end

PowerShell (38)
function f($n,$s){(1..$n|?{$_%$s-eq 1})}

Perl (39) Run here: https://ideone.com/HGoleN
sub f{join(" ",grep $_%@_[1]==1, 1..@_[0])}

Notice that your ><> program counts backwards from n to one by skipping s, thus it produces
2 9 16 23 30 37 44 51 58 65 72 79 86 93 100
for n=100, s=7 instead of
1 8 15 22 29 36 43 50 57 64 71 78 85 92 99
as specified in OP's example.

@cirpis I fixed ><>, still have to fix Befunge.

Rather than assuming everything's on the stack for ><>, I think you can use the -v flag to supply input. Normally flags add a byte, but I'm not sure whether that means you need to remove a junk char or not (since apparently we only care about "code size")

I see people assuming stuff is on the stack all the time for Befunge, GolfScript, etc. But I don't know how to input, other than i, which pushes a character. Also, while we're on the topic of stuff, is it acceptable for the program to crash after successfully completing its output (by popping an empty stack)?

there is no in code way to read input as a number in ><>, however in the python ><> interpreter there is a special flag "-v" that prepopulates the stack, e.g. calling -v 100 7 will make the first value of the stack 100 and the second one 7

The ><> code is still not right :D (please consider using the interpreter). It does not print the 1 as the first number and the ")" should be a "(".

I don't currently have access to one, unless there's one online. That's what you get when you create an esoteric language, and have little documentation.

You should try R, basically the same type of syntax as Python.

I made one in Scala, but it's far too long for me. ((n:Int,s:Int)=>((1 until n)toList)filter(_%s+s-1==0))(100,7)

@mbomb007 With seq.int(). It works the same as range in Python. Then you can get it to 29.

@mbomb007 actually you can use seq() as well as seq.int().

Huh. It never occurred to me to try that.

Note, updated the "padding" on the programs. Golfed CoffeeScript down to 25.

5 languages 11 characters = 0.4545
Took this challenge as an opportunity to check out some new languages (CJam, Burlesque, zsh, gs2). First time I've worked with these languages.
The method behind creating the output is different in nearly each language. Only the CJam and the gs2 method are identical. The 4 methods are, creating a range [1, 100] and slice it with modulo (CJam and gs2), creating the range [1, ..., 100] and filter for elements that are 1 mod 7 (Pyth), creating the range [1, ..., 100], divide it into chunks of len 7 and use the first element of each chunk (Burlesque), and creating the sequence directly (zsh).
I tried to design each program in such a way, that it looks golfed to someone, who is not familiar with the language.
edit 1: added Burlesque, previous 2 languages with 10 characters = 0.2
edit 2: added gs2, previous 3 languages with 11 characters = 0.2727
edit 3: added zsh, previous 4 languages with 11 characters = 0.3636
CJam
q~\1+,0-\%p

Test it online with the input 100 7.
q~           push the evaluated input (100 7)
  \          swap (7 100)
   1         push 1 (7 100 1)
    +        add last to elements (7 101)
     ,        create the range (7, [0, 1, ..., 100])
      0       push 0 (7, [0, 1, ..., 100], 0)
       -      delete 0 from the range (7, [1, 2, ..., 100])
        \     swap ([1, 2, ..., 100], 7)
         %    use every 7th entry ([1, 8, ..., 99])
          p   print pretty

Burlesque
jrojcoq-]m[

Beside zsh, this is the only golfed program. Burlesque is quite awesome, it has a very large range of different functions, like ro. Sadly there's nothing like the Python [::a] slicing operator.
There is no online interpreter, but you can get Burlesque here. Since Burlesque doesn't support functions or IO, you have to put the values onto the stack first, like 100 7 jrojcoq-]m[
j            Swap (7 100)
 ro          Range (7 {1 2 ...  100})
   j         Swap ({1 2 ... 100} 7)
    co       ChunksOf ({{1 2 ..  7} {8 ... 14} ... {99 100}})
      q      Create Block ({{1 2 ..  7} {8 ... 14} ... {99 100}} {})
       -]    head (first element) ({{1 2 ..  7} {8 ... 14} ... {99 100}} {-]})
         m[  map the chunks to the head-block

gs2
read-nums dup head inc range tail swap reverse head mod unlines

Yep, this is only 11 chars. In gs2 each byte has a different meaning. But because writing in bytes is quite hard and not any fun, you can also write in mnemonics, which you can compile to the actual gs2 code. The gs2 code, which gets executed is
W@!'."B !4+

or as hex-dump:
57 40 21 27 2e 22 42 20 21 34 2b

Fun fact: I didn't write in mnemonics, but directly the numbers of the hex-dump.
You can test it by downloading the compiler. Compile the mnemonics file with python gs2c.py < mnemonics.txt > compiled or simply copy W@!'."B !4+ to a file named compiled and then execute it with echo 100 7 | python gs2.py compiled.
The mnemonics is pretty self explainable, but here's what's going on in the stack.
57 40 21 27 2e 22 42 20 21 34 2b
57                                 read-nums ([100 7])
   40                              dup ([100 7] [100 7])
      21                           head ([100 7] 100)
         27                        inc ([100 7] 101)
            2e                     range ([100 7] [0 1 ... 100])
               22                  tail ([100 7] [1 2 ... 100])
                  42               swap ([1 2 ... 100] [100 7])
                     20            reverse ([1 2 ... 100] [7 100])
                        21         head ([1 2 ... 100] 7)
                           34      mod ([1 8 ... 99])
                              2b   unlines ('1\n8\n...\n99')
                                   everything on the stack gets printed

Btw, 8 bytes are possible, maybe even less.
edit: I forked gs2, slightly manipulated a command and made a pull request, which is already merged. So now the task can be done with 6 bytes: read-nums extract-array swap range1 mod unlines, which translates to 57 0e 42 2f 34 2b, which is even better than the optimal pyth.
zsh
f() seq 1 $2 $1

This defines a function f, that creates the a sequence. To use it on Windows, I installed the babun shell, where you can simply type these commands. Simply write f() seq 1 $2 $1 and in the next line f 100 7.
First I tried to write this in Bash, but there you have to write () around the code block, like f() ( seq 1 $2 $1 ). So I switched to zsh instead.
Pyth
fq1%TeQUhhQ

This really hurts, since of course I see the obvious 7 byte golf. You can test it online with the input 100, 7.
                 Q = input()
       UhhQ      the range [0, 1, ..., Q[0]]
f                filtered (only use those elements T, which satisfy the equation
 q1%TeQ             1 == T % Q[1]

Technically Burlesque has an "EveryNth"-Command.
Like 100ro7en?i which produces {8 15 22 29 36 43 50 57 64 71 78 85 92 99}. You can go even shorter by using 7mo14.+?i.

@mroman Quite a long time since I wrote this code. But as far as I remembered the "EveryNth"-Command doesn't work like the [::a] command in Python. EveryNth([1,2,3,4,5,6,7,8, 9], 3) returns [3, 6, 9] and not [1,4,7], like it was required in this challenge.

Yes, you're right. The en works different than one would expect from other languages. I curse the day I implemented it this way :D. Common workarounds for that are either using the mo I mentioned above or by using co as in 9ro3co)-] which produces {1 4 7}.
PS: I had an online interpreter back in the old days but my new hoster doesn't support CGI anymore but I might be able to convince someone who has a Server with CGI support to host the online interpreter again :)

4 languages 51 characters = (4/51) = 0,0784313725490196
No idea how many numbers after comma you want so i'll just leave it like this.
All snippets are 51 characters long when you remove all the whitespace.
Working on more and shorter code but it's a start.
Log
Initial answer
Submitted Python(3.4), Lua(5.1) and Javascript.
Score: 3/51 = 0,0588235294117647
Update 1
Added Ruby
Score: 4/51 = 0,0784313725490196.
Python 3.4
def f(NUMB,ST):
    CNT=1
    while CNT<=NUMB:
        print(CNT)
        CNT+=ST

Lua 5.1
function f(num,st)
    for cn=1,num,st do
        print(cn);
    end;
end;

Javascript
function f(n,s){
  for(i=1;i<=n;i+=s){
    console.log(i);
  }
}

Ruby
def faa(numb,st)
  for i in 1..numb
    if i%st==1
      puts i
    end
  end
end

If you want another language, here's STATA:
di _reque(s) _reque(n) gl a=1 while $a<=$n{ di $a gl a=$a+$s }

@bmarks Thanks, seems a bit lame to add someone else's code to the answer though ;)

In the javascript function, I think you need i<=n instead of i<n. Also, I think you can shorten most of these by using the alert function in javascript and shortening variable names in the others.

@bmarks the variable names used to be 1 character each, same for function names. I just padded them a bit to get them to be the same length. and youre right about the javascript. Ill change it.

I only count 50 chars in the Ruby solution.

1 language - 56 characters = 0.01785714285
piet (2x28) -


text:
count number of valid, unique sequences for moving on a 1xn board
There's a board with n squares in a horizontal row.
You start in the leftmost square, and roll a 3-faced dice.
3 possible outcomes for a single roll of the die:

Left: you move 1 step to the left, if possible.
None: you stay where you are
Right: you move 1 step to the right, if possible.

You want to roll the dice exactly t times, and end up at the rightmost square on the last roll.
If you arrive at the rightmost square before t rolls, your only valid move is None.
You need to determine the number of valid (meaning, for instance, that you don't count sequences that try to move left or right from the rightmost square), unique sequences of dice rolls, for given (t,n) pairs. As the answer may be large, give it modulo 1000000007 (ie. 10^9+7).

t is a positive integer s.t. t <= 1000
n is a positive integer s.t. 2 <= n <= 1000

Sample testcases:

t=1, n=2, answer=1
t=3, n=2, answer=3
t=4, n=3, answer=7

The shortest code in bytes wins.

Seems like you were redirected here from Stack Overflow. It's a good question, but there's two things I'd like to ask: 1) PPCG questions need an objective winning criterion - how are you going to decide the winner here? (My suggestion would be code-golf), and 2) Is this a question from an ongoing contest?

This question will get put on hold or closed as off topic if you don't give it an objective winning criterion. I would suggest code-golf (shortest code, in bytes) as it will be easy to determine the winner. Fastest code is likely to attract less answers (though they might be more interesting) and it requires you to test the answers to determine the winner.

I'm getting an answer of 4, not 3, for t=3, n=2, with the sequences RSS, SRS, SSR, RLR. Am I missing a rule?

@xnor: yep, you're absolutely right; added it in as an edit.

@Sp3000: done, as suggested; no, the contest is not ongoing. it's different from the typical programming contest that is open for a specified duration, this one is self-initiated as and when you please, and then a countdown timer starts from that time of your choosing.

@StChong8 I'm also getting 8 for t=4, n=3.

@xnor t=4,n=3: the 7 that i get - RRLR, RRNN, RNRN, NNRR, NRRN, RNNR, RLRR

@StChong8 OK, I'm now getting the same values with the edit that you must stand still after arriving at the rightmost square, including 7 for t=4, n=3.

If this is from another contest, permanent or not, I still don't think it's a good idea to post it here, in particular, because it might violate their copyright.

@xnor: yea, sorry about that.

@StChong8 "@xnor t=4,n=3: the 7 that i get - RRLR" How is RRLR supposed to be valid ?

@StChong8 can we move left on leftmost pos'n?Plz be quick as I cannot post my code unless you answer.

In view of our policy on posting challenges from competitions, I'm putting this on hold for now.

@Doorknob is that enough to reopen this question ?

@MukulKumar The winning criterion has nothing to do with Doorknob's close vote. That was the close reason es1024 and I chose before a winning criterion was added. While this is no longer the appropriate close reason, I thought the challenge should still be closed, as stated in a comment above, and linked to by Doorknob - since I can't retract my close vote and recast it with another reason I just left it as it is.

@MukulKumar: no, moving left from the leftmost pos (ie. starting square) is not allowed.

@StChong8 "@xnor t=4,n=3: the 7 that i get - RRLR" How is RRLR supposed to be valid ?

Is this from a "virtual contest" for practicing purpose in preparation of real contests? In that case I think it is fine.

Python, 74
f=lambda t,n,i=1:i==n or t*i and sum(f(t-1,n,i+d)for d in[-1,0,1])%(1e9+7)

A recusive solution. The current position i is stored 1-indexed as an optional argument.

If the current position i==n, we've arrived at the final square and are forced to stay still, giving 1 path.
Otherwise,

If the remaining time t==0, we've run out of time, so there's 0 paths.
If the current position i==0, we've run off the left end already, so there's 0 paths.

If neither of those was true, there we recurse. We add up the path counts for each of the directions left, none, and right, corresponding to displacements [-1,0,1], and take the result modulo 1e9+7 as required.

An alternative solution that uses eval with string substitution to do the sum. Same number of chars. Note the use of unary + to start the sum.
f=lambda t,n,i=1:i==n or t*i and eval(3*'+f(t-1,n,i+%d)'%(-1,0,1))%(1e9+7)

Here's another a solution that is surely short for any language with built-in matrices, so anyone who can golf it is welcome to take it.
Let M be the n*n transition matrix for the walk, which is a tridiagonal banded matrix with 1's on the main diagonal and the diagonals above and below it, except for a 0 for movement left from the rightmost cell.
1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 0 1

Then, the output is (1,n) entry of the matrix power M^t.

Nice and short! The faster way to do it would be to set up an array with one cell for each square of the board and iterate t times. Then on each iteration, add the values of the cells to left and right to it, similar to Pascal's triangle. I have a 126 byte ruby solution based on that approach, which I can't post now :-S Matrix idea is cool too.

Thks; pls share more details how you came up with/derived the n*n transition matrix?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Vim - surround comment line with comment character
Today I realised that I often like to define sections in my code like so:
####################
# Helper Functions #
####################

But that it's tedious to do. Assuming I have a line such as this:
# Helper Functions #

What is the shortest set of vim keystrokes to wrap it in a #? Shift does not count as a keystroke in this challenge.
Test cases:
Input: "#test test test#"
Output:
################
#test test test#
################

Input: "#this is a nice block comment#"
Output:
##############################
#this is a nice block comment#
##############################

Input: "# s p a c e s must be supported a l s o#"
Output:
########################################
# s p a c e s must be supported a l s o#
########################################

I'm voting to close this question as off-topic because "vim keystrokes" basically means running commands of an IDE, like Ctrl - C, or Ctrl - R in ST2. This is not coding in any form.

@Optimizer Vim is a turing complete language (e.g. by using macros) with several different constructs coding and the primary method for editing is based on verbs (actions) an objects (movements). There is already a popular web page for vim golfing: www.vimgolf.com. (But I agree that this particular question is pretty boring)

@Optimizer: is there a more suitable S.E. site the question could be moved to? Given vim's extensive scripting/macro language, some people might consider it a language in itself.

Supposedly most other PPCG big shots also think the same as you do. But both the above comments/arguments hold true for any good IDE, like ST2 or IntelliJ or Atom

@Optimizer I have no idea what PPCG means, but your response sounds surprisingly hostile for what I thought was a reasonable reply to your comment.

@Optimizer So there is a www.IntelliJgolf.com as well? :P

@shearn89 Hostile ? What are you talking about ? PPCG is this site.

@Hjulle so treat a random webpage as a proof :D

@Optimizer - ahhh that makes more sense! I interpreted it as you calling myself a "PPCG bigshot", and assumed the PPCG was derogatory. My bad!

Why wouldn't other IDE's be allowed as well if you can write programs in their macro system? What is it that makes it "not programming"?

I like this question, because I also do this =D

11 8 7 keystrokes
YpVkr#p

Yp - duplicate current line, leaving the cursor at the lower of the two
V - enter visual line mode
k - go up and select both lines
r# - replace every selected character with #. Leaves visual mode and leaves cursor at the upper line.
p - put the yanked line (the original) on the next line.

(thanks to doorknob for reminding Y=yy)

Replace yy with Y to save a character.

Wow, that r command is powerful

16 15 14 keystrokes
Yp
:s/./#/g
<cr>
YkP

The straight-forward approach: duplicate the line, replace all characters with #, copy the the result and paste it above.
I'm counting P and : as one keystroke each (instead of two for Shift+p or Shift+;). That being said, the question specifies to count "commands", where I'm not sure how to count the substitution.

Same comment as on @rcrmn's answer: Replace yy with Y to save a character.

I believe it's actually 14 keystrokes, as you have to hit Intro to execute the replace command

@rcrmn Oh, good catch.