Pages

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!