Pages

Sunday, December 9, 2012

Two more days @ AnDevCon_IV

I guess driving on 101 was still better than flying all the way from Japan or India or Russia.


The sond day was much more eventful than the first day.
I started my second day with 'Inside Android User Interface' by Karim Yaghmour. He explained how Android display stack is different than Linux display stack, how is WindowManager used to add views and also touched upon StatsuBarManagerService. Do you know you can send commands to any system service from adb shell? I though that was pretty neat especially during debugging.
For example, if you want to expand the status bar, you can do this on adb shell

$ service call statusbar 1

In order to close the notification tray which was expanded by previous call, send this command

$ service call statusbar 2

The general form of the command is service call

The highlight of the second day was a keynote from Romain Guy and Chet Haase. They talked about what's new in 4.1 and 4.2, nothing much different from their Google IO session except for recent 4.2 enhancements. But nevertheless, it's always fun to listen to these Android Ninjas.


Then it was time to meet people at Exhibition hall, umm ... actually it was time to collect swags and t-shirts. Many of the companies were either focused on testing or monetizing apps. The only interesting spots were Google booth for Android Robots, Amazon booth because it was Amazon, Qualcomm booth with MDP and SnapDragon demo and Immersion tech booth because this was something new for me - use of Haptics tech with Android hardware - can make apps more accessible. Got a chance to ask Romain Guy a few questions and the discussion was quite insightful.

This was an interesting slide from Qualcomm's lightening talk.



On Thursday, the lunch was special too. Robin Jeffries, a Google engineer and a member of the Board of Advisors for the Anita Borg Foundation hosted Women in Android lunch. It was nice to see more geek chics in the room and more importantly Robin's talk was quite inspiring.

After lunch, I attended 'Optimizing Android UI - Tips and Tricks' by Jason Ostrander. He is the author of  Android UI Fundamentals book. He quotes many examples from his book and overall it was a good session. He touched upon Handlers and Services to offload work from main thread, use of Loaders for grabbing data from network sources, ViewHolder pattern to create smooth scrolling lists and many more ...

This was followed by coffee and ice-cream break and a chance to collect more goodies from exhibition hall. And then it was time for yet another keynote, by Mike Shaver, Director of Mobile Engineering at Facebook. The theme of his talk was 'scale' and this was by far the most entertaining talk. He glossed over the challenges posed by Android fragmentation, more than 900 devices and many more coming up with Gingerbread ...

One more day; four more sessions and a hope to win Nexus 7 -

I was really looking forward to attending 'Extending the Android Vibrate Function for Games' especially after the brief discussion I had with Bob at the exhibition hall.
Android supports an API to specify the duration of Vibrator. There is no API to control the frequency, voltage or any other parameters. Immersion Tech. focuses on haptics technologies and in their efforts to promote haptics tech adoption, they have developed a library of over 120 vibration effects. What was more interesting to me was the possibility of making some apps more accessibleusing these various effect. In their presentation, they proposed the idea of Haptics Clock which anyone can use to check time even without looking at the screen.

I have this idea, not sure if it's feasible. Assume a message is written in Braille script and someone does not want it be read to him aloud. In such cases he could touch the screen, and every dot will generate a distinct vibration pattern and it would be possible to read any arbitary message.

Anyways, it's free to use by developers and it's really easy to use. They work with OEMs in order to include more precise motors and implement low level APIS to control the motor. Apparently, OEMs are interested in this technology as it allows them to distinguish their decives based on enhanced Game experience ... Samsung S3 & NOOK have such motors and support their library natively,

Later they announced the winners of various raffles. Oh btw someone gave away an iPad!

So the next session was a long one. 'Battle tested patterns in Android Concurrency'. He had lot of slides and a lot of information to share.
In a nutshell, here are main points

  •  get off the main UI thread
  •  don't leak activity references 
  •  don't just use background threads as they keep running even if Activity is destroed of not handled carefully
  •  Same applies to Asynctask, tehy are not tied with Activity Life cycle
  •  Loaders are aware of Activity Life Cycle - hence post data to the running insatce, managed by LoaderManager - much better than AsyncTask
  •  Loaders cannot throw exceptions which an activity can catch
  •  keep thread count = # cores - 1 => leave some CPU for UI activities!
  •  If you have to, use old school counterlatches to achieve synchronization
  •  use ExecutorService whch has its own threadpool (plain old Java)
  •  LocalBroadcasts can be used as a local data exchange method between loaders and activites - super cheap (work like callback registry)
After this information overload, it was time to sip some coffee. The last session I chose was - 'Intro to RenderScript'. Had no idea about RenderScript so this was a good 101 session.

Google gave away some (only 4 or 5) fur toys, was happy to grab one :)



Overall it was a great experience!


First day @ AnDevCon_IV

Last week I had a great time at AnDevCon_IV. Three days filled with Android, learned interesting stuff, met some smart people, connected with old buddies and shook hands with some famous personalities in Android world.

AnDevCon 4, a four day technical conference started on Dec 4 at Burlingame, California. They had hands on workshops on day 1, including Android Bootcamp, Embedded Android and Facebook apps for Android.

The second day was kicked off by a keynote by Ethan Evans, Director of App Developer Services, Amazon. He discussed the performance and impact of HTML5 apps and also mentioned how Amazon achieved the better performance by using both HTML5 and native code in their apps. He also explained blended HTML5 used in their App store hybrid architecture. "Updates without requiring Upgrades" was the most promising feature of HTML5, he said.

After his keynote, the actual classes began. It was a daunting task to choose between 70+ classes and many interesting topics were cross listed which made the selection even tougher. 'Hacking APKs for fun and profit (mostly fun)' sounded fun but I instead headed to "Dive into Android Fragments" session by Donn Felker. After he explained the basics of Fragments and fragment transactions, he talked about RoboGuice. It's a lightweight library that uses Google Guice library for dependency injection. It's not recommended for games or performance centric apps, but it does make code simpler and cleaner. He also talked about other open source projects -

  • Otto from Square - another dependency injection framework
  • ActionBarSherlock - extension to Android's support library to facilitate the use of ActionBar on all versions of Android
  • Viewpageindicator - adds pagination to Android code, especially useful when using multiple fragments or panes.
Android Bootstrap might be useful if you are planning to use above technologies, the project is built using many open source projects widely used in practice. 

Here is a link to Donn's Github project that he used to explain fragments.

Mike Wolfson presented two part series on Android Developer Tools. Google IO videos on this topics are much more informative so I will skip my notes on this session except for one piece of information.

HAXM - Intel® Hardware Accelerated Execution Manager  It's hardware assisted hypervisor, can greatly reduce the time required to boot an android image on an emulator. You need to download the driver for haxm and also Intel Atom image to use with the emulator. Currently it supports only ICS and JB images.
He also has a repo of all different types of AVDs, which can come handy during testing.

Marko Gargenta presented 'Architecting Android Apps' where he explained basic building blocks - activities, services, providers and receivers, as well as intents that glue them all together.

The post lunch sessions were the most engaging ones and were packed with useful information, so keeping myself awake was not hard.

Alex Gargenta presented 'Deep Dive into IPC/Binder Framework'. You should check out this video. He did a great job explaining binder concept, starting with the kernel level binder driver all the way up to application level code including discovery mechanisms, threading context, security implications etc.




I concluded Day 1 with "Mastering Android Touch system" session presented by Dave Smith. He provided in-depth look at how Android passes touch events between view hierarchies, why should you care about ACTION_DOWN even if you are interested only in ACTION_UP or ACTION_MOVE, what it means to handle a particular event etc. Code examples will make the theory simpler - here is the project he used.

Oh btw, driving on 101 sucks and it doesn't matter which direction you are travelling or if you are in hov lane or not, it sucks!

Saturday, September 1, 2012

Building Your First Android Application

Let's build our first application. Launch Eclipse. click New Android App Project  in the toolbar or select New Project under File menu, then select Android Project. Choose you Application name and package name. Uncheck "Create custom launcher icon" and click next
Next, select Blank Activity
And finally, name your activity. The Title is the Application Title shown in Android launcher screen. Click Finish. 

ADT will generate various folders and files and you will see the layout graphical editor oped for you. This is how your app will appear when launched on device. The ADT has already added the bare bone required to run your app on Android platform.
For this excercis, we will use an android virtual device to run our first app. An AVD is a device configuration for the Android emulator that allows you to model different devices. To create an AVD:
  1. Launch the Android Virtual Device Manager:
    1. In Eclipse, click Android Virtual Device Manager from the toolbar.
    2. From the command line, change directories to/tools/ and execute:
      ./android avd
  2. In the Android Virtual Device Manager panel, click New.
  3. Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
  4. Click Create AVD.
  5. Select the new AVD from the Android Virtual Device Manager and click Start.
  6. After the emulator boots up, unlock the emulator screen, you will see the app running.
In next post, we will learn about application building blocks and we will also examine project directory structure to better understand the app components, Till then play with your Android AVD. It runs the entire android stack and also comes with standard stock apps such as Maps, Browser, Contacts etc. 

Thursday, August 30, 2012

Add Git Branch to Bash prompt and a git goodie - SourceTree

Adding git branch to your bash prompt has become easier than before.

Edit your ~/.bash_profile to add following code

# Set git autocompletion 
if [ -f /usr/local/git/contrib/completion/git-completion.bash ]; then
  . /usr/local/git/contrib/completion/git-completion.bash
fi

GIT_PS1_SHOWDIRTYSTATE=true

if [ -f /opt/local/etc/bash_completion ]; then
    . /opt/local/etc/bash_completion
fi

PS1='\[\033[34m\]\w\[\033[31m\]$(__git_ps1)\[\033[00m\]\$ '

It not only adds branch name but also indicates the current status of your project. For example, when you add files to staging area, + is added after branch name. 
If you make further changes to staged files, it adds * after branch name to indicate there are unstaged files.

The above script also enables Git autocompletion which will help saving some keystrokes.

If you prefer GUI tool and even if you prefer command line, SourceTree is a must have tool for Mac users. It shows you all branches, their commits, the changes. You can do everything using it.


For newbies, it will make using git a lot more fun!

Tuesday, August 28, 2012

Getting Started with Android App Development

The beauty of Android development is that you are not restricted to any particular development environment. You can use any operating systems and any IDE you like. But since we will be writing Java code, Eclipse is a natural choice.

All you need are these 4 things

- Java SDK 6
- Eclipse IDE
- Android SDK
- Eclipse ADT plugin
- git (optional but recommended)

Get Java SDK


If you don't have Java SDK, getting it is simple. Download it from
http://www.java.com/getjava

Download Eclipse IDE


Download Eclipse Classic from http://www.eclipse.org/downloads/
If you are using Mac or Linux, and not sure if you are running 64bit or 32bit machine, inside Terminal run this command
$ uname -a
The output will tell you which eclipse binary you should download. Unzip and you have Eclipse.

Download Android SDK & Tools


Next step is to download Android SDK from
https://developer.android.com/sdk/index.html
Unzip the file you just downloaded. You should see android-sdk-mac folder. Copy it to a location where you want to download all other Android Development tools. Using terminal, navigate to tools folder inside android-sdk-mac and run android program
~/dev/android-dev/android-sdk-macosx/tools $ ./android  
This opens up Android SDK Manager. It shows you all installed components, the updates and also lists all available versions of Android SDK. This is where you will select what you need to download that includes, plain SDK, sample code, SDK source code, system images, Google APIs and also vendor specific components. If that's too much to take in, make sure you select for both Android 4.1 and Android 4.0.3
  • Documentation from Android SDK
  • SDK platform
  • Samples for SDK
  • ARM EABI system image
And under Tools category, select
  • Android SDK Tools
  • Android SDK platform-tools
And click install packages, next Accept all and let it finish.

The final step is to install Eclipse ADT plugin which makes Android development tools (mode on that later) part of the IDE for easy access. 

Download the ADT Plugin


  1. Start Eclipse, then select Help > Install New Software.
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
    https://dl-ssl.google.com/android/eclipse/
  4. Click OK.
    If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish.
    If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
  8. When the installation completes, restart Eclipse.

Configure the ADT Plugin


After you've installed ADT and restarted Eclipse, you must specify the location of your Android SDK directory:
  1. Select Window > Preferences... to open the Preferences panel (on Mac OS X, select Eclipse > Preferences).
  2. Select Android from the left panel.
  3. You may see a dialog asking whether you want to send usage statistics to Google. If so, make your choice and clickProceed.
  4. For the SDK Location in the main panel, click Browse... and locate your downloaded Android SDK directory (such asandroid-sdk-windows).
  5. Click Apply, then OK.

Install Git


Git is an open source version control system. It works best for small projects as well as massive projects like Android platform itself. It will help you maintain different versions of your source code. In case you would like to download the Android source code, you will require git. It's very easy install.
Download it from below site and install it using package manager.
http://git-scm.com/

We will talk s more about git once we start developing actual applications. 

Next, we will talk about some Android Development Tools and will run our first Android app.


Monday, July 30, 2012

rbenv - A Simple Ruby Version Manager

rbenv is a new kid on the block! A simplistic ruby version manger which manages ruby versions and lets you switch between different versions easily and that's it.

Unlike rvm, it does not,

  • Have a configuration file - well there is nothing to configure other than ruby version
  • Install Ruby - you are on your own
  • Manage gemsets - Bundler is your buddy
It's good to have no frills version manager, but if you like rvm, don't switch to rbenv! You will surely miss rvm. 

How to Install Ruby On Rails on Mac - Updated

This post will guide you to prepare your Mac OS to install Ruby on Rails using rvm. It will also show you how to create a sample rails app to enjoy all the efforts involved in installation.

There is a good news and a bad news. First the good news. Ruby comes preinstalled on all Mac's.
To check which version you have, open up Terminal and type
$ ruby -v
The most current version as of July 2012 is 1.9.3.
Now the bad news, the version you have may not be the version you want and it's a pain to manage different ruby versions manually. Ruby Version Manager (rvm) does great job so it carry the burden of installing and managing different versions.

Step 0. Install git and gcc 

To check if you already have git, inside Terminal run this command
$ git --version
If you don't have git installed, download the recent installer from
http://code.google.com/p/git-osx-installer/downloads/list?can=3
Open the .dmg file and you will find the installer package. Follow the instructions to install git.

Ruby is compiled locally using gcc, hence make sure you have gcc installed.
$ gcc --version
Gcc does not come preinstalled on Mac. You need a developer account to install it separately.
  • If you are running Lion, login using Apple ID and download Apple's official Command Line Tools for Xcode. Simply double click .dmg file and then the enclosed .pkg file to start the installation process. 
  • If you on Snow Leopard, you can download Xcode (4 GB in size) and install it, which includes gcc. The easier option would be to download the unofficial Gcc compiler and related tools from osx-gcc compiler downloads page.
Step 1. Install RVM

Open up Terminal and execute this command -
$  curl -L https://get.rvm.io | bash -s stable
It downloads and runs RVM installation script.

If curl complains about certificates, try with -k option
$ curl -kL https://get.rvm.io | bash -s stable
If you run into other issues, make sure you have git installed. Don't worry, it's easy to setup.

Once rvm installtion is completed it shows the files it modified. rvm is now ready to be used. Close the current Terminal window and open a new one. Test rvm using
 $ rvm --version
You should see a version number with no errors. In case it was not recognized as a command you will have to load the rvm script into the shell so that shell can recognize 'rvm' as a valid command. You do that by executing following command verbatim.
$ echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && "$HOME/.rvm/scripts/rvm" ' >> ~/.bash_profile

Step 2. Install Ruby using rvm
We will install 1.9.3 as part of this tutorial. To get a feel of what rvm is capable of installing, run this command
 $ rvm list known
It lists different versions of Ruby packages that can be installed and managed by rvm.
To install ruby use this format rvm install for example, 
 $ rvm install 1.9.3
It downloads the source code for ruby 1.9.3 and then compiles it locally. If there are any errors, rvm will also tell you how to fix them. Once done, it displays "Install - #complete"

To verify, list the installed versions using
 $ rvm list
It should list the installed version like this -

~$ rvm list

rvm rubies

 * ruby-1.9.3-p194 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

and now to double check, verify the ruby version itself using
 $ ruby -v
Now set it as your default ruby version.
 $ rvm --default 1.9.3
Optionally, you might want to generate Ruby core documentation by running
 $ rvm docs generate

Step 3. Install Rails and other Gems
It's simple. Run this command and it will install rails and all other dependencies which work with your ruby version. It also install the docs for al the gems. Takes some time ...
 $ gem install rails
To install SQLite 3, first verify you have sqlite3 installed on your system by typing
 $ sqlite3 -version
It will respond with a long version string. Now install ruby binding for sqlite using
 $ gem install sqlite3

Step 4. Ruby On Rails Test Drive
Now that you have all the required components in place, let's create a your first Ruby on Rails app to make sure everything is working smoothly. Again inside a Terminal window,  navigate to a directory where you want to create your new app. ~/rails-app for example. Run these commands one by one
$ rails new todos
This will create the template application with model, view and controller and some static files.
$ cd todos
Tell rails to generate scema for your todos app database and also generate controller and views for standard actions.
$ rails g scaffold todo name:string completed:boolean
Run database migration
$ rake db:migrate
Then tart the rails WEBrick server on default port 3000
$ rails s
Finally, point your browser to http://localhost:3000/ If you see a welcome page, your app is running fine. Congratulations! Your todos can be managed at http://localhost:3000/todos

When you are done, you can stop the server by typing CTRL+C in the shell window where you started it earlier.

Extra Credit: More rvm commands

To revert to system version of ruby, i.e. pre-rvm ruby use this,
$ rvm system
To go back to 1.9.3 or any other version, use
$ rvm 1.9.3
To get the list of all rvm commands,
$ rvm usage

Hope it helped!

Sunday, February 12, 2012

Sublime Text 2 - I'm loving it!


Leaving Notepad++ was not easy. The recommendation for TextMate was loud and clear. But it didn't impress me and the search continued. There came this new kid on the block - Sublime Text 2. I must say it's really Sublime. If you haven't tried yet, download it now - http://www.sublimetext.com/2 Not just mac users, but my ubuntu friends are also leaving their "vi" and gEdit for Sublime Text 2.

My favorite features -

  • multiple cursors - it's incredibly useful!
  • column select
  • crazy fast file switching - include 'Go to anything' search (cmd + p)
  • context specific search and replace
  • side by side multi-pane editing (like :vsp in vim)
  • auto completion 
  • bookmarks (like in vim)
  • distraction free mode
  • Snippet support 
  • Zen coding support 

And there is a package manager which makes installing new packages a piece of cake.

Terminal command to open up Sublime Text 2
It's simple, just create s symlink and add it to your PATH
ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/subl
Edit your ~/.bashrc or ~/.bash_profile to add this -
PATH=$PATH:~/bin
export PATH

Install package manager-

Open Sublime text 2, you can use subl command in your Terminal now.
Open the console by clicking View -> Show Console  and paste this in the console and hit enter. import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())); open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read()); print 'Please restart Sublime Text to finish installation'
Restart Sublime Text 2 to complete the installation process.
Presse cmd + shift + p to access the command pallet and then type 'Install packages" and hit Enter.
This will open up a list of all available packages. Select the package from the list and Enter. That's it. It will download the package and install it for you.

Here is the list - http://wbond.net/sublime_packages/community

A very quick way to create new folders and file - cmd + alt + n -
Happy Coding!

Print Screen in Mac


When I opened my macbook, the first thing I wanted to do was to take a screenshot and email it to my friend. But there is no Print Screen? First Google result - cmd + shift + 3. Can it be more obscure? 
Sure, it has lot of good functionality built in but a dedicated key or fn+something is more user friendly, isn't it?

Here are all options - 
  • Cmd + shift + 3 -- Takes screenshot of the entire screen and saves it as a .png on the desktop
  • Cmd + shift + 4 -- Lets you select an area and then saves it as a .png on the desktop
  • Cmd + shift + 4 + space -- Lets you take a screenshot of just one window. and saves it as a .png on the desktop

To copy the contents to the clipboard, add control key with above combinations. e.g 
  • Cmd + +ctrl + shift + 3 -- Takes screenshot of the entire screen and saves it to the clipboard
Command Line -
For Terminal lovers, screencapture command can be used and it's especially useful for automated scripts. 
$ screencapture -iW ~/Desktop/screen.jpg

File Format 
Mac OX X 10.4 and later versions use .png as a default file format to save the screenshot but this can be changed by using the below command inside Terminal

$ defaults write com.apple.screencapture type image_format
$ killall SystemUIServer

where image_format can be jpg, tiff, pdf, png, bmp or pict. The second command causes SystemUIServer to restart so that the change takes effect immediately. 

There is also a native app - 
If you don't like so many keys for just a screenshot, you can also use an app called Grab, bundled by Apple by default, to grab a screenshot and view it using Preview application

So much for a simple print-screen!

Moom - Snap for Mac

If you miss the Snap feature of Windows 7 where you can quickly resize any window to occupy half of your screen space, here is a must have app from ManyTricks. It's called Moom - http://manytricks.com/moom/

It does a fantastic job of resizing and aligning multiple windows with simple mouse control. It also has keyboard mappings if you like. I find it extremely useful especially while working with multiple Terminal windows, and also while working on my Website. 

Thursday, November 3, 2011

Spruce up your Terminal

It's very annoying when mouse doesn't work inside Vim in Mac's Terminal and when Cmd + 1-9 doesn't work while switching tabs. With some googling here are simple steps for making these things work.

The first thing you need to install in SIMBL - (SIMple Bundle Loader) - pronounced like "symbol" or "cymbal" - enables hacks and plugins. Download it from http://www.culater.net/software/SIMBL/SIMBL.php Unzip it and use the .pkg installer.

Next step is to get the required plugins. Most of the plugins come with installer but it's easy to do it yourself.  Plugins can be copied to /Library/Application Support/SIMBL/Plugins for all users or ~/Library/Application Support/SIMBL/Plugins for just your account.

Using MouseTerm Plugin -
MouseTerm is a SIMBL plugin for Mac OS X's Terminal.app that passes mouse events to the terminal, allowing you to use mouse shortcuts within applications that support them.
Download .dmg file from https://bitheap.org/mouseterm/
Run Install and restart Terminal app.  To enable mouse for all events inside vim, add this to your .vimrc file
if has("mouse")
   set mouse = a
endif
To check other information and possible values run :help inside vim.

Switching between tabs using cmd + 1-9
cmd + 1-9 lets you switch between different windows, but if you like to work with multiple tabs instead, you can change the behavior of this key combination using TerminalTabSwitching plugin.
Download it here.
Extract it in ~/Library/Application Support/SIMBL/Plugins

Changing bash prompt - 
To customize your bash prompt, you can refer to this post

Adding colors to bash prompt - 
Good explanation on how to add colors to bash prompt can be found here.

Adding git branch to bash prompt - 
This is really helpful, if you work with many branches in git. I have covered this in my earlier post.

Just a quick note, mouse events and tab switching works by default in iTerm 3 and it also supports many more features such as vertical / horizontal splits etc. Give it a shot. 

Wednesday, November 2, 2011

How to install Ruby on Rails on mac

Update: There is an updated version of this article at How to Install Ruby on Rails on Mac - Updated

This is first tutorial in ruby on rails series. This post will show you the exact steps you need to follow to get Ruby on Rails up and running on your Mac.

If you are new to Terminal and Mac os X in general; you will find this helpful.

Since mac gives us shell access, we can take advantage of Linux goodies. The most useful and recommended tool is rvm. It stands for Ruby Version Manager. It's a command-line tool which allows you to easily install, manage, and work with multiple ruby environments including sets of gems. With new versions of ruby getting released periodically, it's nice to have a version manager.

OS X comes with ruby installation by default. Check the version of installed ruby -
 ruby -v
Most likely, you will see ruby 1.8.7 pre-installed for you. Now it's time to upgrade to either 1.9.2 or 1.9.3.

Step 1 - git installation
rvm requires git to be installed on your system. If you already have git, skip to the next step.
git is a popular version control manager used by many open source projects including linux kernel and android. Download the appropriate installer from here
http://code.google.com/p/git-osx-installer/downloads/list?can=3
Open the .dmg file and you will find the installer package. Follow the instructions to install git.
To verify, inside Terminal type git and you should see a list of available git commands.

Step 2 - RVM installation
For GUI lovers, there is GUI version available just for Mac users. Download from here - http://jewelrybox.unfiniti.com/
For rest of of us who love Terminal, follow along. It's one step process. Inside Terminal run this command -
bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
It downloads rvm and installs it for you.

Step 3 - Load RVM
This step is analogous to adding rvm to your $PATH or environment variable.
Again inside Terminal,
echo ‘[[ -s "$HOME/.rvm/scripts/rvm" ]] && source “$HOME/.rvm/scripts/rvm”‘ >> ~/.bash_profile
It add rvm scripts to your bash profile so that every time you open the terminal, rvm gets loaded in the Terminal.

Step 4 - Verify RVM installation
Restart Terminal. Use cmd + Q to close the application and open it again.
Now it's time to see how rvm looks. Type rvm in Terminal and you will be greeted by a long message.

Step 5 - Download and Install xcode
xcode covers most of the dependencies for new Ruby installation. It also includes gcc compiler and other important development tools. You can download Xcode from Apple’s App Store. Search for “xcode” and click the install button.

Step 6 - Upgrade to Ruby 1.9.2
We will use 1.9.2 for this tutorial as it's the most recent stable version.
Inside Terminal,
$ rvm list known
# MRI Rubies
1.8.6[-p420]
1.8.6-head
1.8.7[-p352]
1.8.7-head
1.9.1-p378
1.9.1[-p431]
1.9.1-head
1.9.2-p180
1.9.2[-p290]
1.9.2-head
ruby-head
...
This is the list of all components known and managed by rvm.

We will install ruby 1.9.2.
$ rvm install 1.9.2
Next, check the installed versions by rvm using
$ rvm list
Now start using 1.9.2 by this command
$ rvm use 1.9.2

Your current ruby version is 1.9.2 but you might want to make this as your default version.
$ rvm --default 1.9.2
Check the version in another Terminal window
$ ruby -v
$ which ruby
You are almost done!

Step 7 - Install gems
Ruby gems are managed by a command line tool called 'gem' and it's preinstalled for you by rvm. You can use it to install other gems such as rails or sinatra etc.
$ gem install rails
rvm chooses gems depending on the current version of ruby and you can switch between different version by using 'rvm use' command.

Step 8 - Create Your rails project (optional)
 cd ~
 mkdir rails-apps
 cd rails-apps
 rails new hello
 cd hello
 rails s
In your browser, open localhost:3000/. You have successfully installed Ruby on Rails on mac :)

Tuesday, November 1, 2011

Using Macbook Pro like a Pro

Getting a new macbook pro at work was very exciting. I instantly fell in love with the trackpad and mouse gestures and the overall look and feel of all applications, the dockbar, the cute little animated effects. As I started setting up my development environment, I started missing my Ubuntu and Windows comfy zone.

The first shock was no home and end keys, instead a key combination. I still can't get over it. No page down and page up. And how do you refresh a page? Stop decreasing the brightness, it would help it could reload the page instead. Coming from Windows land, mac keyboard didn't feel native to me. But I promised myself to learn how to use mac like a pro. I will share some of my newly acquired wisdom here :)  


Friday, October 7, 2011

Silicon Valley Code Camp is back :)

I am so excited, the Silicon Valley Code Camp is starting tomorrow at Foothill College, Los Altos :)

This year with over 9 different tracks, 213 sessions and 3035 registered attendees, it's ready to break yet another record! More information here - http://www.siliconvalley-codecamp.com It's not too late to register if you haven't done yet. You can follow us at @sv_code_camp or #svcc

I will be helping with the attendees's registration, stop by to say hi.

Oh and don't miss the special session on Sunday morning at 9:15 am. Lino Tadros, a historian of Silicon Valley history,will retrace the steps of Apple as a special tribute to Mr Steve Jobs!

Happy Coding weekend!

Rebooting ....

Signing in ... SUCCESS (Glad you remember your password!)
Checking last entry ............ long time no see!
Update blogger interface [Y/n] n (I hate the new look)
Promise more regular blog entries? [Y/y/yes] .. (hmm)
List new topics here, type end to finish
 - Ruby On Rails
 - Interview Questions
 - Android 
 - HTML 5 experiments
 - end
Sounds interesting!
Publish now? [Y/n/later] Y
Congratulations!
Reboot Complete!

Wednesday, November 24, 2010

Polymorphic Data Structures Using C macros

Have you seen kernel source files, especially header files or any device driver implementation? They all make a heavy use of C macros. I always wondered why would anyone use C macros so much. Macros are not debug-friendly; you cannot set a breakpoint inside a multiline macros. I used to be afraid of macros until i realized during my kernel project that how benign macros could be.
For the record, C macros can be used for
  • defining "constants"
  • true inline functions with no type safety
  • enhancing readability of source code
  • writing platform independent code with help of conditional compilation
But there is more to it that can take advantage of the fact that C preprocessor runs before the compiler.
One of the more frustrating aspects of non-Object-Oriented languages like C is the apparent lack of re-usable code. For example, a primitive data manipulation structure (like a tree, queue, or list) that has been implemented in one structure cannot manipulate another structure without some workarounds. There are mainly two frequently used workarounds -
  • Copy &Paste - This means we copy the algorithm for one structure and by changing name create another data manipulation structure. Though it sounds time efficient method, maintaining different copies of same algorithm is pain and moreover if there exists any bug in algorithm, it's propagated to all copies.
  • Generalized data structures - These structures which accept only void * for data are frequently used but they come with a price too. The use of void * weakens the limited type safety of C language and allows for bugs to creep into the code. It also suffers from ppor performance because the system has to do twice as many memory references for both data and structural links.
None of the above solutions are as promising  as true object-oriented programming. But there is a way to achieve both efficiency and time safety by using making use of macros! By leveraging C preprocessor's text manipulation one can construct the C equivalent of a polymorphic data structure. Using this technique we can construct a reliable toolbox of primitive data structures that can be used in any C program, since they take advantage of C syntax and not the specifics of any particular implementation.

C preprocessor only does text substitution and does not care of the meaning of the strings. Let's take an example.
#define QUEUE(Q_TYPE, DATA_TYPE) \
struct Q_TYPE{ \
struct Q_TYPE *left; \
struct Q_TYPE*right; \
DATA_TYPE data; \
}
QUEUE(queue_t, int)  myQueue;
The above code generates a unique structure where only allowed data type is int. Hence, we get full advantage of C type safety and we can create structures for different data types on the fly. Sounds familiar? C++ templates? Then, we are on the same page.

The main power comes from the ability to generate algorithmic code which can work on these polymorphic data structure again using macros. Let's see some code -
I define a macro Q_NEW_HEAD(Q_HEAD_TYPE, Q_ELEM_TYPE) which generates a new structure of type Q_HEAD_TYPE representing the head of a queue of elements of type Q_ELEM_TYPE.

#define Q_NEW_HEAD(Q_HEAD_TYPE, Q_ELEM_TYPE) \
 typedef struct { \
  Q_ELEM_TYPE *front; \
  Q_ELEM_TYPE *tail; \
  int size;  \
 }Q_HEAD_TYPE
But I need a flexibility in choosing the link name for my structure. Hence, I define one more macro

#define Q_NEW_LINK(Q_ELEM_TYPE) struct Q_ELEM_TYPE*

This is how I can use these macros in my C program -

Q_NEW_HEAD(int_list_head_t, int_list_t);

typedef struct int_list_t{
  Q_NEW_LINK(int_list_t) myLink;
  int data;
} int_list_t;

Iterating over a linked list is the most common code, here is a syntactic sugar in the form of macros -

#define Q_FOREACH(CURRENT_ELEM,Q_HEAD,LINK_NAME)   \
 for (CURRENT_ELEM = (Q_HEAD)->front; CURRENT_ELEM; CURRENT_ELEM = CURRENT_ELEM->LINK_NAME)

Similarly we can define macros for
#define Q_INSERT_TAIL(Q_HEAD, Q_ELEM, LINK_NAME)
#define Q_INSERT_FRONT(Q_HEAD, Q_ELEM, LINK_NAME)
#define Q_INSERT_AFTER(Q_HEAD,Q_ELEM_TYPE,Q_INQ,Q_TOINSERT,LINK_NAME)
#define Q_REMOVE(Q_HEAD,Q_ELEM,LINK_NAME)
and so on ...
The program becomes much more readable and manageable. 

But, make sure to test all macro definitions for all corner cases, It's tricky to write and debug such long complicated macros. Here are some common pitfalls - well documented. Looking at the generated code may help sometimes - 

$ gcc -E my_macro_loaded_source.c


Saturday, October 16, 2010

Silicon Valley Code Camp 2010

Last weekend, I enjoyed lots of technical discussions on various new technologies including Android, Google APIs, HTML 5, Sencha Touch from some of the smartest people in the industry, together with free food and drinks and lots of swags from sponsors. Yes, this was Silicon valley code camp 2010.
It was a two day event, with 9 different tracks and over 190 sessions. The best part was it was totally FREE :) No, the best part was the learning, sharing, discussing, contemplating, questioning ... Did I mention free food? It was a huge success with close to 2000 attendees. It's a big deal because it's entirely run by volunteers.

Today I want to spend a moment to thank all those people who made this code camp a great experience for me. Special thanks to Peter Kellner for the endless hours he put in to make this possible.

I started my Day 1 with Introducing Google APIs Part-I (A-Z & Geo) session. It was quite informative given the vast variety of Google APIs. I found FusionTables very interesting and its integration with Google Maps APIs along with KMLLayer can result in some useful applications.
Then I head over to 'Android: Beyond Basics' session. Well, I was expecting to hear about some advanced topics, he covered the basic building blocks of Android except Activitiy which he had discussed in his first session, Android Basics. After lunch, I was in dilemma whether to attend Dancing with iOS or Sencha Touch. I am glad I chose Sencha Touch. David Kaneda described the Sencha Touch application framework that enables mobile web apps that look and feel native on iPhone and Android touch devices using primarily HTML5, CSS3 & JavaScript. It was like a roller coaster trip through Sencha framework. He touched so many things, it was hard to digest for a beginner like me. But I will mention few things here. David explained Syntactically Awesome Stylesheets (SASS) and the Compass framework and they together lead to more fun with style sheets. He also recommended, use of PhoneGap to prepare the Sencha Touch apps for both Android and iPhone.

Then I attended two more sessions from Google track - Google App Engine and Google Chrome / HTML 5. Both talks were equally engaging. I personally enjoyed Chrome session partly because I am currently working on Chrome OS and I could totally relate to what they were discussing. I was looking forward to day 2 for more talks on HTML 5.

I wanted to attend Do you Mapreduce? but it was clashing with 'Fun with HTML5, CSS3 and JavaScript'. This was really fun. Tab Alkins Jr (Google) coded a game live in front of audience. He covered only Canvas element so my thrust for HTML 5 was not yet satisfied and I went on to yet another HTML5 session - Mobile HTML 5 by Michael Galpin. I have read his articles on developerWorks so it was a nice opportunity to listen to his talk where he gave an detailed overview of HTML5 features. During lunch, there was a raffle with many exciting prizes including xbox which was fun (for those who won).

The session on Building Video Applications with YouTube API by Jarek Wilkiewicz was interesting because I never knew anything about it before. Some amazing statistics: YouTube gets
* 2B views/day
* 150m mobile views/day
* 24 hours of video uploaded/minute

The last session I attended was 'Mapping On The Phone' by Mano Marks from Google. It was an hands on session where he showed how to use GeoLocation feature of HTML5 together with Google Maps APIs.

It was a time for clean-up and I happily volunteered for this activity together with 10 other people. I was a nice feeling. I totally love my SVCC volunteer t-shirt :) My favorite moment was talking with Michael Galpin on video tag acceleration and application catch.

One of the side effects of attending this event is that I ended up opening my twitter account because almost everyone promised to tweet their ppt links!

Sunday, October 3, 2010

OpenGL For Android - GLSurfaceView

One of the fascinating features of Android platform is its support for OpenGL. OpenGL is a cross-platform 2D and 3D rendering graphics library. An industry consortium, called Khronos Group maintains the OpenGL specification. http://www.khronos.org/opengl/

OpenGL uses C-based flat APIs and hence we need to have a Java language binding to be able to use it with Android Application framework. Java ME has already defined this binding with JSR 231. (Java binding for OpenGL 1.5). What that means for you is - 
import javax.microedition.khronos.opengles.GL10;


Let's get started with the code. 
The main class we use is GLSurfaceView which extends from SurfaceView class. GLSurfaceView
  • Provides a Surface onto which we can render OpenGL scenes
  • Binds with customized Renderer which performs the actual drawing
  • Manages EGL display 
  • Uses a dedicated GUI thread, decouples the main application thread for user interactions
We need to call one method on its object i.e setRenderer() which registers a user specified Renderer object that knows how to draw the desired shapes. 
Activity's onCreate() will look like this - 
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
   GLSurfaceView view = new GLSurfaceView(this);
     view.setRenderer(new SimpleRenderer());
     setContentView(view);
    }
The next thing we need is SimpleRenderer which will be responsible for actual OpenGL rendering. It implements GLSurfaceView.Renderer interface and defines its three methods.



public abstract void onSurfaceCreated (GL10 gl, EGLConfig config)

This method is called at the very beginning e.g when a Surface is created or recreated ( when phone awakes after sleep), it's a good place for all initialization code. 

A typical initialization sequence - 
@Override
 public void onSurfaceCreated(GL10 gl, EGLConfig config) {
  // Set the background color to black (RGBA).
  gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
                // enable smooth shading
  gl.glShadeModel(GL10.GL_SMOOTH);
         // set up depth buffer and enable depth testing
  gl.glClearDepthf(1.0f);
  gl.glEnable(GL10.GL_DEPTH_TEST);
  gl.glDepthFunc(GL10.GL_LEQUAL);
  // use nice perspective calculations.
  gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
  
 }


public abstract void onSurfaceChanged (GL10 gl, int width, int height)

This method is called when the Surface size changes. The size (width, height) affects the aspect ratio so this function should contain the code that depends upon aspect ratio such as GLU.gluPerspective() . A sample code - 
@Override
 public void onSurfaceChanged(GL10 gl, int width, int height) {  
  gl.glViewport(0, 0, width, height);
  gl.glMatrixMode(GL10.GL_PROJECTION);
  gl.glLoadIdentity();
  GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
    100.0f);
  gl.glMatrixMode(GL10.GL_MODELVIEW);
  gl.glLoadIdentity();
  
 }





public abstract void onDrawFrame (GL10 gl)

This method is called when the current frame is being drawn on the Surface and thus actual drawing code goes here. e.g 


@Override
 public void onDrawFrame(GL10 gl) {
  // Clears the color and depth buffer. -- clears the framebuffer
  gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); 
  gl.glLoadIdentity();
                gl.glTranslatef(0, 0, -5); 
  // Draw our square.
  /* square.draw() */
  
 }
This code will create a blank frame with black color. We will see the actual drawing code in the part 2. So stay tuned!

Tuesday, September 14, 2010

Add dictionary support to Notepad++

I love Notepad++. It's light-weight, support many languages, has word completion feature and also includes a Spell Checker. So for all practical purposes, it's a functional editor. Having a dictionary support in your editor is always the best thing and it's very simple when it comes to Notepad++. 

It already has a plugin for Spell Checker which you can find under Plugins->Spell Checker ..
All it requires is GNU Aspell and  a dictionary installed on your machine. 
GNU Aspell is a Free and Open Source spell checker. It can either be used as a library or as an independent spell checker. Main features include 
  • possible suggestions for misspelled words 
  • supports UTF-8 document encoding
  • supports multiple dictionaries. 
Enable Spell checker in four easy steps - 
    1. Download and install Aspell for Windows from http://aspell.net/win32
    2. Now install a dictionary which you can download from the same website.
    3. Notepad++ requires a relative path for aspell-15.dll. Open Plugins->Spell Checker.. A dialog box will open where you can edit the relative path. I have both Notepad++ and Aspell installed in "C:\Programs Files" so I entered the path as "../Aspell/bin"
    4. Restart Notepad++

Bingo! Now if you open Spell Checker, it will show you the list of misspelled words in the current document and possible suggestions. 


Friday, September 3, 2010

Add git branch to bash prompt

If you use git, you will find this small trick very useful.

To make your bash prompt super spiffy (and equally useful), add this to ~/.bashrc:

 #Adding git branch to command prompt
 gitStatus() { git diff --quiet 2> /dev/null || echo ' *' ; }
 gitBranch() { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/ > \1$(gitStatus)/" ; }

Then, somewhere in your $PS1, put \$(gitBranch). Here's an example; try it:

      export PS1="[\u@\h$ \w\$(gitBranch)]\$ "

When you're in a git directory, you'll notice the branch name on the prompt. If the branch has been modified, an asterisk will appear next to the name. Here is an example :

My command prompt looks like this - 

cdump@cdump-linux : /workspace/android/platform > cros-wm *$

indicating I am on cros-wm branch and there are modified files.

Git-goodness!
Credit Serban Giuroiu