Monday, April 14, 2014

Javascript Series for Beginners - Objects

Introduction:

In this post we will talk about how to handle javascript objects.
On the bottom of this post you will find a jsbin that you can use to play with the code snippets below.
This post was inspired by this book: "Javascript: The good parts" by Douglas Crockford

How to create new objects:




How to use inheritance:

Prototype is the mechanism by which objects in javascript inherit properties from other objects.

The prototype link is only used in retrieval. If we look up a property that does not exist in the current object, the prototype link will be used to go up the chain looking if any of the parents has it.

Adding a new property to the parent object will cause to appear in the children but not the other way around.



Reflection and property deletion:

Deleting a property from the child does not impact the parent but it is true the other way around.
Also if you delete a property from the child and the parent has the same property, the parent's value will shine through.


Global scope problem:

One of the big downsides of javascript is that it throws all the objects in the global scope, one way to work around this, is to create a variable that will offer a new scope for your objects and prevent them from conflicting with objects from other applications and librairies.


Your Lab: 

Feel free to play with the code here.

JS Bin


Thursday, April 3, 2014

Tuesday, March 4, 2014

How to Deploy a Sharded MongoDB Cluster

Introduction

In this tutorial we will show how to deploy a sharded MongoDb cluster. We assume that you already have MongoDB and Node.js installed.


Before moving forward, let's explain some key concepts that will make this tutorial easier to follow:
- Sharding: It is the fact of adding more machines to support data growth and greater demand of read and write operations.
- Cluster: It is a set of connected servers that can be viewed as one system.


Our cluster will be composed of the following components:
- 2 shards: these are just regular mongodb databases to store the data   
- 1 query router: also named mongos, it interfaces with client applications and direct operations to the appropriate shard.
- 1 config server: this is a mongodb database that stores the cluster's metadata including the mapping of the cluster's data set to the shards. The query router uses this metadata to route requests to shards.


Installation

Let's start by creating our 2 shards.
The shard needs a folder that will house its files. You can create it like so (-p is to create all the nested folders in the path if they don't exist):
~~~~
mkdir -p /data/db1
~~~~


Now you can start the first shard by issuing this command:
~~~~
mongod --shardsvr --port 27016 --dbpath /data/db1
~~~~


Let's repeat the same steps for the second shard:
~~~~
mkdir -p /data/db2
mongod --shardsvr --port 27017 --dbpath /data/db2
~~~~


Now let's configure the config server.
Issue the following command to create the folder that will house the files of the config server:
~~~~
mkdir -p /data/configdb
~~~~


then start the config server like so:
~~~~
mongod --configsvr --dbpath /data/configdb --port 27018
~~~~


The only component left is the query router server (mongos). You can start it by typing the following command:
~~~~
mongos --configdb localhost:27018 --port 27019
~~~~


All the components of our cluster are now installed and running. Let's move to the next step and configure our system to use sharding.


Sharding configuration

For this step, we will be using the "test" database.

In order to start the configuration, we need to connect to the mongos instance. The connection can be established like so:
~~~~
mongo --host localhost --port 27019
~~~~


Add the first shard to the cluster by typing this command from the mongos console prompt:
~~~~
mongos> sh.addShard("localhost:27016")
~~~~


You should see an output matching this line:
~~~~
{ "shardAdded" : "shard0000", "ok" : 1 }
~~~~


Add the second shard:
~~~~
mongos> sh.addShard("localhost:27017")
~~~~


The output should match this:
~~~~
{ "shardAdded" : "shard0001", "ok" : 1 }
~~~~


To verify that the two shards have been created, type the following command:
~~~~
mongos> sh.status()
~~~~


You should see two shards listed in the output like so:
~~~~
chunks:
                   shard0000 1
                   shard0001 1
~~~~


To enable sharding for the db, you can type the following command:
~~~~
mongos> sh.enableSharding("test")
~~~~


The output should be something like this:
~~~~
output: { "ok" : 1 }
~~~~


To enable sharding for a collection, issue this command (the collection will be created if it does not exist):
~~~~
mongos> sh.shardCollection("test.location", { "zipcode": 1} )
~~~~


You should see this output:
~~~~
{ "collectionsharded" : "test.location", "ok" : 1 }
~~~~


Verification and Testing

Now it is time to test our setup and verify that the whole system works as expected. To achieve that, we need to write some code to insert 300000 records into the database and then verify that this data has actually been distributed over the two shards we have.



For our test, let's create a file called "sharded_cluster_test.js" and add the below Node.js snippet to it. This code will insert some data into our sharded cluster, :
~~~~
var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;


MongoClient.connect('mongodb://127.0.0.1:27019/test', function(err, db) {
    if(err) throw err;


    var collection = db.collection('location');
      for(i=0;i < 300000;i++){
           collection.insert({ "zipcode" : i}, function(){});
      }
      db.close();
});
~~~~


Run this file like so:
~~~~
node sharded_cluster_test.js
~~~~


Verify that the data made it to the database:
~~~~
mongos> use test
mongos> db.location.count()
~~~~


The above command should return: 300000


Let's now verify it has been distributed over our two shards.
Log into the first shard like so:
~~~~
mongo --host localhost --port 27016
~~~~


and then count the items that have been added:
~~~~
db.location.count()
~~~~


Repeat the same steps for the second shard:
~~~~
mongo --host localhost --port 27017
db.location.count()
~~~~


The total of the items added to both shards should be equal to 300000


Congratulations! you have successfully deployed your first MongoDb sharded cluster.


Resources
http://docs.mongodb.org/manual/sharding/


Sunday, September 18, 2011

How to execute tasks in separate threads in Objective C

This code snippet shows how you can execute tasks  in two separate threads:


    dispatch_queue_t download_queue = dispatch_queue_create("Home View Controller", NULL);
    //first thread
    dispatch_async(download_queue, ^{               
        NSError *error = nil;
        NSArray *array = [[NetworkService getThingsByAccountId:accountId error:&error] positions];        
        //second thread, we use the main thread to run ui related activities
        dispatch_async(dispatch_get_main_queue(),^{
            [spinner stopAnimating];
                ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" array:array];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];                    
        });
    });
    dispatch_release(download_queue);    


Wednesday, January 12, 2011

How to fix blank screen due to undetected graphics card on ubuntu

I recently encountered an issue while installing Ubuntu 10.04 Lucid Lynx on a HP Proliant Desktop with an Nvidia display card. After the installation finished and i boot up the system, i got a blank screen.

Here is how this issue can be fixed:
- Boot up the system using an Ubuntu Live CD and press any key when you see a human and a little keyboard at the bottom of the screen
- press F6 and then Esc.
- Append "xforcevesa" at the end of the command line.
- Select try out Ubuntu
- Mount the hard drive (in the Places).
- Edit this file "/etc/default/grub" and locate GRUB_CMDLINE_LINUX_DEFAULT
- Change it to be like so if you have an nvidia display card: GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nomodeset"
- Edit this file "/boot/grub/grub.cfg" in the hard drive
- Locate the "linux" tag and add "nomodeset" at the end of the command with "quiet splash"
- Reboot the system without the Live CD.
- Done

Wednesday, December 22, 2010

How Garbage Collection works in Java

Garbage collection is one of the features that made Java very popular, it saved developers the burden of having to deal with pointers. This convenience came at a price though; developers had to give up control over the objects' cleanup, only the JVM can decide when to collect objects.


Heap memory arrangement:
The heap is divided into 3 main spaces:

  1. Young: contains the newly created objects. It usually contains 3 spaces; Eden and 2 survivor spaces that active objects get copied in between.
  2. Tenured: contains old objects.
  3. Perm: it holds data needed by the virtual machine.
The JVM comes with a default arrangement of generations, but you can always change their sizes to fit the requirements of your system.

Collectors:

The collectors mentioned below are stop-the-world "tracing collectors" in which a collector starts from the root reference and follows all the references until all reachable objects have been examined.  
  • Mark-sweep: It marks all the nodes it visits and after it is done, it collects the non-marked ones. It is used to collect objects in the old generation region of the heap.
  • Copying Collectors: When the space of memory dedicated to active objects fills up this collector runs and copies the live objects to another space of the heap and then switch the roles of these two spaces. This type of collectors is used to collect objects in the young generation region of the heap.
Developers have the option of running the collectors above concurrently by using the following flags:

  • -XX:+UseConcMarkSweepGC : enables concurrent collector
  • -XX:+UseParNewGC : enables parallel copying collector
  • XX:UseParallelGC : enables parallel scavenge collector 

For more details, check out these links:
http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
http://www.javaperformancetuning.com/news/qotm026.shtml
http://www.ibm.com/developerworks/java/library/j-jtp10283/

Tuesday, November 16, 2010

Cloud Computing

With all the hype going on around cloud computing and the attraction it is gaining day after day, i thought it is time for me to put my head in the cloud as well.
So I did a little research, put together some material and wrote a powerpoint presentation that you can access here.
Feel free to leave any feedback or thoughts about the presentation.