All about programming in GNU/LINUX


Intro to AngularJS and Client Server communication using nodeJS and AngularJS:Posting data to the Node-Express server using AngularJS

Hmmmm , its time for a new post !!! After the last post on Depth First Search in python , now you have a U-turn ahead and this post is on achieving client server communication using NodeJS server in the backend and AngularJS in the front end  !!!

If your curious on achieving client-server communication using backbone.JS and nodeJS , here is the link
In case you try the same using websockets and nodeJS , here is the link for the post .

And here is the github link for the codes posted in this blog !

Lets get started with how to achieve it using Angular and NodeJS as server .This might be a very simple task for a AngularJS developer ,but the blogs are not always meant for experts 😛  Since the blog is aimed at web developers who are starting to develop web applications by using NodeJs in the backend and AngularJS in the front end , ill try to keep the post as simple and easy as possible .

So , Lets get started ……….

Before we begin here are the basics of AngularJS ,

  • AngularJS provides a set of html attributes which starts with ng , example ng-app,ng-controller,ng-view,ng-click , these attributes are used to direct and communicate with angularJS .
  • ng-app attribute tells angularJS to bootstrap or start the application , usually this is associated with the html tag of the application , example 
<html ng-app>
         <script src=""></script>

 controllers in AngularJS

  • Using controllers you can tell AngularJS ,which of javascript variables or primitives forms the Models data which will be used the views
  • Angular by default passes this object called $scope for every Angular controller
  • By assigning the data to this $scope object you’ll
    be telling angular that the assigned data are those which are supposed to be the used by views to render HTML , this is the model data

To brief , the controllers in angularJS have three responsibilities
1.Initializing the model variables
2.Give views the access to the models data by assigning them to the $scope variable
3.It provides the code and logic to execute while users interact with the various parts of the controllers

$http is another directive passed onto a controller and can be made use of to interact with server (make GET,POST requests etc…) , we’ll be using same directive in this post to interact with the server

One of the amazing feature of Angular which makes application development really easy is the ability of Angular’s controller to bind the data of an HTML element (like a input box , text box or any widget) with the models data and it also provides event handlers/methods to propagate the changes to the model data automatically  

Here is an simple example of how controller binds the data and the views , a angular controller is binded to the application by using ng-controller attribute  within a html element , the controller will be incharge of the application within the scope of that html tag,the explanation is given after the code example  

<html ng-app>
    <script src=""></script>
      <div ng-controller="firstController">
      <!--firstController is the name of the controller function, its scope expands within this div element -->
        <input ng-model="modelData" >

         function firstController($scope){ //controller function
 /*This is the same variable which is used in html,now the value is variable is binded the input box data*/
             console.log("New: "+newVal);/*Watch the browser console*/
           /*$scope.$watch listens to the changes in the modelData variable ,
             The value in the modelData variable is changed when the value in the input box is changed ,
             these are automatically bound together  using <input ng-model="modelData" > */

ng-model=”modelData”, This is like a global declaration of the variable ‘modelData’ within the controllers scope(within div element in this case) without the need to declare it anywhere .This variable now can be accessed as model data inside the html to render by using it inside the double braces {{}}, this is how you can bind the data with the views . Now lets say you have some application logic to be performed using this data , so you need to be able to access the variable within the Javascript too , the variable `modelData` can be accessed only within the controller function (inside your javascript) which is incharge the current html scope , in this case the data is accessible through the firstController() , controller function (since this is the controller function for the input elements scope,that is, the input element inside the scope of the div with ng-controller=”firstController”).Now as i had already mentioned the model’s data can be accessed using the $scope object which is passed onto the controller,so this can be accessed using $scope.modelData inside the controller function of the Javscript
ng-model=”modelData suggests that the $scope.modelData is the controller variable with which this view is associated,and this is how angular easily brings in binding of the views and data with the help of the controller.
Now lets say you have used {{modelData}} at ten different places in your html to render the view , the change to the modelData is automatically propagated to all thee places in views so that the html with new data is rendered
Here is the screenshot on with the browsers console opened

Angular MVC

Angular MVC

Phew!!!!! 😯 Lets now start with the headline of the post …How to communicate to the server from angular ,and how to handle it using NodeJs-express server
Here is the code snippet ang2.html of where angular makes a POST request to the server when user clicks the submit ,

<html ng-app>
    <form ng-controller='appController' ng-submit="send()">
      <!--send() function from the controller is called on form submission -->
        <textarea ng-model='data.textdata'></textarea>
        <input type="submit" ngClick="Submit">

    <script src="">
        function appController($scope, $http) {
            /*$http directive is used to communicate ot the server */
            $ = {}
            $scope.response = {}

            $scope.send = function () {
                /*executed when submit is clicked*/
                console.log("inside click");

                var posting = $http({
                    method: 'POST',
                    /*posting to /post */
                    url: '/post',
                    data: $,

                    processData: false
                posting.success(function (response) {
                    /*executed when server responds back*/
                    $ = response;


Here is the server code app.js using node.js-express to handle the POST request from the AngularJS frontend script and respond back to it .

var express = require('express')
, http = require('http'), path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));
/*JS client side files has to be placed under a folder by name 'public' */
/*to access the posted data from client using request body*/'/post', function (req, res) {
    /* Handling the AngularJS post request*/
    res.setHeader('Content-Type', 'application/json');
    /*response has to be in the form of a JSON*/
    req.body.serverMessage = "NodeJS replying to angular"
        /*adding a new field to send it to the angular Client */
    /*Sending the respone back to the angular Client */

http.createServer(app).listen(3000, function () {
    console.log("Express server listening on port 3000");

Create a folder called public and place ang2.html inside it
, Here is the link for the codes published in this post

Here are the screenshots from server and client side ,

Angular posting data

Angular posting data

server handling client angularJS request

server handling client angularJS request

fianlly !!!!!!!!!!!!!!!!thats the end of this post , i hope you guys found this post to be helpful in understanding how to use AngularJS to communicate to the server , will catch up soon with further exciting posts , till then Happy coding 😀

Algorithms using python:Graph Algorithms-1:Depth First search

Firstly hello to all the readers !!After the last and its previous post on node.js , Here is the first post of the series of posts to come related to algorithms using python.In this post Ill be discussing about popular tree traversal algorithm Depth First Search . Using python makes the implementation of the algorithm relatively easy because of the availability of numerous built in data structures like hashes(dictionaries) ……….In this this blog post ill be using dictionaries as the main data structure for most of the operations .I’ve tried my best to enhance the degree of detailing in the post so that folks with even least acquaintance with python can understand the code . So then what are we waiting for??? Lets begin 😛


A graph will represented using a JSON like structure . here is an example …

Consider the following graph


Here node A is connected to nodes B,C and E and this is represented as described below


‘A’:{‘B’:1,’C’:1 }


Using the similar approach here is the representation of the complete graph










  • Declaration of a dictionary

Declaring an empty dictionary in python very simple , the line below illustrates it

      example_dictionary = {}             

Now lets see given tuples containing the pair of codes between which there exists an edge , how to convert them into graph

representation given above and store them in dictionaries ,Here is the tuple representation of connected nodes of the above graph


def make_link(G,node1,node2):
	if node1 not in G:
		G[node1]= { }
	(G[node1])[node2]= 1 
	if node2 not in G:
		G[node2]= {}
	(G[node2])[node1]= 1 
	return G 
anil_akg rediff

connections = [('a','g'),('a','d'),('d','g'),('g','c')]
G = {}
for x,y in connections:make_link(G,x,y)

print G 


Here are the key points that could help you understand the above operations on dictionary G

G= {} #initializes the empty dictionary
G['A'] = {} #Creates a key 'A' in the dictionaries and assigns the key to a value of another empty hash
(G['A'])['B'] = 1 #Creates a Sub-Hash for key 'A' of the hash,Sub-hash is {'B':1}
print G

Here is the screen shot with the above mentioned operations , this will help you understand the process of representing a Graph similar to JSON using dictionaries .


2.Concept of Depth first search

As wikipedia quotes “Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

Now let us traverse the above graph using Depth-First-Search.Lets start from node ‘A’ and then move to any of its neighbouring nodes,lets say ndoe ‘C’ , mark these nodes when you visit them for the first time , ‘C’ has only one neighbour ‘G’,so move to node ‘G’ .’G’ has no neighbours so now start backtracking,move to the previous node , that is node ‘C’,node has no more unvisited neighbours , ‘G’ has already been visited.So now backtrack to ‘A’ ,since ‘C’ has already been visited now move on to an unvisited node of ‘A’ , lets say ‘B’ , this process repeats till all the nodes of the graph are visited ,Here is the python code to achieve the some

def make_link(g,node1,node2): #function to construct the graph in JSOn like format 
	if node1 not in G:
	if node2 not in G:

G={} #initializing the empty grapgh
connections = [('A','B'),('A','C'),('A','E'),('B','D'),('B','F'),('C','G'),('E','F')] #tuples representing the connections

for x,y in connections:make_link(G,x,y) #constructing the graph using tuple representation 

print G

def dfs(G,node,traversed):
	traversed[node]=True #mark the traversed node 
	print "traversal:"+ node 
	for neighbour_nodes in G[node]: #take a neighbouring node 
		if neighbour_nodes not in traversed: #condition to check whether the neighbour node is already visited
			dfs(G,neighbour_nodes,traversed) #recursively traverse the neighbouring node 

def start_traversal(G):
	traversed = {} #dictionary to mark the traversed nodes 
	for node in G.keys(): #G.keys() returns a node from the graph in its iteration
		if node not in traversed: #you start traversing from the root node only if its not visited 
			dfs(G,node,traversed); #for a connected graph this is called only once 


The comments in the code explains everything . The worst case time complexity of DFS is of order n*m , ‘n’ is the number of nodes and ‘m’ is no of edges .We’ll thats it for now,hope that this post helped you understand the implementation of D.F.S in python 😀 see you folks soon with more exciting posts,this is the link to the code from my GITHUB profile

Obtaining user logs! (Task 1)

Good post!

Karthik Srivatsa

Out of a lot of options that we had, we opted for OpenCart ( ) for our front end e-commerce solution. So the first step was to download and configure open cart over a locally running LAMP server. The steps for setting up the OpenCart site on your Apache server can be found here : ” ” .




Apache provides a mod_usertrack ( “ ” ) module for logging the user activity by using cookies and generates a ‘clickstream’ log. An enhanced version of the same module can be found here by the name mod_cookietrack : ” ” . This module requires apache-dev to be installed and perl. After that you install it using the command ‘sudo ./’.


NOTE : If you have errors saying that apxs file is not found in /usr/sbin/apxs try to look for it in the folder /usr/bin/apxs and…

View original post 465 more words

Sending GET ,POST requests to the server using Backbone.JS and handling them using Node.JS server in the backend

In the last post i discussed about  communicating with the webServer from the browser in the front end using WebSockets .This post too is about sending requests (GET , POST) to the web-server from the browser , but i’ll be employing a different methodology this time around .

So , You might be very curious now about the methodology i’ve employed to interact with the server in this post 😯 😀

In this post  ill be discussing about sending requests to the Node.JS server using Backbone.JS in the front end , Backbone.JS sends AJAX requests to the server.

Backbone.JS is a front end Javascript Library which helps you keep your web application more organized by following MVP(Model View Presenter) approach and it is capable of communicating with the server in RESTful fashion .

First Lets lets see how to send GET request to the server using Backbone.JS and handling it at the backend using NODE.JS webserver which is built using the express framework . Basics of using express framework is also discussed in the last post .

Here is the link for the code from my repo

Here is the Front end code using Backbone.JS to send GET request to the server

<!doctype html>
<html lang="en">
		<title>Backbone App</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<script type="text/javascript" src=""></script>
		<!--  Underscore.JS is the dependency library for Backbone.JS-->
		<script type="text/javascript" src=""></script>
		<!-- Jquery is used for DOM manipulation-->
		<script type="text/javascript" src=""></script>
		<!--Fieldset helps logically grouping the HTML elements  -->	
			<legend>Post Data To Node.JS Server</legend>
			<!-- Input Field to Enter the data to be sent to the server
				Backbone.JS code is written to send POST request to the server 
				on clicking the button -->
			<input type="text" id="course_type" placeholder="Enter the Course Name" required />
			<input type="button" id="post_data" value="Send data to the Server" /> 
	    	<legend>Get Data From Node.JS Server</legend>
	    	<input type="button" id="get_data" value="Get Data From Server">
	    	<!--Backbone.JS code is written to send GET request to the server on clicking the button -->
		<div id="data"></div>
		<!-- Div element where data from the server is placed-->
	<!-- Backbone.JS code starts here -->
	<script >
			Courses = Backbone.Collection.extend({
				console.log('Post Clicked');
				console.log('Get Clicked');
			function get_data_from_server(){
				var courses = new Courses();
				 		data = data_array.models[0].attributes;
				 		data = JSON.stringify(data);
				 		var data = "<p>" + data + "</p>" ; 
			function post_data_to_the_server(){
				var courses = new Courses();
				courses.fetch({data:{course_name:$('#course_type').val()},type:'POST' });



 All the functions which start with ‘$’ are derived from JQuery . Plain Javascript can be used instead of JQuery ,its just that coding becomes easier on using Jquery . Backbone Collection is an entity to hold a collection of data .The ‘url’ in the backbone.collection.extend() specifies the URL to which the request to be sent. By using Jquery’s $(‘#button_id’).click() callback functions are associated to the button , which gets executed on click of the button .Backbone.JS sends AJAx requests to the server.
function get_data_from_Server is used to to send GET request to the server Collection.fetch() sends a get request by default and fires the success function when it recieves a reply from the server with data attached in JSON format .Model is an individual entity and collection is a set of different instances of same model.The returned data contains an array of models and its attributes are picked and added onto the html of the page after which the data returned from the server is displayed on screen , Function post_data_to_the_server() is used to POST data to the server.The type:POST argument to the collection.fetch() in the below code makes sure that POST request is sent to the server with the data

Place the html inside a folder called public inside the root of the folder where server.js file is placed. Here is the code for Node.JS server to handle the Bakcbone request

var http = require('http');
var express = require('express');
/* Express Web Development Framework is used */
var app = express();

/* Specifying the public folder to place the static html and javascripts */

/* app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it */
	console.log('Get Request obtained from Backbone.JS');
	data = {
		author:"Karthic Rao",
		backend:"NODE.JS and Express"
	} /*data to be sent to the client */
	/* The response type should be a JSON */ 
    /*The Javascript Object is converted to JSON and sent
     back to the browser as response*/
/*app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it*/'/courses',function(req,res){
	console.log('Post Request Accepted' );


Intructions to the run the application

1.Install the server’s dependency module[express in this case]

npm install express 

2.Save the server code as server.js and place the html inside the public folder as course.html

3.Run the application

node server 

4.Go to browser and visit 

Here is the snapshot of the application from browser window


I hope that this blog helped you guys understand the basics building a web application with node in the backend and Backbone in the front end , see you guys soon with another exciting post …..Till then Happy Coding 😀

Client-Server communication using Websockets and Node.JS[express,]


Hello ppl …………. !!! Its been a long long time since the last blog ….Well , be ready for raining techie-geeky Blogs 😀

What are the various ways you guys can think of using which data can be sent to the server from the front end …hmm,,,,, By Posting data to the Server ?????? Yes , data can be sent to the server by posting the required data from HTML forms . hmm,,,,,,Using AJAX ????Yes , AJAX is a very popular implementation using which browsers can interact with the server .But the question now would be “Dude the title of the post  suggests that Web-sockets too are used to interact and send data to the server ,  Then what the hell is a Web-socket 😯 , How different is it from other means by which data is sent to the server  😕 “

Now  you know that web-sockets are one of the means by which the front end JavaScript can interact and send data to the server , But here are the reasons why it is very different from other implementations which are used to achieve similar objective.Ever since the onset of web applications, developers have worked towards different ways of getting duplex communication between the server and the browser. Be it using Java, Flash, Comet, or many other workarounds, all aim to do the same. But for the first time, there is a specification to build a full-duplex communication system by using HTML5 WebSockets. WebSocket is a revolutionary, new communication feature in the HTML5 specification that defines a full-duplex communication channel operating over the Web through a single socket.It is not, and will never be, available on older browsers that are still in use. is an abstraction layer for WebSockets,with Flash, XHR, JSONP, and HTMLFile fallbacks. provides an easy server and client library for making real-time, streaming updates between a web server and a browser client.
The Wiki page “Unlike HTTP, WebSocket provides for full-duplex communication. Additionally, Websocket enables streams of messages on top of TCP. TCP alone deals with streams of bytes with no inherent concept of a message. Before WebSocket, port 80 full-duplex communication was attainable using Comet Channles; however, Comet implementation is nontrivial, and due to the TCP handshake and HTTP header overhead, it is inefficient for small messages.

Summing everything up , the advantage of websockets are listed below ,

  • The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content without page refresh
  • Websockets are amazingly fast compared any other alternative implementations , so it can be used for creating Real-Time web applications (Games , Live News feed)
  • Websockets are Standardized being part of HTML5
  • Support across all major browsers
  • Ease of use

Ahhhhh , i believe all of you had enough going through the details of webSockets 🙄 😀 Lets start with how to make use of WebSockets features using Node.JS server in the backend . This is not an introductory tutorial on Node.JS ( Here is an introductory tutorial on writing WebServers using Node.JS ) .

Here are The NodeJs modules which are used in coding the backend .

  • Express – It is a Web Development  Framework for Node.JS ExpressJS
  • Socket.IO – is a node module available through the npm,It has two parts: a client-side library that runs in the browser, and a server-side library for Node.JS. Both components have a nearly identical API. Like node.js, it is event-driven.( Client side JavaScript to be included will be generated dynamically by this module.

       Installing the dependencies

npm install express
npm install

The Server

var express = require('express');
var http = require('http');
var io = require('');

var app = express();
//Specifying the public folder of the server to make the html accesible using the static middleware

var server =http.createServer(app).listen(8124);
//Server listens on the port 8124
io = io.listen(server); 
/*initializing the websockets communication , server instance has to be sent as the argument */

	/*Associating the callback function to be executed when client visits the page and 
	  websocket connection is made */
	  var message_to_client = {
	  	data:"Connection with the server established"
	  /*sending data to the client , this triggers a message event at the client side */
	console.log(' Connection with the client established');
		/*This event is triggered at the server side when client sends the data using socket.send() method */
		data = JSON.parse(data);

		/*Printing the data */
		var ack_to_client = {
	  	data:"Server Received the message"
		/*Sending the Acknowledgement back to the client , this will trigger "message" event on the clients side*/


Save the code in a file called server.js , run it using node executable (node.js should be installed on the system) ” node server.js ”

Create a folder by name public and place the html file inside it .

Here is socket.html file which handles the client side connection (save it inside a folder named public within the root directory of the server file)

<!DOCTYPE html>
<html lang="en">
		<title>webSockets and Socket.IO</title>
		<script type="text/javascript" src="/"></script> 
		<!--The above library(/ will be generated by module of server -->
		<script type="text/javascript" src=""></script> 
			<input type="text" id="message" /> <!--text form to send data to the server-->
			<input id="submit" type="button" value="Send data to Server">
			<div id="content"></div> <!--This is where the data from the server is added-->


		<script type="text/javascript">
			var socket = io.connect("/"); 
			/*Initializing the connection with the server via websockets */
					When server sends data to the client it will trigger "message" event on the client side , by 
					using socket.on("message") , one cna listen for the ,message event and associate a callback to 
					be executed . The Callback function gets the dat sent from the server 
				console.log("Message from the server arrived")
				message = JSON.parse(message);
				console.log(message); /*converting the data into JS object */
				$('#content').append('<div >''</div>'); /*appending the data on the page using Jquery */
				$('#submit').click(function(){ /*listening to the button click using Jquery listener*/
					var data = { /*creating a Js ojbect to be sent to the server*/ 
						message:$('#message').val(), /*getting the text input data  	*/
					/*Data can be sent to server very easily by using socket.send() method 
					The data has to be changed to a JSON before sending
                                          it (JSON.stringify() does this job )*/
					/* This triggers a message event on the server side 
					and the event handler obtains the data sent */ 

					//Emptying the text box value using jquery 



Go to the browser and visit the URL

The comments inside the code explains it

Here is the screenshot of the application


Hope that this blog was very interesting and helped you to understand how to use websockets to communicate with the Node.JS server …..Will come back soon with lot more exciting posts , till then Happy Coding 😀





2013 in review of the blog

The stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 11,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 4 sold-out performances for that many people to see it.

Click here to see the complete report.

Backbone.js – Listening to DOM events using backbone.views

Writing Backbone.js applications requires three dependies , the Jquery Library , Underscore.js and Backbone.js libraries , this illustrates the simple task of associating a listener for the click event on the checkbox element on the DOM, Backbone.js provides all the necessary functionalities to make a fully fledge web applications , it is well known for the implementation of the MVc architecture , use Ctrl+shift+K in the firefox browser to open the Javascript console and view the console log

	<meta charset="UTF-8">

	<script src="">
	<script src="">

	<script src="">
		$( document ).ready(function() {
		/*Enclose the script under Jquery Document.ready , this makes sure that the script is executed after the DOM 
		elements on the browser is loaded */
    		var View = Backbone.View.extend({

			el : '#listen_to_box' , 
			/*associate  DOM element on which you want to work on , 
			In this case #listen_to_box is the ID of the div element with the  checkbox */
			events: { 
				'click [type="checkbox"]':'clicked', 
				/*associate an event listener 'clicked' for 
				the click event on the checkbox , this is done using the Views events property*/
		clicked : function(event ) { /*The Handler function for the click event on the checkbox*/
			console.log("events handler for "+  this.el.outerHTML);
			/* el.outerHTML has the markup or the HTML code of the DOM element associated with el, 
				in this case the 'div' element with the id of #listen_to_box is assigned to el */ 
	var view = new View();
	<div id="listen_to_box">
		<input type="checkbox" />


Js console

Js console