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

<!DOCTYPE HTML > 
<html>
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

	<script src="http://code.jquery.com/jquery-1.10.2.js">
	</script> 
	
	<script src="http://underscorejs.org/underscore-min.js">

	</script> 
	<script src="http://backbonejs.org/backbone-min.js">
	</script> 
	<script>
		$( 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();
			
});
					
	</script>
	
	<div id="listen_to_box">
		<input type="checkbox" />
	</div>

</body>
</html>


Js console
Js console
Advertisements

Using Semaphores and Mutex in Linux Device drivers to tackle concurency

Semaphores provide a satisfactory solution for issues related to concurrency . Access to critical section is controlled by enforcing threads to hold a lock before entering the critical section , Without a semaphore being unlocked no thread is allowed access to execute in the critical section .

Semaphore is a single integer value bound to two functions P and V . P is called down or some variation of that name and V is called up . Function P is used to lock the critical region and V is used to unlock . Function P decreases the count of semaphores , for example from 1 to 0 . When the value of the semaphore still remains 0 or less no other threads are allowed to execute in the critical region . There are made to wait or even may be put to sleep till the region is unlocked .

Functions of type V releases the semaphores that’s being help , these category of functions increases the value count of the semaphore and may even wake up the processes waiting for the access into the critical region .

Semaphores are generally and mostly used for the purpose of mutual exclusion , that is to make sure that only one thread of execution or a process executes in the critical section .

 Linux Implementation of Semaphores

<asm/semaphore.h> defines several functionalities for semaphore and mutex implementation ( Mutexes are just a special case of semaphores ) .

To initialize a declared semaphore ,

void sema_init(struct semaphore *sema, int val) can be used ,

 this initializes the declared mutex to value val ( The second argument to the function ) ;

But , as i had mentioned earlier semaphores are generally used for implementation of mutex ,

the following two functions declare and initialize the mutex

DECLARE_MUTEX(mutex_name ) ;

DECLARE_MUTEX_LOCKED(mutex_name) ;

 These functions declares mutex named as ‘mutex_name’ , the function DECLARE_MUTEX declares the mutex and initializes it to 1 ( 1 is the unlocked state , a thread or a process can possibly lock the critical region ) , wherein the later function declares the mutex and initializes it to 0 ( 0 is the locked state ) , mutex has to be explicitly unlocked before it can be used for locking .

 

 For initializing the mutex at runtime the following functions can be used ,

void init_MUTEX(struct semaphore *sema ) ;

void init_MUTEX_LOCKED(struct semaphore *sema) ;

 Holding and releasing Mutex ( The version of P [down] and V[up] functions )

 Linux kernel provides three versions of down function

  1. void down(struct semaphore *sema) ;

  2. int down_interruptible(struct semaphore *sema) ;

  3. int down_trylock(struct semaphore *sema ) ;

As briefed earlier down decrements the value of the semaphore , successful exection of any version of down function leads to locking of the critical region of the code , and the thread of execution or the process is said to have acquired the lock . Other user space process trying to access the critical region of code will be made to wait .

In case of the first version of down ( void down_interruptible() ) , the user space process waiting for the mutex to be released cannot to interrupted , it’ll be running in a dreaded state . This is not desirable in many cases , so the second version of down allows the waiting user space process to be interrupted .

The third version can used to test and lock , if the lock is already being held the function returns with a negative value , If no other thread is holding the lock , the lock will be acquired . Using down_trylock() the process wont wait for the acquired lock to be released , it returns immediately .

void up(struct semaphore * sema) is used to unlock the acquired lock and even wake up the processes waiting on the semaphore .

When executing in the critical region on occurance of error its very important to unlock the region before returning

 

 

 

 

 

Concurrency issues in Linux Device Drivers and protection from concurrency

Concurrency was not a big issue till kernel support was introduced for SMP systems . Before there were only few sources of concurrency like the interrupt handling context , but with introduction of kernel support for SMP systems it also drastically increased the chances of  code being vulnerable for concurrency issues .SMP (Symmetric Multi Processing ) systems involve architecture with multiple processors , this introduces the possibility of the same code snippet being run in more than one processors at a given point of time . Codes running in kernel context are pre-emtible too , it may lose the processor at any point of time and the process scheduled next may run in your driver .There are surprisingly many ways where the Device Driver or a program running in kernel context becomes vulnerable for concurrency related issues , In the computing world where one in a million probable event too can happen every second bugs related to concurrency are difficult to identify even for expert kernel developers .

Reasons for concurrency

Consider this small code snippet in your driver

if(!dptr->data[block]) { //1.check whether memory is already allocated 
    dptr->data[block] = kmalloc(block_size , GFP_KERNEL); //2.allocate memory if its not allocated 
    if(!dptr->data[block] ) //3.check whether the memory allocation was successful 
         end the program ; 4.//exit if memory allocation fails 
}

Consider the case wherein processes A and B both try to access the driver . When both A and B arrives at the condition to check for memory allocation (line 1 ) , both predicts the memory to be not to be allocated and moves ahead executing the lines to follow allocating the memory .

The second process to allocate memory by executing kmalloc() wipes out the memory allocated by the first process . The second process gets the inconsistent view of the variable .

Such piece of code which is vulnerable for concurrency related bugs should be protected , such snippet of code is called as critical region of code . Critical region code should be protected from concurrent access , access to the critical region of code should be controlled and managed .

There are few rules following which the concurency related issues can be minimized and solved .Reduce the use of shared resources

  1. Hardware resources are shared and likewise many structures and variables too are accessible for any no.of.threads of execution , unless there is a strong reason its better not to make use of shared resoures ( like global variables ) .If there are no shared resources there wont be any concurrency issues , but sharing is often required and all varialbles in the driver by default is accessible all threads of execution .

  2. Use kernel’s locking primitives to manage and control access to critical region, if critical section of code is secured or prevented from multiple processes to execute simultaneously the issue can be solved .Kernel Provides different primitives to handle concurrency related issues since the triggering factor for all concurrency related issues are not same . Concurrency in the driver may be purely due to access from user space or code executed by asynchronous events like interrupt handling or kernel timer mechanisms . 

Ways of protecting critical section of code from concurrent access and kernel primitives and API’s that can be used in device drivers to protect the critical section of code will be discussed in the next post . Till then have great time coding ……….. 🙂

Simple CSS3 Transformations – transitions , translations and rotation

 W3C consortium was setup to standardize different browser interpreted languages , but different browser vendors wanted to provide support for experimental css3 features till they are standardized by W3C , such experimental and browser specific css3 features are to used with the prefix provided the vendor , -webkit-(chrome and safari),-o-(opera),-moz-(firefox),-ms-(IE), in the following code snippet i’ve just used -webkit- prefixes , so the code just works in Google chrome browser , to make it work in other browsers , just repeat the attributes with the vendor specific prefixes 

Image

<!DOCTYPE html>
<html>
<head>
<title>First Transform </title>
<style>
h1 {
text-align : center ;
font-family : Futura ;

}
h1:hover {

-webkit-transition :6s all steps(6,end);
-webkit-transform : translateX(600px);
/* the header (h1 ) moves on X-axis (translates) 600px to the right , but the transition(webkit-transition) effect in place
makes sure that this transition takes place over a time of 6 seconds and 6 steps on mouse hover */
}
img.tilt:hover {
-webkit-transform : rotate(9.0deg); /*Rotates the image by 9 degrees on mouse hover and transition makes the effect take place smoothly over a period of 5 seconds */
-webkit-transition : 5s all;
}
</style>
</head>
<body>
<h1>CSS3 Testing</h1>
<p><img src = “deb.jpg” style= “width:300px;height:200px; margin: 0 2em 2em 0;”class=”tilt” >Hi , this is Debian , Debian is a free Operating system , the kernel used by debian is the kernel written Linux torwals .Debian is a free and universal operating system where everything , i repeat , everything in the operating system is free , the source for every binary in DEBIAN is available, All the softwares for debian comes packaged in .deb(.debian) files where these are hosted in their official repositories </p>

</body>
</html>

Intro to HTML 5 Geolocation :Find the locational data and getting it on the Map

HTML 5 brings in lot of powerful features along with it , one of such fascinating feature is the capability to code locational based applications using the `Geolocation and Goolge MAPS API’s `

In this post i’ll be briefing you folks on obtaining your locational reference in terms of latitude and longitude and using the same to get the MAP on the webpage centred around your current location

There are 3 parts to be coded to achieve the objective.The HTML5 code where the execution starts and links to the Java Script file and the CSS stylesheet

Here is the HTML5 code which is pretty much straigh forward

<!doctype html>
<html>
<head>
	<meta charset = "utf-8">
	<title>Location</title>
	<script src="http://maps.google.com/maps/api/js?sensor=true"></script> 
        <!-- To link to the google map API's -->
	<script src="loc.js"></script>          
	<link rel = "stylesheet" href="myLoc.css">
</head>
<body>
	<div id="Location">
		Here comes the location              <!-- Place Holder for the locational data -->
	</div>
	
	<div id="map">				     <!-- Place holder for the Map -->	
	</div>

</body>
</html>	

The Java script part is the most important snippet to get this working , here goes the Java Script Code 😀

var map=null;


window.onload = getLocation ;

function showMap(coords) {
	var googleLatAndLong = new google.maps.LatLng(coords.latitude,coords.longitude);
	var mapOptions	= {
		zoom: 10, 
		center: googleLatAndLong ,
		mapTypeId: google.maps.MapTypeId.ROADMAP	
	};//The option object specifying the options for the map
	var mapDiv = document.getElementById("map");
	map = new google.maps.Map(mapDiv,mapOptions);//API which gets the map
}




function getLocation() {
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(displayLocation); 
//The API calls the display location function with position object containing the positional parameters
	}
	else {
		alert("Doesnt support Geolocation");
	}
}
function displayLocation(position) {
	var latitude = position.coords.latitude ; 
	var longitude = position.coords.longitude ;

	var div = document.getElementById("Location");
	div.innerHTML = "You are at latitude: " + latitude + " Longitude: " + longitude;
	showMap(position.coords); 
	//showMap function takes in the positional parameters and displays the map
}


Here the CSS code for the map id

div#map {
	margin: 5px;
	width: 400px;
	height: 400px;
	border: 1px solid black;
}

Writing A Simple WebServer using NODEJS

Well , we should consider ourselves lucky to be in this age of computing where a programmers job is made very easy with usage of modern languages . Writing a Web Server using C was and is a herculian task . With issues like limited buffer size , spawing threads or new processes to cater new clients and bulky system calls with complex structures to pass as parameters everthing has to be explicitly managed . One of the easiest way which i’ve found out to write webservers is by using NODEJS . Concurrency handling mechanisms are taken care of implicitly and programming becomes easy since Java Script is used .Here is a simple webserver written using NODEJS

var http=require('http'),
	url = require('url'),
	mime = require('mime'),//npm install mime
	fs = require('fs'),
	search_path='/home/karthic/mydata/codes';
http.createServer(function(req,res) { 
	 pathname = search_path + req.url;
	 console.log(pathname);

	fs.stat(pathname , function(err,stats){
	  if(err) { 
		res.writeHead(404);
		res.write('Bad Request , Request cannot be accepted');
		res.end()
		}
	else if(stats.isFile()) {
		//content-type
		var type = mime.lookup(pathname);
		console.log(type);
		res.setHeader('Content-Type',type);

		// 200 status - found , no errors 
		res.statusCode = 200;
	
		//create a readable stream and pipe to the http response 
		var file = fs.createReadStream(pathname);
		file.on("open",function() { 
			file.pipe(res);
		});
		file.on("error",function(err) {
			cosole.log(err);
		});
	     }
	else {
		res.writeHead(403);
		res.write('Cannot Access Directory');
		res.end();
		}
	});
}).listen(8324);//listen to port 8324
console.log('Server running at 8324');