Do you guys have a better way of copying large source posts?
One of my primary use cases is to download C++ code directly to a file so that I can compile it and try to reproduce the problem. So I wrote this simple one-liner to download code blocks from questions:
curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[1]/text()" - 2>/dev/null|recode html..ascii
The code block number can be specified in square brackets in an XPath expression. For me I find this more useful than a "Copy" button. Here are examples of a one-liner in action for Why is it faster to process a sorted array than an unsorted array?.
First code block:
[ ~]$ curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[1]/text()" - 2>/dev/null|recode html..ascii
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
Second code block:
[ ~]$ curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[2]/text()" - 2>/dev/null|recode html..ascii
import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i)
{
// Primary loop
for (int c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}
}