Monday, December 30, 2013

Beautifying personal & professional public links using your own domain

In an attempt to make links to my public persona A) easier to remember and B) easier to share, I cooked up a 25 line Sinatra app that can be used to do just this. I love Sinatra since the DSL makes writing simple apps like these so easy.

You can find the code here on github.

I hosted the app on a digital ocean instance and cooked up these links:

Sunday, October 6, 2013

Getting started with animations on Android

Want to get started with animations on Android? It turns out, things are surprisingly easy.


There are two ways to create animations:
  1. Using OpenGL --- See documentation here
  2. Using built-in View animations --- More here and here.
I explored the later. Basically the code boils down to the following:

1- Create an animation template. For example the following can be used to rotate an imageview back and forth:
2- You can then apply the animation to the view using the following code:
I created the following app to demonstrate various animations on arbitrary images:
Read the README.md for more details.

Twitter is Hiring! A tech talk @ McGill University


Check out the (much nicer) keynote version here.

Saturday, September 7, 2013

Developing Trackpad: An 18 second Vine documentary

My goal was simple. I wanted to be able to control my Mac's mouse from my Nexus 7. These following Vines document an evening's attempt at that.

Phase 1 - Basic Android application. Just getting set up.

Phase 2 - Server setup. My mouse now speaks http.

Phase 3 - Hook server up to application. World's hackiest wireless mouse.

Check out the android app here
Accompanying scala Play service here.

Monday, September 2, 2013

Hacking the coding interview

The technical interview process used to hire software engineers/developers hasn't changed much over the years. A couple of coding problems to solve on a whiteboard for roughly an hour a piece over the course of a day. Intersperse lunch & bathroom breaks for fluid I/O needs. Leave feeling exhausted, perhaps regretting how silly you were to forget the algorithm for merge sort on that 3rd interview.

Over the last 7 years I've given and received enough interviews to see a couple of patterns emerge. I think it's rather unfortunate, but proper preparation and foreknowledge of "the process" can make as much difference as simply being the right person for the job. As a result, I've also seen a lot of false positives & negatives occur. I'm really interested in getting to the bottom of this since the most important decision a company makes is who to hire. One rock-star engineer you can trust to get the job done is worth five mediocre ones. Hiring the wrong people can have disastrous consequences on effectiveness, morale and culture.

What I'd like to do is spend the remainder of this post being a hacker who's goal is to get the best offer at a company possible (compensation, position). We will employ all means at our disposal, save for anything dishonest. Think of this as attacker-centric threat modeling. Once we gain an understanding of how one can optimize & exploit the existing process, we can look at flaws and propose a fix.

Know what you're up against
These are the typical steps in the interview process from first contact to offer letter:

At any point, the process can dead end --- for a variety of reasons.  There's a lot to say for each step, but I'd like to focus on the on-site interview for now.

There's a good bit of variety in how on-site interview panels are set up, but at the end of the day this is what will be used to judge whether you get a job or not:
  • 3 to 6 interviewers. Mostly developers, usually includes a hiring manager and sometimes product manager(s). Sometimes you will have 2 interviewers at a time; this usually means a junior interviewer is "shadowing" a more senior one.
  • 45-60 minute interview sessions in a room with a whiteboard. The whiteboard may be replaced with a laptop in some cases, but this is less common.
Some companies are moving away form the last point and doing things like pair programming and live code debugging. I think this move is very interesting, but I haven't seen this applied in a scalable way at larger companies.

Before the Interview
Defining a model for interviews success
I propose the following model as predictor of offer quality:

# of offers = (coding interview skill) x (raw intelligence/skill) x (# companies interviewed)
and
offer quality (position & compensation) = (# of offers) x (Experience in CV)

Out goal is to optimize for offer quality. More offers = more choice = more negotiation leverage = higher pay/better position.

Assuming we can't increase the interviewer's raw intelligence or experience in a short time span, we will focus on the following:
  1. Build a solid "lead generation pipeline" to increase # of companies interviewed
  2. Train the interviewer's brain to be a "coding problem pattern recognizer" to improve coding interview skill
From here on out let's assume you have 1 month to prepare for the interview, nothing lined up, and about 2 hours a day to spend, every day, during evenings and weekends. We'll also assume you're working at a job during this time. Let's be clear, your success will be directly correlated to how much time can be spent studying & on LinkedIn. Remind yourself how badly you want this.

Generating leads
If you're buying a house, you'd be silly to put an offer for the first one you see. Likewise, with interviewing, you should look at as many options as possible. Lead generation is the idea of advertising yourself in such a way that you generate maximum possible interview interest. How can we do this?
  1. LinkedIn --- Update LinkedIn profile as soon as possible to highlight your latest work. Also start reaching out to all friends you have to see if their company is hiring. Get co-workers to write recommendations for you; the more the better. 
  2. A-List --- Identify the companies on your "A-list", places you'd really love to work. If you have any contacts at these companies, reach out to them expressing interest early on. Referrals can work on the inside to get you an interview. Their past experience with you is usually seen as huge plus that can override poor interview feedback in some cases. If you are applying cold to companies on your A-list, go to the careers\job section of their website (these always exist) and apply directly.  
  3. Interview everywhere --- If you're already getting InMail requests on LinkedIn, reply to all of them (even those that you're not interested in). Many requests come from come from headhunters who can connect you with companies you might care about interested in. 
  4. B-List --- For companies that you wouldn't want to work at, but would be easy to interview at, add these to a "B-list". We'll want to interview at these places first to use them as "practice runs".
The idea is that after a couple of weeks you should have a couple of B-list phone screens & on-sites done. If any A-list interview opportunities come up, push them out so that you can have enough B-list preparation. You might even have a couple of offers by the time you start "A-listing". 

Training your Brain
In parallel with lead generation, we need to train your brain to think in terms of coding interviews. This is where you will spend the majority of your time every day. This way of thinking is extremely different from how you approach writing software on your own with an IDE & internet connection. So different, that this is the number one reason for false negatives in interviews.
  1. Language --- First, pick the language you are most comfortable with. I've seen many candidates go into an interview and decide on the spot they wanted to use Scala instead of Ruby. Or C instead of Java. Mistake. Pick one language and stick with it for all your time studying & interviewing. Know the ins and outs of the language so that you can write code without hesitation. Remember, time is limited in interviews, and you don't want to waste it fumbling. Consider picking a language with good library support. Using the provided HashMap in Java beats writing your own from scratch in C.
  2. Study Material --- Next, get a good set of sample interview questions with solutions. We're going to use multiple sources for this. Our mainstay will be Cracking the coding interview which neatly divides problems between discrete domains (get a physical copy off amazon). We'll also be looking at the Berkely cs riddles forum and codercharts.com as backups.
  3. Paper --- From here on out we will only be coding on paper since this mirrors the interview environment best. Being near a computer helps to look up syntax/algorithms, but write everything out by hand. This will help greatly building muscle memory for algorithms. 
  4. Time --- Every day, you should aim to get 4-5 interview questions completed. You will do this until the last day you accept an offer. If you have 15 minutes to spare, do an interview question. This is your new hobby, which you will eat, sleep and breathe.
  5. Work & Study --- In order to buy time for yourself, you'll need to stop doing any overtime at your current job\school. Do the minimum possible to meet your commitments, but no more. Your priority now is your job hunt.
  6. Focus Areas --- In "cracking the coding interview", questions are divided between different categories which require specific approaches we'll want to master. The most important types of problems to master are(in order):
    1. Primary: Trees & Graphs, Recursion & Dynamic Programming, Arrays & Strings, Sorting & Search, Stacks & Queues, OO Design, Linked Lists,  Bit Manipulation, 
    2. Domain Specific (depends on job): Math & Prob, Scalability & Memory, Testing, Databases, Threads & Locks
  7. Bread & Butter Algorithms --- The following algorithms are useful to know in an interview, but you might not use day-to-day: Breadth-first search, Depth-first search, Dynamic Programming, Binary tree traversal, Merge Sort(asked a lot for some reason), Djikstra's algorithm, Tail recursion, Threading & concurrency patterns. 
    • I've seen that the first 4 algorithms in the list apply to a disproportionate amount of interview questions (~1/3).
  8. Tracking --- Track your progress as you go through problems every day. Do all your work in a notebook where you write down each problem on a separate page; this will be useful as you start to see patterns between problems. Keeping a sheet that records all the problems you go through helps build confidence and a sense of accomplishment. Here is an example:

  9. Problem solving approach --- Never, ever jump straight into a question. Think of exactly what clarifying questions you would want to ask had this been an in person interview. Many candidates get dinged for jumping into a question they don't really understand. For each interview question you study, clearly define an interface for the algorithm. If you can think of multiple solutions, learn to pick the best one(see next point #10). Explicitly call out edge cases as you're coding. Once you finish writing code, you're not actually done; verbally go through the code you wrote and confirm it does what it should. Catching bugs in your code without being told is a plus.
  10. O(N) Everything --- Understand Big-O notation and how to apply it to any algorithm you write. Time and space complexity analysis is always asked as part of the coding interview. For every coding problem you solve, you should learn to subconsciously apply this when evaluating the optimal approach.
  11. Talk --- Your ability to verbally communicate your thought process during the interview will be a huge asset. Practice talking to yourself while coding (maybe using the inside voice if you're shy).
  12. Progression --- Your progress will be very slow at first. Painfully so. You won't remember basic algorithms from CS 101 and you'll feel stupid and scared about the interview. You'll be very nervous until you start doing some of the B-list interviews. And then, all of a sudden, things will start to click and you'll start seeing patterns. A scary looking graph question is a simple matter of applying BFS (which you can write up blindfolded now), linked list questions will be a joke, you will be a master of recursion... etc. 
  13. Soft Questions --- You will probably get "soft" questions and these should be part of your training regimen. You should have well thought out, convincing, canned answers for some of the following: ["Describe the current project you're working on", "Describe a time you had a disagreement with a colleague and how you handled it", "What's your biggest weakness", "Why do you want to work here"]. Some of these questions are valid (always know why you want to work at a place you're interviewing). Some are bullshit since if you're caught off guard, you can give a terrible answer that ends up inadvertently hurting your chances.
  14. Puzzle\Riddle Questions --- are pure BS in my opinion, and generally acknowledged to not be a very good indicator of job performance, but you will see them. The key to these is being very methodical, asking smart questions and hoping the problem doesn't have an impossible trick. I wouldn't spend too much time studying these, but you should look at a couple.
  15. Study human relations --- Not, like, the whole field :) But read How to win friends and influence people by Dale Carnegie.  Many points brought up in this book are directly applicable to the "soft" side of the interview process. Seriously, consider this mandatory reading.
  16. Remove Fear --- If you're lucky enough to have an offer from another company before going in to interview, you will do amazing. There will be no fear to hold you back, your self confidence will be sky high and you'll simply do your best without worry. If your lead generation is able to yield enough interviews, this might happen, and you'll be golden.
During the interview
So you've been training hard for a couple of weeks and your lead generation pays off. You land an onsite interview and you want to do well. You'll always be nervous beforehand, but the trick is to A) let your training kick in and B) apply a deep understanding of human relations.
  1. Communication --- ABC. Always be communicating. Candidates that get a problem and write code for 45 minutes without saying a word will not get hired. Communication abilities are as important as coding abilities in a software development environment. Ask questions. If you get stuck, spell out your exact thought process and what you're trying to do next. Even if you don't solve a problem, being able to explain what's going on in your head counts for a lot.
  2. Getting stuck --- You're asked to solve a problem, and you pull a complete blank. You force yourself to solve the problem in a way you're not sure will work. After 20 minutes, you coding in circles. This is a very common pattern and results in a poor interview. In order to recover, communicate as much as possible you thought pattern. Spell out all assumptions you've made up until this point and question them in a conversational way with the interviewer. In the end, interviewers will usually give hints if they see that you're too stuck.
  3. Build Rapport --- If someone likes you, they are more likely to give a "hire". This doesn't happen all the time and interviewers might not realize that it happens, but it does play a role. Two things to try in every interview are 1) try to get the interviewer to laugh and 2) try to get them to tell you something personal about themselves. Doing this at the beginning of the interview is best, and it only works if it feels natural (as with all things).
  4. Hand Writing --- Write neat code. This sounds silly, but you will get dinged if your code is illegible and hard to understand.
  5. Solve what's asked --- Don't try to solve problems that aren't asked. It's very easy to start solving a problem, and suggest going down a very complex route. Make sure you're only solving what's being asked, otherwise you can hurt yourself. Sometimes interviewers will let you go down a winding path if they haven't prepared for the interview. Which leads to my next point ...
  6. Simplify --- When interviewers propose a problem, you can ask a clarifying question that steers the problem in an easier direction by calling out simplifying assumptions. The opportunity to do this comes up more often than you'd think and is easier the more you study. Ex: Instead of coding a sort method from scratch, assume you can use the inbuilt sort method. Boom, you saved 20 minutes.
  7. Never Argue --- Never argue with the interviewer, even if they're wrong. You should politely point out if you think things are obviously incorrect, but if they insist they're right, don't press the issue. The interviewer's pride is not to be trifled with, and doing so will always backfire. Agree that you're wrong and move on; the interviewer usually realizes things on their own after.
  8. Don't eat too much --- So you're interviewing at Google and lunch time comes around. Food is free so you eat way too much, especially carbs. Your post-lunch interview is a disaster since you have trouble focusing due to lethargy. True story.
  9. Keep notes --- Bring a notepad with you and write the names of each of the interviewers you talk to during the day. Writing their name down at the beginning of the interview looks professional and will help you remember their name during the interview. Once the interview is done, write what question they asked you and how you think you did for each question. Be self-critical and drill into areas you think you were weak in future studies.
  10. Get cut short --- If you're scheduled for 6 interviews and you do 3, this usually means you got cut short. That is, your performance was so bad, someone felt it was a waste to have 3 more people interview you. This sometimes happens for the wrong reasons, so don't feel too bad. Keep calm, keep training.
Conclusion
In summary, the real hack to the coding interview is that if I have a big pipeline of companies all using this interview technique then if I screen at Company A on Tuesday and bomb out on a question, I may well get the same question on Thursday from Company B. Company A evaluates me to be low skill and Company B evaluates me to be high skill. Sooner or later, someone will ask me questions I know and I'll be evaluated as high skill.

We should presuppose this happens, and focus on building "pattern recognition" before even entering the first interview. The faster the interviewee gets to "peak pattern" (a level that varies by individual) the more offers and leverage they have.

The fact that I can write this, and it's true, is the saddening fact I'm trying to change.

Next Steps
I'll probably add to this over the coming days if I can think of more. I'd like to get feedback and dissect some of what's going on here. A lot of what I'm suggesting to do is pretty extreme. A lot of the skills here are not something you learn by doing a standard software engineering job (or get coming out of college). It's especially hard for more senior engineers to do technical interviews since most have limited time due to familial obligations and haven't taken CS 101 for quite some time. 

I think there is a better way, and I hope to find it. 

Sunday, September 1, 2013

Triggered breakpoints in Android Studio

I found a nice timesaver in Android Studio. The IDE can automatically set a breakpoint whenever an exception is thrown. This is instead of waiting for one to happen, looking at the callstack, manually placing a breakpoint, restarting the debugger and trying to repro.

To do this:
1- Start the debugger

2- Click "View Breakpoints"

3- Check "Any Exception"

4- You'll see a triggered breakpoint appear any time there is an exception

Saturday, August 31, 2013

The speed of trust

Stephen Covey on the importance of trust:
"It’s ironic, but from my experience around the world, Sarbanes-Oxley compliance (or its equivalent) has eclipsed the focus on the mistakenly so-called soft stuff, like trust. CFOs and auditors have replaced people developers and strategic-minded HR practitioners in the throne room. At the same time, one of the hottest topics today is ethics— ethics discussions, ethics curriculum, ethics training, codes of ethics.  This book shows that while ethics is fundamentally important and necessary, it is absolutely insufficient. It shows that the so-called soft stuff is hard, measurable, and impacts everything else in relationships, organizations, markets, and societies. Financial success comes from success in the marketplace, and success in the marketplace comes from success in the workplace. The heart and soul of all of this is trust. 
 
This work goes far beyond not only my work, but also beyond anything I have read on the subject of trust. It goes beyond ethical behavior in leadership, beyond mere “compliance.” It goes deep into the real “intent” and agenda of a person’s heart, and then into the kind of “competence” that merits consistent public confidence. Just think about it— whether you define trust as mutual confidence or loyalty or ethical behavior, or whether you deal with its fruits of empowerment and teamwork and synergy, trust is the ultimate root and source of our influence."

The SPEED of Trust: The One Thing that Changes Everything 

Saturday, August 24, 2013

Formatting code blocks from Kindle

I was ramping up on android using a Kindle book and realized Kindle for Mac app does a terrible job of copy/pasting contents to an IDE/text editor. I created a simple ruby script which tries to properly format code blocks copied from the Kindle app and then replaces the contents of your clipboard with *somewhat* better formatted code. Not perfect by any means, but made my life a little easier. 
 
Before:












After:























Check it out on github -> here <-

Saturday, July 13, 2013

Scheduling background tasks in Play made easy: A mailer bot example

It took a little while for me to figure this out earlier, so I thought I'd share how to easily schedule background tasks in your Play application. Let me illustrate with an example that will send an email to a user every 5 seconds. If you follow all the steps below, you should have your very own spam bot up in no time.

1- Create a new play application in scala
> play new background-email
2- Let's set the Global object location for our project. In your background-email/conf/application.conf file, make sure you have the following set:
application.global=Global
This will tell Play where to look for the Global object class of our application.

3- Under background-email/app/ create Global.scala. This file is loaded at application start time and the onStart method is where we can add calls to schedule tasks. In the example below, we'll have onStart call startAwesomeBackgroundTask which will schedule periodic email sends. Note: If you want this example to work, create a gmail account and replace "user@gmail.com" with your username and "password" with a the real password.


4- Before we can run our code, we'll need to add the right dependencies to our project. Update background-email/project/Build.scala to include a reference to org.codemonkey.simplejavamail:

5- You should now be able to run the application and see it in action:
> play start


Voila! From the console output you should be seeing an email sent every 5 seconds. The proof is in the pudding:



*The above instructions work as of Play 2.1.2.

Monday, May 27, 2013

Visualizing Twitter geo data using Play 2.1 & heatmap.js

My latest weekend project involves visualizing real time Twitter geo data using heatmap.js:


I'll be hosting the app here for the next couple of days: ignite.phyous.com

Check out the code on github if you'e curious: https://github.com/phyous/ignite

Saturday, May 4, 2013

Mining geo data from Twitter's API


Hot off the press, a script that is able to gather large-ish amounts of geo tagged tweet data from Twitter's public API. Running for 24 hours will yield ~300MB (~6 Million Tweets) in the following format

timestamp    tweet_id           tweet_language    country    lat        lng
1367706951 330813049193762816 es ES 39.4643 -0.3548

For more details check out: twitter-geo-data on github.

Saturday, March 30, 2013

Grasp: A Leap Motion mouse controller for OSX


Check out the code here: https://github.com/phyous/grasp

Developing for the Leap Motion controller in Scala


I just got a hold of a Leap Motion controller today and I have to admit it's a neat little device with a lot of potential. The first thing I did was figure out how to interface with the device using Scala. Here are some quick pointers on how to get setup.

Before reading further, entire process I outline below is summed up in the following github repo. You can clone it and run ./install then ./run to produce the following results:


Instructions

1- Download the SDK here.

2- Assuming you have maven installed, create a project using the following command
mvn org.apache.maven.plugins:maven-archetype-plugin:2.2:generate \
-DarchetypeGroupId=org.scala-tools.archetypes \
-DarchetypeArtifactId=scala-archetype-simple \
-DarchetypeVersion=1.3 -DgroupId=leap-scala \
-DartifactId=leap-scala -Dversion=1.0.0 -DinteractiveMode=false

3- Install the leap motion sdk jar in your local maven repository (found in the sdk package from step #1 under /LeapSDK/lib/LeapJava.jar). Use the following command:
mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
    -Dfile=PATH_TO_JAR \
    -DgroupId=com.leapmotion.leap -DartifactId=leapMotion \
    -Dversion=1.0.0 -Dpackaging=jar

4- Add a reference to this jar file in the leap-scala/pom.xml that was created in step #2.
    
    <dependencies>
        <dependency>
            <groupid>org.scala-lang</groupid>
            <artifactid>scala-library</artifactid>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupid>com.leapmotion.leap</groupid>
            <artifactid>leapMotion</artifactid>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

5- Write some code for capturing events from the device. Here are some snippets from the leap provided samples I ported to scala:


6- Once you have some code, you can bundle it along with the leap motion library in a "fat" jar using the maven-assembly-plugin. Check out a sample pom.xml that does this here. You can then bundle the app using the following maven command
 
mvn install

This will produce a jar file called "leap-scala-1.0.0-jar-with-dependencies.jar" under the target folder.

7- Once your code is compiling, it's time to run. You'll need to point the jvm runtime to the native leap motion libraries for interfacing with your OS. On OSX, this is a file called libLeapJava.dylib found in the same directory of the SDK as the jar file. Here is how you would run your app once it's compiled:
 
java -Djava.library.path=".:./libs" -jar target/leap-scala-1.0.0-jar-with-dependencies.jar

Using the code above, you should be able to see input directly form the device on your console.

These instructions were generated while developing on OSX. Things might need a little bit of tweaking if running on other platforms.

Thursday, March 7, 2013

How to pretty print JSON from the command line

JSON has become one of the main formats for exchanging data through HTTP APIs. Being able to request and properly print json in your console is useful from time to time. Here are three ways to easily "pretty print" your data.

Option 1 - Simple formatting using python 


If you have access to python on your system, simply add an alias to "python -mjson.tool" to pretty print any well formed json. Execute one of the following commands to add the alias directly (depending on whether you use bash or zsh):
See an example in action:

Option 2 - Prettyjson: a colorized option


prettyjson is a node.js package that you can call form the command line to get colorized and bracket stripped json printed in your CLI.

To install:
Once installed, you can try it out. Here is a before shot:

And after:

As you can see prettyjson does a good job of stripping superflous brackets and quotes. 

Note: If you can't execute prettyjson after installing it, make sure the node package manager bin folder is in your path. You can do so by adding the following to your .bashrc/zshrc:
export PATH=/usr/local/share/npm/bin/:$PATH

Option 3 - underscore-cli


Yet another node.js based option is the underscore-cli package. It doesn't strip some of the less useful json characters form the display like prettyjson, but it does colorize your text and it has other powerful features.

To install:
sudo npm install -g underscore

Underscore pretty formatting in action:

It's not just pretty printing that makes this package neat, you can extract specific portions of it as well:

Head on over to ddposon's github page for more details.

Sunday, March 3, 2013

Babel-hose: Real-time Twitter translations


"Now the whole world had one language and a common speech." -- Genesis 11:1

This was a weekend project of mine which combined Twitters streaming API and Bing translator allowing you to understand what's happening everywhere in the world in real time in your native language. This project leverages the recently released hosebird framework for easy access to the sample and filter streams.

Getting started with the Bing translator API


Bing Translator is the best freely available machine translation API that I know of. If you're interested in getting set up to use the API to make your own translation enabled apps, follow this guide.

Create an Azure marketplace account

1- Go to http://datamarket.azure.com/ and login using a Microsoft live account. If you don't have one, you'll need to create one beforehand. You can do that here.

2- Complete the registration:


3- Once logged in, head on over to the bing translator subscription page and select the free 2,000,000 character/month subscription package.




4- If you go back to your account page under "My data" you should see the following:




Create an Azure application

Once you have an Azure marketplace account with a subscription to Bing translator, the last step is to create an application. By doing this, you'll have a client key and secret you can use to call the API. 

1- Head on over to the application registration page. Once there, fill out all the necessary information. For Bing translator, you won't be using a redirect uri (even though it's mandatory). You can put any valid URI you want to complete the form. ** Before hitting submit, copy the Client secret and Client ID. We'll need these later.

2- If you go back to the application registration page, you should see your app show up:

Call the API

Using the client key and secret from above, you have all you need to call the API. If you're going to be implementing a client to call the API yourself, you'll need to first authenticate in order to get an access token, then use that in the header of your requests for authorization. 



I wrote some sample code(here) that retrieves the access token, before realizing there was a really great client for the translator written already called microsoft-translator-java-api. Here is some sample java code using this library which takes care of authentication and translation requests under the covers:


Here is a more involved project that involves Twitters streaming api and bring translator:

Here are some additional resources you might find useful:

Bonne Chance! Que la force soit avec vous.

Wednesday, February 6, 2013

Adding code snippets to your blog


When writing technical articles about programming, one needs to add code snippets for reference from time to time. The following post highlights two methods I find both simple and easy to use. 

Github Gist



Think of a Gist as a single source controlled file that can be edited, cloned and shared easily. This is one of my favorite options for sharing small code snippets. It has the added advantage of being version controlled as well.

Instructions
1- Head on over to gist.github.com
2- If you have a github account (which you should) sign in. Start by adding a file name for your gist; the syntax highlighting will automatically be detected by the extension:



3- Make sure to create the gist as "public". Once you do so, you'll see a "embed this gist" link ont he left hand side in the following format:
<script src="https://gist.github.com/<user_id>/<gist_id>.js"/>



4- Copy that and embed it in your blog. Here is an example with some ruby code:

SyntaxHighlighter



If you don't want to bother with an external service and you'd rather host your code as part of your site, there is another popular option called SyntaxHighlighter. It's essentially a set of javascripts you can add to your blog/website to easily display syntax-highlighted code in a variety of languages.

Instructions
(based on original instructions from Alex Shirmanov)
1- Go to your blog's html source and add the following in your <head> section. 
<!-- SyntaxHighlighter -->
<!-- 1- Core javascript and css -->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/> 
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCoreDefault.css' rel='stylesheet' type='text/css'/> 
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js' type='text/javascript'/> 
  
<!-- 2- Brushes -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>  
  
<!-- 3- Activate SyntaxHighlighter -->
<script language='javascript' type='text/javascript'> 
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>
Note #1: To edit the layout of a blogger blog, go to Template -> Edit Html
Note #2: If you have your own hosting capabilities, you might want to upload these files to your own server

2- Notice that in the brushes section (#2) we are loading various javascripts for different programming language syntaxes. For a full list of what's supported, see here. If you need support for a given language, just add an additional reference to shBrushXXX.js where XXX is the language you want support for.

3- We're now ready to add code snippets to your blog. You can do so easily by adding the following html (replacing brush_name with the language of your code snippet):
<pre class="brush: brush_name">
// Enter code here
</pre>

Here is an example with class="brush: scala":
// Hello world in scala
object HelloWorld {
    def main(args: Array[String]) {
      println("Hello, world!")
    }
  }

Happy blogging!

Tuesday, February 5, 2013

Multi-threading in JRuby

The traditional Ruby you might be used to running (along with other interpreted languages such as python) make use of a global interpreter lock which ensures that only one thread can interpret code at any given time. In Ruby 1.8, the process is only allocated one OS thread meaning any attempts at parallelism are basically useless. In Ruby 1.9 things were improved slightly; the GIL still only runs on one thread, but the process can take advantage of multiple threads. This means that anything I/O bound can run concurrently (database queries, network requests) but you won't be able to make effective use of the processing power of all of your cores.

JRuby on the other hand, is built upon the JVM. One can make use of "true" native threads which are able to run concurrently with you parent thread.

To visualize how this works check out this diagram:


Read more about the GIL here (from which I borrowed the above diagram).

Setup

Here are some quick instructions on how to setup JRuby on your machine so we can test out multi-threaded performance. The easiest way to install JRuby in my opinion is through Ruby Version Manager. RVM is essentially an easy way to manage multiple ruby versions (and their associated gems) on a single machine. For Linux/Unix/OSX instructions, see here. For windows go here.

1- Install JRuby:

>rvm install jruby

2- Check that it's installed

> rvm list gemsets









3- rvm use <name of the jruby gemset>
> rvm use jruby-1.7.1

4- Test it out in irb (ruby's interactive console). You should see "java" as the
RUBY_PLATFORM if things are installed properly:






Sample App

The following are two sample apps which showcase multi-threading in JRuby vs. Ruby 1.9 vs Ruby Enterprise Edition 1.8.7.

JRuby Example (also showcasing how easy it is to call java code from Ruby):

Standard Ruby example:
To run the experiment:
1- Run in Jruby:
> ruby multi_thread_jruby.rb

2- Run in Ruby 1.9.3
> rvm install ruby-1.9.3-p286
> rvm use ruby-1.9.3-p286
> ruby multi_thread_ruby.rb

3- Run in Ruby 1.8.7
> rvm install ree-1.8.7-2012.02
> rvm use ree-1.8.7-2012.02
> ruby multi_thread_ruby.rb

Average completion time summary:
JRuby(1.7.1):            199.3ms
Ruby(1.9.3p286):         610.0ms
Ruby(ree-1.8.7-2012.02): 748.6ms

As we can see, JRuby is close to 4 times faster than Ruby 1.8 on my 4 core MacBook Air. Ruby 1.9 performs slightly better by being able to take advantage of time during which the process is I/O blocked. Overall, JRuby is the clear choice for maximizing multi-threaded performance.

Additional Reading: 


More on calling Java from JRuby:
https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

An interesting look at benchmarks of JRuby compared to other ruby versions. This shows that JRuby is not better in all scenarios: 
http://etehtsea.me/the-great-ruby-shootout

#SeekDiversePerspectives