301 Redirects With Octopress on Heroku

I decided to move over my personal blog entries outside this blog. Following good migration procedure, I set up 301 Redirects. At first, my dumb self cranked up vim and created a .htaccess, then I remembered that this blog runs on Heroku, which is probably not using Apache (for obvious scalability reasons). After a quick heroku ps, I can see that the ‘thin’ application is serving my blog. thin --version reveals that I am running thin 1.2.6 codename Crazy Delicious.

Needless to say, htaccess wont work, so I must resort to using rack-rewrite[1].

I add the gem at the end of my Gemfile:

1
gem 'rack-rewrite'

Then I add my rewrite rules to config.ru (after the $root line)

1
2
3
4
5
6
use Rack::Rewrite do
  r301 %r{^/blog/2012/10/25/bliss-that-is-out-of-reach/?$}, 'http://blog.andrebrutus.com/2012/10/25/bliss-that-is-out-of-reach/'
  r301 %r{^/blog/2012/10/28/job-sins-from-the-youth/?$}, 'http://blog.andrebrutus.com/2012/10/28/job-sins-from-the-youth/'
  r301 %r{^/blog/2012/11/03/chronicles-of-a-bittersweet-travel-experience/?$}, 'http://blog.andrebrutus.com/2012/11/03/chronicles-of-a-bittersweet-travel-experience/'
  r301 %r{^/blog/2012/10/24/quote-from-job-2/?$}, 'http://blog.andrebrutus.com/2012/10/04/quote-from-job-2/'
end

Then download the rake-rewrite gem by executing bundle.

Finally, update your blog by rake generate and publish away! You can see the changes to both the Gemfile and confi.ru on my github commit

Footnotes:

[1] While definitely more verbose, this article helped me find the solution.

cURL PUT Request With P12 (PKCS #12) Certificate Using PHP

While working with some archaic API I was asked to upload files via HTTP using a P12 certificate. At first, phased and confused, I thought to myself: file uploads usually happen through a POST request using a form that has an enctype of multipart/form-data, or different protocols like (S)FTP, WebDav, etc. Remembering some academia on the HTTP protocol, I resorted to the PUT request, and it actually worked. So to save someone some time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$content = file_get_contents("/path/to/file_you_want_to_upload.pdf");
$stream_length = count($content);
$fp = fopen("php://memory", "rw");
fputs($fp, $content);
rewind($fp);
curl_setopt($ch, CURLOPT_URL, $url="http://some.url/file_you_want_to_upload.pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLCERT, "/path/to/certfile.p12");
curl_setopt($ch, CURLOPT_SSLCERTTYPE, "P12");
curl_setopt($ch, CURLOPT_SSLKEYPASSWD, "CertFilePassword");
// And if the HTTP endpoint requries HTTP Auth
//curl_setopt($ch, CURLOPT_USERPWD, $cfg['HTTP_AUTH_USER']. ":" . $cfg['HTTP_AUTH_PASS']);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_INFILE, $put_file_handle);
curl_setopt($ch, CURLOPT_INFILESIZE, $stream_length);
$result = curl_exec($ch);
if($result === false) {
  throw new Exception("Curl Error on PUT file: ". curl_error($ch));
}
curl_close($ch);
fclose($ch);
?>

This snippet opens a file, counts the bytes, opens a file stream (in memory) and passes that information into the CURLOPT_INFILE and CURLOPT_INFILESIZE parameters of the cURL API. This snippet throws, so you should use a try-catch.

An obvious improvement would be to use filesize() instead ouf count(), but my script generates files on the fly, so instead of resorting to slow I/O, I do things in memory. You could change $content = "my file contents"; and see its dynamic nature. If you will use it only for file system files, I do recommend using filesize().

Spell Check Using VIM

It should be no secret to anyone that my main editor for programming (and writing blog posts) is VIM. Given that I have allowed personal posts to occasionally feature on my blog, I have written some lengthy blog posts. Long posts usually mean lots of spelling mistakes, and there are some commands that have helped me on the way.

To enable spell check (will highlight misspelled words)

1
:set spell

Here’s a sample output:

Sample of VIM's spellcheck'

To advance to the next misspelled word

1
]s

or to go to the previous word

1
[s

To show spelling suggestions for currently selected misspelled word:

1
z=

Spelling Suggestions in VIM

And to add a word to VIM’s dictionary:

1
zg

And of course, to turn off spellcheck:

1
:set nospell

Also, if you don’t know it by now, this Blog runs on Octopress and is published via git. If you find a post that needs ‘refactoring’, feel free to fork the repository and do a pull request. Gotta love open source!

Creating a Virtualenv for Use With Django 1.4 and (Possibly) Heroku

Say you want to start a project and you want to use Heroku for your quick ‘proof of concept’. You will need virtual environment.

On my Mac 10.8.2, I did:

1
2
sudo easy_install virtualenv
sudo easy_install pip

Then to create the virtual environment called venv (while on my project folder):

1
virtualenv --distribute venv

Then to activate the virutal environment:

1
source venv/bin/activate

By now, my propmt’s prefix would be appended with (venv) and I am inside my virtual environment. I can now proceed to install Django, by executing

1
pip install Django

After installing Django, I can freeze the requirements so Heroku would know which packages to install whenever I do a push by executing

1
pip freeze > requirements.txt

and adding the output file(requirements.txt) to the repository.

By using a virtualenv, you can have different projects use different python installations(2.x and 3.x) in a single development machine, and also replicate your exact production environment. Heroku uses the requirements file to install the specific versions of the modules which in turn makes everything a replica of your development environment.

Coding Every Day

Today I begin my challenge to write code daily(outside of the code I write for work). The main problem with this decision is that I often don’t believe the code that I write just-for-fun to be “publish worthy”.

However, this way, the big brother effect will kick in and allow me improve my daily coding while (hopefully) helping out someone out there. As a result, you will see my newly renamed github (from anebg to abrutus) grow on a daily basis, and this blog will contain short snippets and explanations. Because this is such a big commitment, I command you as a reader and programmer to do the same, and I will link to your blog(yes, you are my new accountability partner).

So my plan is to pick up a book on a langugage I know next to nothing about (scala/clojure) and mark-down notes here for everyone’s reference.

Wish me luck!

The Broken Windows Theory and Software Engineering

Recently, I stumbled upon an interesting email. It was in Spanish(found it) so be merciful with me as I attempt to translate and paraphrase:

1969, Stanford: Professor Philip Zimbardo conducted an experiment in social psychology. He left two identical cars(same make,model, color) in two different neighborhoods(Bronx-NY, and Palo Alto-CA). Two identical cars in two neighborhoods with very different populations, along with a team of specialists in social psychology to study the behavior of people at each site.

It turned out that the car in the Bronx began to be vandalized within hours: lost the tires, engine, mirrors, radio. All that was usable was taken away, and what wasn’t usable was destroyed. The car in Palo alto remained intact.

Commonly, people attribute poverty to cause crime, but the experiment wasn’t over. With the Palo Alto car unscratched and the Bronx car destroyed, the researchers decided to break a window in the Palo Alto Car. The result was that this action unleashed the same process as in the Bronx: theft, violence and vandalism reduced the vehicle to the same state as in the poor neighborhood.

Why was the broken car window in a supposedly safe neighborhood able to unleash such a criminal reaction?

It isn’t poverty, it’s obviously something to do with psychology, human behavior and social relations

A broken window in an abandoned car conveys an idea of deterioration, lack of interest, carelessness that breaks codes of coexistence, and it resembles the absence of law, norm or rules. Every new attack suffered by the auto reaffirms and multiplies the idea, until the escalation of events, getting worse, becomes uncontrollable, leading to irrational violence.

In later experiments (James Q. Wilson and George Kelling) developed the ‘broken windows theory’, from a criminology point of view concluding that crime is higher in areas where neglect, dirt, disorder and abuse are higher.

This article got my mind running. What If the same principle is applied to Software Engineering?

Suddenly my mind wandered off to that function I left undocumented, that class that needed refactoring. I’m not a perfect programmer. Will the future programmers(or some newbs) vandalize my code? Will I be ashamed to look at my creation?

Probably. Also, you don’t need a “society” of programmers to make this theory a reality. Just you and your future you, looking back at beta version of your own self in code. You will see the broken windows, but will you fix those broken windows? Or, will they influence you to carelessness?

Some hope (from the Wiki article):

George L. Kelling [the author of the theory], was hired as a consultant to the New York City Transit Authority in 1985, and measures to test the broken windows theory were implemented by David Gunn. The presence of graffiti was intensively targeted, and the subway system was cleaned from 1984 until 1990.

According to the 2001 study of crime trends in New York by George Kelling and William Sousa,[3] rates of both petty and serious crime fell suddenly and significantly, and continued to drop for the following ten years.

And apparently similar success occurred in Albuquerque, Massachusetts(20% drop in calls to the police) and even the Netherlands.

Feel free to drop me a line in the comment section below.

UPDATE: From the comments (below and reddit), it seems that this topic was covered previously by the Pragmatic Programmer and I recommend you read it here.

On Blogging Engineering

You’ve landed. Here I blog mostly about issues that arise out of the technology I employ(Django, CodeIgniter, jQuery, Bootstrap) and the ones I’m learning (Scala and Ruby). Ocassionally, you’ll hear me describe architectures. Drop me a line in the comments, twitter or github. I’ll be around (I promise)

And here is a hello world for syntax highlighting:

1
2
3
4
5
6
7
// Operator for Overloading
object operator
{
  def operation(a: Int, b: Int) = {
    a+b
  }
}