Sunday, October 6, 2013

Basics of Jasmine Framework

Hey folks today we will look into some basics of jasmine. Jasmine is a behavior-driven testing framework for JavaScript programming language. It’s a bunch of tools that you can use to test JavaScript code. you can test your code against specifications that you write. If your code should work in a certain way, Jasmine helps you express
that intention in code.




Getting Started
1. Start by downloading the latest standalone release of Jasmine (https://github.com/pivotal/jasmine/downloads). Unzip it.

2. In your html include scripts in following order:

<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/boot.js"></script>

3. Now include you spec file. This is a normal js file in which your test cases are written. So in our case it will be

<!-- Spec files-->
<script type="text/javascript" src="spec/calculatorSpec.js"></script>

Please not that always include spec file before actual code file.

4. Now we include the code file

<!-- Src files-->
<script type="text/javascript" src="src/calculator.js"></script>

Which will contain our logic

Now here are few things you need to know before we look into the code of spec file

* A describe("some name"...) is called a suite. This name of suite would usually be a component of your application.
* Inside of suite is the it() block. This is called specification. Its is a Js function that says what a small  peice of your component must do.

* Matchers: This basically takes the arguement to the expect function and checks to see if it satisfies some criterion in the matcher. for example: toEqual()

Now lets take a look at the spec

You can view the example here: http://designmantra.x10.mx/jasmine/

We are carrying out five tests here:
1. Storing current value
2. Addition yields correct results. 
3. Substraction yields correct results.
4. Multiplication yields correct results.
5. Division yields correct results.

Here is the code for spec file:

describe("Calculator",function(){
it("Should have current value stored",function(){
expect(calculator.currentValue).toBeDefined();
});
beforeEach(function(){
calculator.currentValue = 0
});
describe("Addition module",function(){
it("Should add two numbers",function(){
expect(calculator.add(5)).toEqual(5);
expect(calculator.add(5)).toEqual(10);
})
});
describe("Substraction module",function(){
it("Should substract two numbers",function(){
expect(calculator.substract(5)).toEqual(-5);
})
})
describe("Multiplication module",function(){
it("Should multiply two numbers",function(){
calculator.currentValue = 5;
expect(calculator.multiply(5)).toEqual(25);
})
})
describe("Division module",function(){
it("Should divide two numbers",function(){
expect(calculator.divide(5)).toEqual(5);
})
})
})

Here is the corresponding code for calculator.js code

var calculator = {
currentValue : 0,
add: function(num){
return this.currentValue += num;
},
substract:function(num){
return this.currentValue -= num;
},
multiply:function(num){
return this.currentValue *= num;
},
divide:function(num){
return 25/num;
}
}

Hope this article was useful. For any queries write me at prabhu.anirudh@live.in.

Saturday, August 24, 2013

Debugging a website or web application using Chrome and Android device made easy

In this post we will look into simple steps of how to debug your website or you web application on chrome desktop while you are viewing it on chrome on android. Here is what you need:

1. An android device with chrome installed on it.
2. Device drivers for that android device (must have as this will enable USB Debugging)
3. ADB extension (https://chrome.google.com/webstore/detail/adb/dpngiggdglpdnjdoaefidgiigpemgage)

Here is how you perform debugging:

Step 1. Install ADB extension in your chrome on desktop
Step 2. Install device drivers for your android device
Step 3. Enable USB debugging:
Step 4: Enable USB debugging within chrome for android as shown below:

Step 5. In chrome on desktop click on Start ADB
Step 6: Click on view inspection target to start debugging






Saturday, April 27, 2013

Introduction to SASS

In this blog post i will be giving you a short tutorial on SASS that will clear most of the fundamental syntax and how the language work.
Sass is an extension of CSS3, adding nested rules, variables, mixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
You can see how to install SASS here: http://sass-lang.com/

FUNDAMENTALS:

1.
 Declaring variables in SASS: You declare variables in SASS using following notation :: 


$blue: #00F;

This can be used in you scss file as follows:

color: $blue;

2. Declaring list in SASS: You declare list in SASS using following notations ::

$icons: twitter facebook youtube.

List comes handy when you want generate a set of element in some common fashion. For example you might wish to generate a series of divs with different background images and having same dimensions. You can do that in following manner:

@each $social in $icon{
##{$social}{background: image-url("avatars/#{$social}.png") no-repeat}
}

MIXINS:

Mixin is a way by which you can declare a reusable chunk of code. This can also be called as advanced version of variable.
Example:


@mixin border-radius($radius:10px){
border-radius: $radius;
-moz-border-radius: $radius;
-webkit-border-radius: $radius;
-o-border-radius: $radius;
}

These mixins can be used in your code in following manner:

@include border-radius(5px)

SELECTOR INHERITANCE:

In SASS, you can inherit styles from one class into another class. This can be done in following manner:

.primaryClass{
/*Style declaration*/
}

.secondary{
@extend .primaryClass;
}

This feature can come handy when you want to reuse certain style attributes across multiple classes like fonts, color.

@IMPORT

Sass extends the CSS @import rule to allow it to import SCSS and Sass files. All imported SCSS and Sass files will be merged together into a single CSS output file. In addition, any variables or mixins defined in imported files can be used in the main file.

Example:

@import "reset";

NESTING SELECTORS

Sass avoids repetition by nesting selectors within one another. The same thing works with properties.

Example for this:


.nav{
background-color: $brandcolor;
width:100%;
height: 64px;
@include setMargin("10px","20px","30px","40px");
.container{
.items{
position: relative;
.submenu{
width:96px;
@include border-radius(5px)
}
}
}
}

When compiled this will output:

.nav {
  background-color: #ac2428;
  width: 100%;
  height: 64px;
  margin: 10px 20px 30px 40px;
 }
.nav .container .items {
  position: relative;
}
    
.nav .container .items .submenu {
      width: 96px;
      border-radius: 5px;
      -moz-border-radius: 5px;
      -webkit-border-radius: 5px;
      -o-border-radius: 5px; 
}

USING LISTS AND @each

We can process a list to get some meaningful styles. Here is an example where i m creating social classes based on the list of social names that have been provided in the list.

$icon:twitter facebook youtube;
@each $social in $icon{
##{$social}{background: image-url("avatars/#{$social}.png") no-repeat}
}

BUILD YOUR OWN FUNCTION

It is possible to define your own functions in sass and use them in any value or script context.


@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { width: grid-width(5); }

LOOPING IN SASS USING FOR LOOP

We have provision in SASS where we can loop using for loop. Example of this:

$class-slug: for;
@for $i from 1 through 4{
.#{$class-slug}-#{$i}{
@if $i > 2{
width:60px;
}
@else{
width:40px;
}
}
}

As you can see in this example we are generating four classes using for loop. Within this loop we see the number of iteration and assign the width accordingly. This also shows implementation of if.

GENERATING CSS SHORTHANDS USING SASS

While working on SASS when writing this tutorials i cam across a scenario where i wanted to write a mixin that would throw me shorthand declaration instead of providing me separate declarations.
For example how would you generate a something like

margin: 10px 20px 30px 40px;

using SASS? Here's how you do it:


@mixin setMargin($top,$right,$bottom,$left){
margin: #{$top} #{$right} #{$bottom} #{$left};
}

You can use this mixin in following manner

@include setMargin("10px","20px","30px","40px");

Well this is it for fundamentals of SASS. You can also refer to this manual for trying out more stuff in SASS:
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html

Yet another good site for reference is:
http://thesassway.com/

For any queries feel free to write to : prabhu.anirudh@live.in


Saturday, December 22, 2012

Getting started with knockout js

Today we will be seeing how to work with knockout js. Objective of this article is to quickly get you up and running with this MVVM framework.

So what is Knockout JS

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

Some key things to understand:
1. observables:  model properties as observables, because these are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.

2. observable array: If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray. 

3. computed : these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.

For this article we will be creating a view model for simple ma thematic operations like addition, subtraction, multiplication etc...


The code for our view model looks as follows:


function mathematica(){

var self = this;
this.firstNumber = ko.observable(2);
this.secondNumber = ko.observable(3);
//Start off with computed values
this.addition = ko.computed(function(){
var add = this.firstNumber() + this.secondNumber()
return add;
},this);
this.substraction = ko.computed(function(){
return this.firstNumber() - this.secondNumber()
},this)
this.multiplication = ko.computed(function(){
return this.firstNumber() * this.secondNumber()
},this)
this.division = ko.computed(function(){
return this.firstNumber() / this.secondNumber()
},this)
this.squareRootFirst = ko.computed(function(){
return Math.sqrt(this.firstNumber())
},this);
//Compute the value multiplication table and assign it to the observable array
this.MultiplicationTableGenerate = ko.computed(function(){
var testArray = new Array();
for (var i = 0; i <= 10; i++) {
testArray[i] = i*this.firstNumber();
};
return testArray;
},this);
this.TableValue = ko.observableArray(this.MultiplicationTableGenerate());
this.recalculateTable = function(){
var inputtedNumber = document.getElementById("firstNumber").value;
this.firstNumber(parseInt(inputtedNumber));
var newArray = new Array();
for (var i = 0; i <= 10; i++) {
newArray[i] = i*inputtedNumber;
};
this.TableValue(newArray)
}
this.setFirstNumber = function() {
var inputtedNumber = document.getElementById("firstNumber").value;
this.firstNumber(parseInt(inputtedNumber));
}
this.setSecondNumber = function() {
var inputtedNumber = document.getElementById("secondNumber").value;
console.log(inputtedNumber);
this.secondNumber(parseInt(inputtedNumber));
}
}

in this code, we first create observables "firstNumber" and "secondNumber". Rest of the variables like addition, subtraction, etc are computed.
In case you’re wondering what the second parameter to ko.computed is (the bit where we passed this in the preceding code), that defines the value of this when evaluating the computed observable. Without passing it in, it would not have been possible to refer to this.firstNumber() or this.secondNumber().

To activate Knockout, add the following line to a 

var instant = new mathematica();
ko.applyBindings(instant)

Monday, October 1, 2012

Handling hashChange event

If you intend to build site navigation based on hash values in your URL, one of the major problem you would come across is how to deal with old browsers like IE 7. These old browsers donot support "window.onhashchange".
If you are using jquery then you can initiate the following code if "window.onhashchange" is not detected.

$('a').click(function(e){
  e.preventDefault();
  var url = $(this).attr('href');
  var hashvalue = url.substring(url.indexOf("#")+1,url.length);
  //perform some processing based on this value.
 })

Monday, August 27, 2012

Implementing adaptive ceasar cipher

In this tutorial we will see how to implement ceaser cipher in an adaptive way. Normal ceasar cipher uses a fixed length to shift the characters. Example we shift characters by fixed units example shift by 5 characters or 7 characters. We will make this algorithm adaptive by making this shifting unit variable. This unit can be based on length of the string. Here is how you will do it.


function adaptivecipher(tocipher)
{
var word_cipher = tocipher;
var word_cipher_length = tocipher.length;
var stepper = word_cipher_length;
var char_library = '0123456789abcdefghijklmnopqrstuvwxyz';
var char_library_length = charset.length;
var cipherText = "";

/*Loop and shift replace the characters*/
var index = word_cipher_length - 1;
for(;index >= 0;index--)
{
var realchar = word_cipher.charAt(index);
var place_in_char_library = char_library.indexOf(realchar);
if(place_in_char_library != -1)
{
var newcharposition = place_in_char_library+stepper;
if(newcharposition <= char_library_length)
{cipherText = char_library.charAt(newcharposition) + cipherText;}
else
{cipherText = char_library.charAt((newcharposition - char_library_length)-1) + cipherText;}
}
}
return cipherText;
}

If we want further make it effective we can shuffle the order in character library.

Sunday, July 1, 2012

Creating a simple contact us form with PHP script

Today we will be building a simple contact us form using PHP. There is not much of description needed for this task

The form



 

 

 

 

 

 

 

 

 

 

 



Once this is in place you will need to write the code of PHP which will be as follows




if(isset($_POST['email'])) {
     
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "info@domain.com";
    $email_subject = "Contacted from vergo pharma";
     
     
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.

";

        echo $error."

";

        echo "Please go back and fix these errors.

";

        die();
    }
     
    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    }
     
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
     
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.
';

  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';

  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.
';

  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';

  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Hi, Someone has contacted you from the website. Details below.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";
    $thankyou = "Thank you ";
     
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers,"-f $email_from");
@mail($email_from, $email_subject, $thankyou); 
}
die();
?>


This code will work for email accounts (a common problem that mails sent using php scripts are not received at the destination email address which is normally caused in some ISP's and servers that require that the Return-Path header email address match the From email address in order for it to be passed onto the users account.)