Skip to content

Instantly share code, notes, and snippets.

@nicholasbs
Created November 3, 2012 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholasbs/4008506 to your computer and use it in GitHub Desktop.
Save nicholasbs/4008506 to your computer and use it in GitHub Desktop.

LinkedList NYC Program

inside this file is a webserver that will output the text "LinkedList NYC" on network port 31337 via HTTP.

killin' it

executes with ruby 1.9.3

ruby -x ./readme.markdown to run the server, do a killall ruby to stop the server

ruby run.rb to run the server once, output with curl, then stop.

List Output

in your terminal run curl localhost:31337 to get the output, something resembling "LinkedList NYC" should output, unless there's some tragic error.

#!/usr/bin/env ruby -w

# This script is a simple ruby web server that
# serves the file it is inside.

require 'socket'

Process.daemon

server = TCPServer.new(31337)
DATA.rewind
data = DATA.read

# Pull out first letters
parts = data.split('```')
first = parts.first.split("\n").map{|l| l[0] }

# Pluck out NYC
last = ""
lines = parts.last.split("\n")
lines.each_with_index do |l, i|
  last += ( l[0] || "\n") if lines.fetch(i+1, '')[0] == '-'
end

# Finish output
out = first.join.gsub(/[^\w]/, '') + " " + last

# Serve http
loop do
  Thread.start(server.accept) do |client|
    lines = []
    while line = client.gets and line !~ /^\s*$/
      lines << line.chomp
    end
    client.puts <<-MESSAGE.gsub("\n", "\r\n")
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: #{out.bytesize+2}
Connection: close

#{out}
    MESSAGE
    client.close
    Thread.exit
  end
end

__END__

Now how does it work?

The script there in the middle is a web server. Ruby can run scripts embedded inside of text files. I have no idea why, but the bits between the shebang and the __END__ block become executable with the -x flag sent to ruby.

Once the script starts running, everything after __END__ becomes available as as the constant DATA, which allows rewinding to the beginning of the file so that you can see everything before the __END__ as well.

After that, it's a simple matter of plucking out the message from the rest of the DATA block and outputting it with http headers.

Yes, but is it web scale?

ab -c 10 -n 1000 http://localhost:31337/

Requests per second:    3095.75 [#/sec] (mean)
Time per request:       3.230 [ms] (mean)
Time per request:       0.323 [ms] (mean, across all concurrent requests)

Credits

This script brought to you by Hurricane Sandy.

It uses quite a few tricks learned from https://speakerdeck.com/jeg2/10-things-you-didnt-know-ruby-could-do

#ifdef _
_(A)_(B) _(C)_(D) _(E)
_(F) _(G) _(H) _(I)_(J)
_(K) _(L) _(M) _(N)
_(O) _(P) _(Q)_(R)
_(S) _(T) _(U)
_(V)_(W) _(X)
_(Y) _(Z)_(a) _(b)_(c) _(d)_(e)
_(f) _(g) _(h) _(i)
_(j)_(k) _(l) _(m)_(n)
_(o) _(p)_(q) _(r)
_(s) _(t) _(u)
_(v)_(w) _(x) _(y)_(z)
#else
#define _(z)_##z)();typedef _##z(*
#include <stdio.h>
typedef int(*
#include __FILE__
#define __(_,z)_z _(__ y){return fputs(z,stdout),y?y(0):(_z)_0;}
#undef _
__)();__(_0,"")__(nl,"\n")__(_," ")
#define _(_)__(_,#_)
#include __FILE__
int main() {
(L)(i)(n)(k)(e)(d)(_)(L)(i)(s)(t)(N)(Y)(C)(nl);
return 0;
}
#endif /* http://mishadynin.com/ */
Universe amends
narrows enough split young. bear hatchery powers Links. (Listed)
narrows enough split bear hatchery power. invert instigate
narrows enough split young. bear hatchery powers naturalized
narrows split enough bear hatchery power. invert conversation. regarding. link
narrows split enough young. bear hatchery powers (among,nodes). despite
narrows enough split bear hatchery power. invert dastardly
narrows enough split young. bear hatchery powers Links. (HTML)
narrows enough split bear hatchery power. invert in
narrows enough split young. bear hatchery powers seminal. sites
narrows split enough bear hatchery power. invert linking. the. rat
narrows split enough young. bear hatchery powers amidst.
narrows enough split bear hatchery power. invert Neuveau
narrows split enough young. bear hatchery powers H4x0rY
narrows enough split bear hatchery power. invert Citizens, where all the cold snowmelt ?
from argparse import ArgumentParser
import sys
src = """#include <stdio.h>
int main(void)
{
printf("LinkedList NYC\\n");
return 0;
}
"""
def learn_language(input_line):
pass
parser = ArgumentParser(description="An anything-to-C translator with some caveats")
parser.add_argument('-i', '--input', help="Source file to translate (defaults to stdin)")
parser.add_argument('-o', '--output', help="Output C file (defaults to lltrans.c)")
args = parser.parse_args()
infile = open(args.input, "r") if args.input else sys.stdin
outfile_name = args.output if args.output else "lltrans.c"
outfile = open(outfile_name, "w")
for line in infile:
learn_language(line)
outfile.write(src)
infile.close()
outfile.close()
/*
Most Inconvenient Way of Printing `LinkedList NYC`
Yufei Liu @yufeiliu, liu.yufei@gmail.com
10/27/2012
*/
var http = require('http');
var question = 'what is the largest city in america';
http.get({ host: 'www.bing.com', path: '/search?q=' + question.replace(/[ ]/g, '+') }, function(res) {
var data = '';
res.on('data', function(body) {
data = data + body;
});
res.on('end', function () {
var processed = data.replace(/<(\/)?strong>/g, '').replace(/[,\.\n]/g, '');
var allWords = processed.split(' ');
var acceptableWords = [];
allWords.forEach(function (word) {
if (/^[a-zA-Z]+$/.test(word)) {
acceptableWords.push(word.toUpperCase());
}
});
console.log([firstPart(), secondPart(acceptableWords)].join(' '));
});
});
//Generated 'LinkedList' with an interpolated 9th degree polynomial function
function firstPart () {
var polynomial = function (x) {
var factors = [
6.191841505 * 10E-4,
-0.242807737,
3.983961591,
-35.53337866,
187.270882,
-592.9775643,
1093.411018,
-1070.65602,
443.7940326,
75.96024295
];
var y = 0;
for (var i = 0; i < 10; i++) {
y += factors[i] * Math.pow(x, 9 - i);
}
return y;
};
return [0,1,2,3,4,5,6,7,8,9].map (function (x) {
return String.fromCharCode(Math.round(polynomial(x)));
}).join('');
}
//Generate 'NYC' by analyzing trigram model of search results of `what is the largest city in america` on bing
function secondPart (words) {
//generate a tri-gram model
var counters = {};
for (var i = 0; i < words.length - 2; i++) {
var key = [words[i], words[i+1], words[i+2]].join(',');
if (!counters[key]) {
counters[key] = 0;
}
counters[key]++;
}
//sort by occurence
var sortable = [];
Object.keys(counters).forEach(function (key) {
sortable.push([key, counters[key]]);
});
sortable.sort(function(a, b) {
return b[1] - a[1];
});
//Find first trigram containing all content words (e.g., no 'is', 'in', etc)
var useless = ['IS', 'THE', 'IN', 'OF', 'WITH', 'A', 'AND'];
var foundIt = null;
for (var i = 0; i < sortable.length; i++) {
var key = sortable[i][0].split(',');
var hasUselessWords = useless.some(function (word) { return key[0]===word || key[1]===word || key[2]===word });
var hasRepeats = key[0] === key[1] || key[1] === key[2];
if (!hasUselessWords && !hasRepeats) {
foundIt = key;
break;
}
}
//abbreviate
var abbreviation = foundIt.map(function (word) { return word.charAt(0); }).join('');
return abbreviation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment