# the trick is using the `then` keyword
try fail() catch e then console.log e
Reveal More
# the trick is using the `then` keyword
try fail() catch e then console.log e
printBar = ({bar}) ->
console.log bar
printBar
foo: 42
bar: 'ohai destructuring args!'
try fail() catch e then console.log e
setTimeout ->
# callback code here
, 2000
# coffeescript
elideBefore = (text, elideLength) ->
if text.length < elideLength then text
else text.slice(0, elideLength).replace /\W\w*.{3}$/, '...'
# This is CoffeeScript, dammit!
# Adapted from example code here: http://is.gd/keMc3
# Big thanks to James Halliday (A.K.A. Substack)
{puts} = require 'sys'
fs = require 'fs'
{exec} = require 'child_process'
Seq = require 'seq'
Seq()
.seq ->
exec 'whoami', @
.par (who) ->
exec "groups #{who}", @
.par (who) ->
fs.readFile '/etc/bashrc', 'ascii', @
.seq (groups, src) ->
puts "Groups: #{groups.trim()}"
puts "This file has #{src.length} bytes"
#!/usr/bin/env ruby -rubygems
require 'couchrest'
require 'time'
abort "usage: #{$0} DB_URL INPUT_FILE_PATH" unless ARGV.length == 2
DB_URL = ARGV[0]
INPUT_FILE_PATH = ARGV[1]
BULK_SAVE_LIMIT = 5000
LOG_LINE_REGEXP = /^\[([^\]]+)\] \[([^\]]+)\] \[([^\]]+)\] ([\d.]+) - - '(\S+)' (\S+) (\d+)\s*$/
def parse_line line
match = LOG_LINE_REGEXP.match(line)
return {
:time => Time.parse(match[1]).utc.iso8601,
:type => match[2],
:erlang_pid => match[3],
:ip_address => match[4],
:verb => match[5],
:url => match[6],
:response_code => match[7].to_i
} unless match.nil?
end
db = CouchRest.database! DB_URL
db.bulk_save_cache_limit = BULK_SAVE_LIMIT
open(INPUT_FILE_PATH).each_line do |line|
doc = parse_line line
unless doc.nil?
db.save_doc doc, true
putc '.'
end
end
db.bulk_save
puts 'done'
qsort([]) -> [];
qsort([H|T]) ->
{Bigger,Smaller} = lists:partition(fun(N) -> N > H end, T),
qsort(Smaller) ++ [H] ++ qsort(Bigger).
qsort([]) -> [];
qsort([H|T]) ->
Smaller = [N || N <- T, N =< H],
Bigger = [N || N <- T, N > H],
qsort(Smaller) ++ [H] ++ qsort(Bigger).
function(s) {
return $('<div/>').text(s).html();
}
// http://en.wikipedia.org/wiki/Ordinal_number_(linguistics)
function toOrdinal(n) {
function suffix(tens, ones) {
if (tens != 1) {
switch(ones) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
}
}
return 'th';
}
return n + suffix(Math.round((n % 100) / 10), n % 10);
}
// http://en.wikipedia.org/wiki/Ordinal_number_(linguistics)
function toOrdinal(n) {
var tens = Math.round((n % 100) / 10);
var ones = n % 10;
var suffix = 'th';
if (tens != 1) {
switch(ones) {
case 1:
suffix = 'st';
break;
case 2:
suffix = 'nd';
break;
case 3:
suffix = 'rd';
break;
}
}
return n + suffix;
}
(function($) {
function firstOfMonth(d) {
return new Date(d.getFullYear(), d.getMonth(), 1);
}
function sameDate(d1, d2) {
return d1.getFullYear() == d2.getFullYear() &&
d1.getMonth() == d2.getMonth() &&
d1.getDate() == d2.getDate();
}
function renderCalendar(dateForMonth, selectedDate) {
function dayOfWeekHeaders() {
var dayLabels = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
output.push('<tr>');
for (var i = 0; i < 7; i++) {
output.push('<th>');
output.push(dayLabels[i]);
output.push('</th>');
}
output.push('</tr>');
}
function blankDaysBeforeFirst(dateForFirst) {
for (var i = 0; i < dateForFirst.getDay(); i++) {
output.push('<td></td>');
}
}
function blankDaysAfterLast(dayOfWeek) {
if (dayOfWeek != 6) {
for (var i = dayOfWeek; i < 6; i++) {
output.push('<td></td>');
}
output.push('</tr>');
}
}
function dayCell(date) {
if (sameDate(date, selectedDate)) {
output.push('<td class="selected">');
output.push(d.getDate());
output.push('</td>');
} else {
output.push('<td><a href=#>');
output.push(d.getDate());
output.push('</a></td>');
}
}
var output = [];
output.push('<table class="calendar">');
dayOfWeekHeaders();
output.push('<tr>');
blankDaysBeforeFirst(dateForMonth);
var currentMonth = dateForMonth.getMonth();
var d = firstOfMonth(dateForMonth);
while (d.getMonth() == currentMonth) {
var dayOfWeek = d.getDay();
if (dayOfWeek == 0 && d.getDate() != 1) {
output.push('<tr>');
}
dayCell(d);
if (dayOfWeek == 6) {
output.push('</tr>');
}
d.setDate(d.getDate() + 1);
}
d.setDate(d.getDate() - 1); // Go back to last day of month...
blankDaysAfterLast(d.getDay());
output.push('</table>');
return output.join('');
}
$.fn.calendar = function() {
return this.each(function() {
var $cal = $(this);
var selectedDate = new Date();
var displayedMonthDate = firstOfMonth(selectedDate);
var renderHtml = function() {
$cal.html(renderCalendar(displayedMonthDate, selectedDate));
$("a", $cal).click(function(ev) {
var dayOfMonth = parseInt($(this).text());
selectedDate = new Date(
displayedMonthDate.getFullYear(),
displayedMonthDate.getMonth(),
dayOfMonth
);
renderHtml();
$cal.trigger('selectedDateChanged', [selectedDate]);
});
};
$cal.bind('showPrevMonth', function() {
var month = displayedMonthDate.getMonth() - 1;
displayedMonthDate.setMonth(month);
renderHtml();
$cal.trigger('monthChanged', [displayedMonthDate]);
});
$cal.bind('showNextMonth', function() {
var month = displayedMonthDate.getMonth() + 1;
displayedMonthDate.setMonth(month);
renderHtml();
$cal.trigger('monthChanged', [displayedMonthDate]);
});
$cal.bind('setSelectedDate', function(ev, date) {
selectedDate = date;
renderHtml();
$cal.trigger('selectedDateChanged', [selectedDate]);
});
renderHtml();
});
};
})(jQuery);
function assembleDate() {
var d = new Date();
d.setUTCFullYear(arguments[0]);
// WTF, javascript! Zero-indexed month, really...?
d.setUTCMonth((arguments[1] || 1) - 1);
d.setUTCDate(arguments[2] || 1);
d.setUTCHours(arguments[3] || 0);
d.setUTCMinutes(arguments[4] || 0);
d.setUTCSeconds(arguments[5] || 0);
d.setUTCMilliseconds(arguments[6] || 0);
return d;
}
// js> assembleDate(2005,5,5);
// Wed May 04 2005 19:00:00 GMT-0500 (CDT)
// js> var parts = [2005,5,5];
// js> var d = assembleDate.apply(null, parts);
// js> d.toUTCString();
// Thu, 05 May 2005 00:00:00 GMT
# NB: this is CoffeeScript!!
# http://jashkenas.github.com/coffee-script/
# We assume that you're storing image files in a 'test-images' directory.
sys = require 'sys'
http = require 'http'
url = require 'url'
posix = require 'posix'
workingDir: process.cwd()
getImageName: (request) ->
requestURL = url.parse request.url
pathSegs = requestURL.pathname.split '/'
pathSegs.shift()
pathSegs.shift()
http.createServer((request, response) ->
imageName: getImageName request
headers: { "Content-Type": "image/jpeg" }
imagePath: workingDir + "/test-images/" + imageName
posix.cat(imagePath, "binary").addCallback(
(data) ->
response.sendHeader 200, headers
response.sendBody data, "binary"
response.finish()
).addErrback(
(err) ->
response.sendHeader 404, headers
response.finish()
)
).listen 8000
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>nginx</string>
<key>Program</key>
<string>/opt/nginx/sbin/nginx</string>
<key>KeepAlive</key>
<true/>
<key>NetworkState</key>
<true/>
<key>StandardErrorPath</key>
<string>/opt/nginx/logs/error.log</string>
<key>LaunchOnlyOnce</key>
<true/>
</dict>
</plist>
<%= 'This is a test by Geoff' %>
-module(web_server).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-define(OK, <<"ok">>).
%% API
-export([start_link/1, dispatch_requests/1, stop/0]).
%% gen_server callbacks
%% (Same old, same old. You can skip down to the handle/2 function...)
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link(Port) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [Port], []).
init([Port]) ->
mochiweb_http:start(
[{port, Port},
{loop, fun(Req) -> dispatch_requests(Req) end}]),
erlang:monitor(process, mochiweb_http),
{ok, []}.
stop() ->
gen_server:cast(?SERVER, stop).
dispatch_requests(Req) ->
Path = Req:get(path),
Action = clean_path(Path),
handle(Action, Req).
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', _, _, {mochiweb_http, _}, _}, State) ->
{stop, normal, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
mochiweb_http:stop(),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% This was ripped off from the following blog:
%% http://willcodeforfoo.com/2009/07/29/using-mochiweb-to-create-a-webframework-in-erlang/
handle(Path, Req) ->
CleanPath = clean_path(Path),
CAtom = erlang:list_to_atom(top_level_request(CleanPath)),
ControllerPath = parse_controller_path(CleanPath),
case CAtom of
home ->
IndexContents = case file:read_file("www/index.html") of
{ok, Contents} ->
Contents;
_ ->
"<html><head><title>Error</title></head><body><h1>Uh oh</h1></body></html>"
end,
Req:ok({"text/html", IndexContents});
assets ->
Req:ok(assets:get(ControllerPath));
ControllerAtom ->
Body = case Req:get(method) of
'GET' -> ControllerAtom:get(ControllerPath);
'POST' -> ControllerAtom:post(ControllerPath, decode_data_from_request(Req));
'PUT' -> ControllerAtom:put(ControllerPath, decode_data_from_request(Req));
'DELETE' -> ControllerAtom:delete(ControllerPath, decode_data_from_request(Req));
Other -> subst("Other ~p on: ~s~n", [users, Other])
end,
Req:ok({"text/html", Body})
end.
%% Helper methods:
%% Parse the request body as JSON
decode_data_from_request(Req) ->
RecvBody = Req:recv_body(),
Data = case RecvBody of
<<>> ->
erlang:list_to_binary("{}");
Bin ->
Bin
end,
{struct, Struct} = mochijson2:decode(Data),
Struct.
% Parse the URL path
parse_controller_path(CleanPath) ->
case string:tokens(CleanPath, "/") of
[] ->
[];
[_RootPath|Rest] ->
Rest
end.
%% Strip off the query string off the URL
clean_path(Path) ->
case string:str(Path, "?") of
0 ->
Path;
N ->
string:substr(Path, 1, string:len(Path) - (N+1))
end.
top_level_request(Path) ->
case string:tokens(Path, "/") of
[CleanPath|_Others] ->
CleanPath;
[] ->
"home"
end.
class Judge
def evaluate app
app.name == 'flowcoder' ? :winner : :boo
end
end
@app = self
@judge = Judge.new
@judge.evaluate @app
%% Damn, Erlang, I forgot my periods...
-module(flowcoder).
-compile(export_all).
read_post() ->
io:format("Thanks! We missed you!").
%% from my MacBook Pro