CDMoyer's
Ramblings


15
May

Tweet :: Command-Line Twitter Broadcast with Readline Support

So, after giving Allan some feedback about the latest less project, Get More Honey, we chatted a bit and it came out that I’m a PHP guy, with a bit of a leaning towards CakePHP. But, I’ll fully admit that I love the ruby language, have played with it quite a bit, but simply never had an opportunity to write a rails app. People pay me to write PHP code. ;)

But, it did inspire me to fire up vim and write something in ruby. (Some day I’ll dust off RubyKnight, the chess engine I wrote in ruby after reading Behind Deep Blue) Here it is:

#!/usr/bin/ruby
# Written by Chris Moyer (chris@inarow.net // http://inarow.net/)
# Do with it whatever you want.  That's public domain, right?

require ‘readline’
require ‘rubygems’
require ‘twitter’

user = ARGV0
pass = ARGV1

if !user or !pass then
puts ‘usage: tweet username password’
exit
end

$0 = “tweet #{user} xxxxxxxx”
twitter = Twitter::Base.new(user, pass)

while line = Readline::readline(’(tweet)> ’) do
Readline::HISTORY.push(line)
if line.length > 140 then
puts “#{line.length – 140} characters too long, try again.”
else
begin
twitter.post(line)
puts “Tweeted!”
rescue
puts “Failed to tweet! (#{$!})”
end
end
end

puts “\nBye!”

It solves my problem of reading twitter via gtalk, and not wanting to open twitter.com to post… while hating when I underestimate the length of my message and being trunctaed. I can just let this run in window of my screen session, and tweet away.

So, I’d love to hear from the rubyists out there:

Posted In: · development    · ruby    · twitter   
Comments

14
May

Tweets Per Hour :: Flot & Twitter API Mash-Up (JSONP?)

Screenshot

TPH :: Tweets per Hour

So, as I mentioned before, Flot is an awesome jQuery plugin for making on-the-fly graphs. The twitter api supports a JSONP mode for its output. 100 lines of javascipt (well, 60 if you condense whitespace and braces, commas… less if the goal was to write small code).

What I don’t understand about what I’ve done here is JSONP, which I first read about here, at remy sharp’s blog… Why doesn’t it get more press. Solves the problem that I would mentally run in to all the time when considering various mash-ups and takes on various internet APIs, that of cross-domain limitations with XMLHTTPRequest.

The heart of the magic is demonstrated in this incredibly simple example:

$.getJSON('http://twitter.com/statuses/user_timeline.json?id=CDMoyer&callback=?',
      twitterCallback);

function twitterCallback(timeline) {
alert(’Twitter Username: ’ + timeline0.user.screen_name);
}

The magic happens in two places. First, jQuery replaces the ? in callback=? piece of the URL with a function name that references to the callback you pass to getJSON(). Second, the twitter API takes the callback parameter and wraps the JSON result structure in a function call with that name. The end result is that the JSON structure is passed to a function in the namespace of your document, circumventing the same-domain origin policy

So far Scoble has reached the highest TPH (8.0) I’ve seen, looking at various popular tweeters.


Posted In: · javascript    · development    · twitter    · jquery   
Comments

07
May

Flot - Slick jQuery Graphing Plugin

I read about Flot a couple months back and have wanted an excuse to play with it, as it looked pretty slick. Unfortunately, not actual opportunity presented itself, so I had to just make something up. The neat thing is how simple it is to make a basic graph, but how you can achieve some awesome effects through various options. The latter examples on the Flot site show of some great features.

Simple Flot Example


var data = [[0,0], [1,1], [4,5], [123,2], [12.3]];
$.plot($('#graph_area'), [data]);

And that’s it. You need to make sure and have dimensions defined for the target element, and Flot will automatically scale your graph based on your data. If you want more data sets, you pass in more arrays inside the secord argument. plot() also takes a third argument, options which lets you controll the appearance and more advanced features.

Posted In: · javascript    · jquery    · development   
Comments

01
May

10 Observations in one day with my Kindle

Freshly Opened Kindle
Freshly Opened Kindle

On Monday or Tuesday, the Kindle started showing up as in-stock and shipping at Amazon. Having read numerous blog posts about it, I took the plunge and ordered it with free 2-day shipping. It arrived Friday, and I’ve been playing with it quite a bit.

  1. The terms of use for the wireless make it very clear that Amazon reserves the right to modify or shut off the service at any point.
  2. While the bland white design didn’t appeal to me online, in real life it’s nice. It just seems to get out of the way, letting you focus on the content.
  3. I wasn’t sure at the time I purchased, but it does come with a nicely designed protective jacket.
  4. I’m sure this is the norm with modern e-book readers, but the screen is incredibly comfortable for reading. The claims of “electronic paper” are pretty accurate.
  5. Before it even arrives, Amazon adds “send to my kindle” and “send preview to my kindle” links for all books with kindle editions. I sent several previews on Thursday, it arrived Friday… I turned it on, registered it, and had content on the device a few minutes later.
  6. While not full-featured, the browser is more than adequate for mobile gmail, mobile google reader (they aren’t getting me to pay for blogs) and some light surfing. Reading the web in black-and-white is an interesting experience.
  7. I’m torn about the magazines. I subscribed to Fortune and compared to the hard-copy I read through at my dad’s house it’s a bit lacking. This is primarily because the kindle edition is missing all the photos. But it’s convenient, decent content, and I think I’ll probably keep the subscription.
  8. Two “next page” buttons, large and well placed, make it comfortable to read in a variety of positions. It’s a tad heavier than a paperback, but certainly lighter and more conventient than a hardcover.
  9. The convenience of sending documents for conversion seems worth the 10 cent charge to me, when I weighed the annoyance of getting out the cable and hooking it up and futzing around. (Perhaps I’ll break down later and do some bulk conversion)
  10. Amazon makes it very, very (dangerously) easy to buy content. The free previews (which seem to be in the 2-4 chapters) are enough to get you hooked… and then that “buy now” link appears at the end, making the full book a click away.

(Check out the kindle or see what’s on my kindle at my Amazon store.)

Posted In: · kindle    · review   
Comments

27
Apr

jThrottle - A jQuery Plugin to Throttle Big Loops

Uh oh!

Inspired by Oliver Steele’s Sequentially Library and this post by Felix Geisendörfer, I created a very simple jQuery plugin.

It provides a drop-in replacement for each(), which performs the loop in iterations and pauses between each iteration. You’d only do this if you are iterating over a largish set and performing non-trivial operations. Basically, if the browser freezes, this is a decent solution as the call to setTimeout() allows the browsers UI thread to get a slice of the action and prevents spinning cursor syndrome.

If you wrote:

$('foo').each(function () { alert($(this).html()); });
Now you write:

$('foo').throttle(function () { alert($(this).html()); });

Or:

$('foo').throttle(
		function () { alert($(this).html()); },
		{per: 100, pause: 10});
Posted In: · javascript    · development    · jquery    · projects   
Comments

26
Apr

AutoBlogger Update :: 0.9.2

Version 0.9.2 of AutoBlogger is now available.

This is the tiniest of bug fix releases. Now, whenever new photos are processed, all pages are rebuilt. This keeps the archive pages from becoming stale.

AutoBlogger Site: http://www.inarow.net/entries/projects/one_evening/autoblogger/
Grab it: Download Tarball or Anonymous SVN (svn co svn://inarow.net/trunk/autoblogger)

Posted In: · autoblogger    · projects    · one evening   
Comments

17
Apr

Link Attack II

Screenshot of MikeOS
MikeOS

MikeOS
If you like to read code, this is the OS for you. It’s a simple 16-bit OS written with the goal of demonstrating the basics of OS development. I’m not much of an assembly programmer (at all), but I was able to grab the tarball and read through, and learn a few tidbits right off the bat. Oh, and it’s got tetris. ;)

Jones Forth
Similar to MikeOS, Jones Forth is a wonderfully literate implementation of a FORTH compiler. You can just jump right to the source file and start learning. To quote the author:

FORTH is one of those alien languages which most working programmers regard in the same way as Haskell, LISP, and so on. Something so strange that they’d rather any thoughts of it just go away so they can get on with writing this paying code. But that’s wrong and if you care at all about programming then you should at least understand all these languages, even if you will never use them.

Three Small Javascript Libraries
A good post by Oliver Steele, describing three interesting libraries that really flex a bit of javscript, beyond the everyday DOM manipulation. Fluently – which allows you to easily create “chainable methods” (ala jQuery), MOP JS – which allows for some slick metaprogramming around asynchronous calls, and Collections JS – implements some nice utilities for collections.

TaffyDB – A Javascript DB
At first, my reaction to this was ,“Why?!” But then I mulled it over a bit more. I can see quite a few uses for this, especially in this modern era of “never reload the page.” I’m envisioning stateful browser apps neatly keeping their state, and transacting with the servide data store through tidy little JSON snippets. [via Joe’s Blog]

Posted In: · links    · development    · javascript   
Comments

03
Apr

Stupid Comma!

Normally, when defining a large array in PHP, I’ll write it like so:

$foo = array(
    'some_key'  => $val,
    'other_key' => $val2,
    'also_this' => $val3,
);

Note the comma on the ‘also_this’ line. I’ve gotten into this habit, as it makes it much simpler to later rearrange the order of these elements or add another. As I’ve been playing with jQuery, I’ve had cause to create assorted JSON data structures, and wrote a bit of code like so:

$('#slider').slider(
    {
        handle: '.handle',
        minValue: 0,
        maxValue: 9000,
        steps: 9,
        stop: slider_slid_callback,
    }
);

(See the trailing comma?) Well, this works great… in FireFox. In IE?

Line 13
Error: expected identifier, string or number.

Normally I’d complain about IE here, but looking at Introducing Json I see this defintion for a JSON object (doh!):

 object
    {}
    { members } 
members
    pair
    pair , members
Posted In: · development    · javascript   
Comments

05
Mar

reCAPTCHA — Fight Spam, Read Books

In a startling development (to me), my small blog started getting spammed like crazy. Out of 100+ posts, a handful were legitimate. After going through the process of manually deleting them all, I decided to invest a bit of time in a CAPTCHA system for my blosxom blogging software. Having seen the reCAPTCHA interface on several sites, and read about it before, I decided to start there.

Basically, reCAPTCHA provides some incredibly simple APIs to add a CAPTCHA to your site. The neat part about it, though, is that the images presented to the user are actually difficult to scan words from real-life books. The results of people submitting these CAPTCHAs are combined to improve the digitization of hard-copy archives. The learn more page on the reCAPTCHA site has a more detailed explanation.

Implementation

Step 1 – Sign Up, Get Keys

Here

Step 2 – Add the the interface to the front end

	<script	type="text/javascript"
		src="http://api.recaptcha.net/challenge?k=$MYKEY">
	</script>

This javascript (and iframe) API takes several parameters, allowing you to customize the look and feel of the interface.

Step 3 – Validate the submitted reCAPTCHA

As bloxsom is written in perl, I went with the CPAN module Captcha::reCAPTCHA.

	use Captcha::reCAPTCHA;
	my $rec = Captcha::reCAPTCHA->new;

my $rec_res = $rec→check_answer(‘6LdWHQEAAAAAAORoD7pXt_BAHRdsZ2GPjmcFdWWi’, $ENV{’REMOTE_ADDR’},
param(‘recaptcha_challenge_field’), param(‘recaptcha_response_field’));

// [snip some lines]

if (!$good || !$rec_res→{is_valid}) {
$comment_response = “Some required fields were missing.”;
if (!$rec_res→{is_valid}) {
$comment_response = ‘Please verify that you are human, with the reCAPTCHA!’;
}
}

Obviously, not the most elegant code, but it was an incredibly simple process… and my blog has been spam free for 3 weeks!

Posted In: · development    · perl   
Comments

08
Feb

jQuery Rocks

jQuery rocks. After playing with YUI, EXT, and Mootools, and using Prototype/Scriptaculous for over a year, I am now completely sold on jQuery. It was a a post on err.the_blog, which first got me to take a look.

The Basics

As an example of why I am so enamored with jQuery, this simple javascript calendar required so little javascript, for so much functionality, that it blew me away. The whole idea is that you can chain various methods onto the results of simple selectors. Methods for animation, manipulation, and bindings are all provided. A snippet from my calendar example:

jQuery(function () {  // jQuery() sets a callback for when the page is ready to go
	$('#calendar .row .day').hover(
		function() { $(this).addClass("active_day"); }, 
		function() { $(this).removeClass("active_day"); }
	)
}

So, a simple CSS selector, and a utility function that automatically binds a function to the mouseover and mouseout events of each matched element. addClass() and removeClass() make it incredibly simple to provide visual user feedback. The simplicity of traversing the DOM in this manner, with #ids, .classes, and tag types, is incredible. Enhanced selectors such as :checked and :text are included to make finding the right element easy.

Simple Animation

As another example, the calendar includes a hidden div positioned at the top of the window. When a message needs to be shown to the user, this function takes care of showing the div, animating it’s appearance, updating the textual message, rounding it’s corners, and then hiding it again:

function show_results(str) {
	$("#results").html(str);
	$("#results").corner("bottom");
	$("#results").slideDown();
	setTimeout(function() {$("#results").slideUp("slow");}, 4000);
}

Unobtrusive

I think what makes jQuery stand out to me, is how it really lends itself to the unobtrusive javascript paradigm. The better you semantically mark up your page, the more easily jQuery is to add to the page.

Posted In: · jquery    · javascript    · development   
Comments