Thursday 9 August 2012

Ruby


              Ruby is a scripting language which is need no be compiled. The code will be interpreted. It supports Object Oriented programming. Even the basic data types are objects. It is dynamically typed as in Javascript. It is a server side scripting language.
              The class of each object can be known using the ".class" command.
            For example : 10.class will return Number.
            Similarly "10".class will return Fixnum.
             Each class is associated with member functions. For example we can convert a string object into a Fixnum using the to_i method.
              The methods can either be for a class or for an instance of the class. The class methods will have self keyword. They can only be accessed by the class name. The instance methods will be accessed by the instance names.
              Similar to the constructors in the C++. there is a special method called as initializer in the Ruby. This method will be invoked  whenever a new instance is created.
             There are private and public variables too like c++. But they have different syntax.
             There are access specifiers such as attr_reader which allows public read of the particular variable. attr_writer which allows public write of the variable. There is attr_accessor which allows the variable to be both read and written in public.

Containers :
              The container objects available in the language are array and hash. We should specify the key and value pairs in for the hash. If we want to access the value all we need to do is use the key to access the variable.
             The syntax for the array is ,
              a = [1,2,3,4,5]
             and for a hash,
              h={"1"=>prem,"2"=>anandh}
             In the above we can access like,
             puts a[0]
             puts h["1"]
             The output is,
             1
             prem
             
Control Structures and loops:
              The control structures include if(condition), elsif(condition) statements doing the job of the if(condition) and the else if(condition) of the C++. There is an option called as unless structure. The working

             if(condition)                      unless( ! condition )
             #some_code                      #some_code
            end                                     end

             If the condition is true in if the #some_code will execute and the opposite is there in unless.

              There is a syntax called as
               case (option) when match1 when match2 end
                This is similar to the switch case in ruby. It is a multi branching statement unlike if else.
                 The loops in ruby are,
                 for, while and until. The first two are familiar as they are similar to the loops in C++. The for loop has syntax like,
#  If you're used to C or Java, you might prefer this.
for element in collection
  ...
end

#  A Smalltalk programmer might prefer this.
collection.each {|element|
  ...
}

Coming  to until .
       until (condition1)                     
       ....                                             
       end                                           
        In the until loop the loop will continue till the condition is true.

There are options for loops like:
   5.times {p "*" } #print "*" 5 times.
   3.upto 6 {p "*" } #prints "*" 3 ( 3 to 6) times.

Classes and objects:
         Classes have their name preceded by the "Class" keyword. We can create the objects using the "new".
          object = Class_name.new

Inheritance:
             Inheritance in ruby is done by the "<". Here there is a base class
              class some_class < parent_class
              ...
              end
               Here the class some_class is inherited from the parent class.

Procs and Lambda and Blocks:
               Well i might call Procs as generic functions which can be passed as parameters and then they could be called from there. The syntax and working of these are listed at the site http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
                Procs and Lambda are similar but the only two differences between them are,
  1. Lambda's check the number of parameters getting passed.
  2. Lambda's let the method execute even after it has returned a value but  Procs don't.  Procs will return the control the out of the function once it returns the value.
I also came to know about meta programming in ruby and ROR and how well these languages support meta programming. It still was confusing and thought that I will know in depth once I am used to programming in ruby and ROR.

A block is also a Proc.

Scope in Ruby :

Name Begins WithVariable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@A class variable

                 The above mentioned table contains the table having the ruby variables and their scope. For clarifications in details visit http://www.techotopia.com/index.php/Ruby_Variable_Scope

Ranges :
          Ruby allows a new concept of ranges where you can specify the start and end of the range and you the intermediate values will be automatically generated.
              Ranges can be used as conditions, intervals and sequences.
            For example :
             if  marks == 0..49
                  puts "fail"
              else
                   puts "pass"
           Thus the above code will give "fail" is the mark is between 0 and 49. There are two ways of creating ranges.
             using "start..end"  and "start...end".  The first range is from start to end and the second one is from start to value_previous_to_end.

Iterators :
         Ruby offers two iterators. They allow us to traverse through the collections. They are .each and .collect.
        .each will not return any individual element while the .collect returns a new collection.
        For example :
        ary = [1,2,3,4,5]
        ary.each do |i|
           if( i%2==0 ) puts i
        end
        The output is,
        2
        4
        And for the .collect operator.

        ary = [1,2,3,4,5]         new_ary = ary.collect{ | x |  10*x }
        puts new_ary
        The output is,
        10
        20
        30
        40
        50
        Thus we can manipulate the values in the original array and return the new array to new_array.

Tuesday 7 August 2012

JS-OOP and event handling

OOP:
    In Javascript everything you can manipulate are objects. They include all the Strings, Numbers, Arrays, functions and Objects.

    var x="prem"
    prem.length

    here x is an object which has value as "prem" and property as length.
    We can also create objects such as
    var prem = Object.create(null);

    Here the prem is an object. But where is the class...????
    There is no class, just objects.
    Here we need to think apart from the traditional OOPS where you need to create classes and instantiate the objects using the classes as in java and c#.

  To add the properties

    There are options to allow the get and set methods in the JS. They can be set by using the following syntax,

// () → String // Returns the full name of object. 
function get_full_name() 
{ return this.first_name + ' ' + this.last_name }  
// (new_name:String) → undefined 
// Sets the name components of the object, from a full name. 
function set_full_name(new_name)
 { 
    var names names = new_name.trim().split(/\s+/) 
    this.first_name = names[⁣'0'] || ''  
    this.last_name = names['1'] || '' 
  } 

Object.defineProperty(prem, 'name', { get: get_full_name , set: set_full_name , configurable: true , enumerable: true })


In the above example there is a property called "name". 

prem.name="prem anandh" // set_full_name is called
now,
prem.first_name is "prem"
and
prem.first_name is "anandh"
and of-course,
prem.name //get_full_name is called

Do Classes even exist in JS...?
        Yes. They do. But slightly different from the rest of the languages in which they are used. The syntax is,
       function name( some_variable )
       {
             this.val=some_variable;
        }
       


   

Thursday 2 August 2012

Javascript - an intro


What :
       Javascript is a programming language which can exist on its own and it can interact with the DOM elements. It goes well with HTML and CSS to give so many good things in the web page. These are all facts about the language. Now we can see about some working in that language.

To declare any variable in this language we can use the "var" keyword.

  • var name="prem"; // String type has double quotes( "" )
  • var age=15;// Numeric type don't have double quotes.
  • var nothing; //undefined type
  • var something=null; // null type

To create and call a function.

var add = function(a,b) // function definition
{
       return a+b;
};

add(10,15);  // invoking the function

The most used output function is,
 document.write("something");
To print the output onto the console we use
 console.log( add(10,15) );
To print the output onto the screen as a pop-up
 confirm( add(10,15) ); // here the return will be a boolean
To output without the use of a return value we can use alert box
  alert( add(10,15) );

To get inputs directly from the user we use the prompt(); function.
It takes two parameter first is the text you need to appear on the screen and the second is the default value in case user doesn't enter anything.
var name=("type your name","prem");

The conditional statements and the looping statements will work in the same way as in C language.
Note : There is a difference between operators "==" and "===".
      E.g;
       5=="5" and 5==5 will return true
       but
        5==="5" returns false while 5===5 returns true. i.e, here both the value and type are checked.

Objects:
      Javascript supports objects. An object have properties and methods.
      For example for a string,
      "prem".length // is a property
      and
      "prem" .toUpperCase() // is a method.
       Method is doing something over the given object while properties are the attributes associated with an object.
        Date  is an object in the JS(shorthand for JavaScript) and the date object can be obtained by,
          var today = new Date ();
           Now, to have the seperate date, hours, minutes and second we can use the code below,
          var date=today.getDate();
          var month=today.getMonth();
          var h=today.getHours();
          var m=today.getMinutes();
          var s=today.getSeconds();


Wednesday 1 August 2012

TDD-Test Driven Development

TDD
       So before beginning this we shall see about the usual manner in which we code. When we are given the problem description we will start to code. End up with a solution. Then give test cases to check if the code works well. But in TDD,
  • We take a requirement and write a test case that matches it.
  • Run the test so that it fails.
  • Modify the existing code so that the test passes.
  • Refactor the code so that the code is more efficient and manageable.
       The diagram below explains the working of the TDD.


























Scenario:
        So lets consider a scenario where you are asked to write a code to play music using a music player.
        music_player()
        {
        }

        Test 1: should play a song.
        The above test will fail as there is no option to play the song.
        The code is changed to,
          music_player()
          {
                 play_audio(); // it will contain the code to play a particular file
           }

           Test 2: Should allow user to select a song.
            The above code will fail for this test. So we will need to add a new piece of code to choose a file.
           music_player()
          {
                int song_id = select(); //to select a song from the list of songs
                 play_audio( song_id );

           }

           Test 3: Should not list non audio/video files.
           The code will fail as there is such an option is not created.
           music_player()
           {
                show_list();  // list only audio/video files.
                int song_id = select();

                play_audio( song_id );

            }


           Test 4: Should not play a deleted song.
           The code will fail as there is no option to check if the given song id is in the list.
           music_player()
           {
                show_list();
                int song_id = select();
                if( check_updates(song_id) ) // This will check if the song is still in the list
                {
                        play_audio( song_id );
                 }
            }

            Test 5: Should play videos for video songs.
            The code fails as there is no special provision for playing videos. Then we have to change the code as,
            music_player()
           {
                show_list();
                int song_id = select();
                if( check_updates(song_id) )
               {
                     int type = get_type(song_id);
                     play( type, song_id ); //generic play function
                }
            }
            play( type , song_id )
            {
                   switch(type)
                   {
                             case AUDIO: play_audio(song_id);
                             case VIDEO: play_video(song_id); 
                   }
            }

            Here we assume that select(), play(), play_audio() and play_video() are already tested units so we need not check their functionality again. We are concentrating only on the music player().
 
Advantages:
            The good thing about this is if a new programmer wants to add some other features such as categorize() the music files. He will write a test case for it and add the feature and run the entire test cases on the music_player().

            So if there is a problem he can know due to which test case there is a failure and overcome the problem. This gives the programmers some assurance over the code.

              NEGATIVE TEST CASES: These test cases are here to handle situations when the test cases are outside what is defined for the system. For the above music_player() scenario providing non audio/video files and selecting id's of deleted files.
  
             POSITIVE TEST CASES: These test cases are to know how system should react to proper inputs. For the above music_player() giving files to play and selecting files are examples of positive test cases.


Monday 30 July 2012

CSS

CSS, an abbreviation of Cascading Style Sheet.

Why ?
       CSS came to existence to solve the problem of overloading the HTML contents with all the formatting options. When all the formatting options came into use there was a problem of mentioning the options in each and every tag. This lead to having a big HTML document which is not a good method for a programmer. Hence people came up with the idea for separating the formatting style options into a separate file. Thus came the CSS.

Like is said in my previous blogs the css can be included,
  1. Inline(within each tags). 
  2. In the style tag of the head section.
  3. From an external CSS file.
 The last one is the preferred way. If multiple styles are set to a particular selector then the style will be inherited with number three having the highest priority and the priority decreases as we move up in the above mentioned list.

CSS styling includes adding attributes to background, text, font, links, list tables.
  • In Background we can specify either a color or a picture. We can specify the position of the image. There is also an interesting property called as attachment. This specifies if the image should scroll with the rest of the page or if it should be fixed on the screen.
  • In Text section we can specify the space between the letters, lines, words. Indentation of the words. Text decoration( underline,blink, etc.,).
  • In  Font section we can format the fonts we want. There are options for specifying the font size, family, weight(degree of boldness).
  • In the Links section there are four categories link-normal unvisited link, visited-any visited link, hover- when the user mouses over the link, active- the moment the link is clicked. We can give properties depending on the links.
  • In Table we can set attributes such as border format(type, color, width, collapse), we can also use the above mentioned options within the table contents as it can contain those elements too.
The Box model:
          The box model consists of four elements. They are given in the above diagram. The Margin and the padding are transparent elements. The former is to specify clarity between the element and adjacent elements while the latter is to have some space between the border and the contents.
         The margin and padding will take the amount of space in all the four directions. The Border will have style and width attribute.

Fluid design :
          Before you start to design any website there is a need to know on which device the web page will be accessed. The normal desktop monitor has a resolution of about 1024 * 768 pixels. But for a smart phone it will not be the same. So if you have specified the dimensions in pixels it wont have the proper in the phone. So the concept of fluid came into picture. Here the dimensions are given as percentage corresponding to the browser. This helps the page to be displayed properly in case it is getting accessed by a hand held device.

Selectors :
       We can select HTML elements from CSS using their id, class or the name of the tags.
         To select a particular element belonging to a particular class we can use
 element_name.class_name. The same cannot be applied over an id as an id will be unique to an element. We can have the same style for more than one selector using ',' operator. E.g,   
        #style_one , #style_two
       {
         color:black;
       }
      If you need to select a particular element like "<p>"which is inside a class "some_class" of element like <div> which in-turn is inside a id "some_id". Then we can select the element using the following way,
        #some_id div.some_class p
        {
             text-align: right;
         }

OOPS CSS:
         OOPS CSS is combining the OOPS concepts into the CSS. CSS doesn't support the OOPS concepts like other languages. But they are still applied in the CSS. How is this possible and why is this necessary..?
       The need to go for such a concept is that you should not duplicate the same css code.
        For example, There are different types of boxes in a HTML file. One can be round, Rectangle. These can further be classified as narrow and wide. So inseted of having classes like,
       .box_round_narrow{...}
       .box_round_wide{...}
       .box_rectangle_narrow{...}
       .box_rectangle_wide{...}
       The above mentioned option can be done but we will unnecessarily using the same "box"  code four times and code for the "rectangle", "round", "narrow", "wide" two times each. This is not a good way right.
      So lets apply some OOPS here. Split each into different classes.
       .box{...}
       .round{...}
       .rectangle{...}
       .narrow{}
       So if we need a box of type "narrow round ". We can include it in the HTML by giving the class in the following manner.
       <tag_name class=" box narrow round"> some code</tag_name>
        I didn't say that the number of classes will be reduced all i am saying is that unnecessary repetition of codes will be reduced.

        We can also apply the OOPS concept when we need to
1) Separate structure and skin :
          Skin is the appearance of the HTML element i.e, color, font attributes, border color, style etc., This can be same for both the table and a paragraph even if they are not within a single parent container. Thus the skin can be a class and it can be reused over different elements.
         I have a doubt about the structures so i will explain about that to you people later.

2)Separate container and content

         Here the container is the base container and the content is the content the container holds. For E.g, in case where  

<div class="some"><img src=url('www.x.html')> </img></div>.

     The CSS can have .some{border-color:black;border-style:bold;}. Instead of the above design we should alter it as

<div><img src=url('www.x.html') class="bordered"> </img></div>

and in the CSS file we can have,.bordered{border-color:black;border-style:bold;}.

  The use of the above is that we can have another image within the <div>  which doesn't require the border and we can also have a bordered image in any part of the HTML file.


SPRITES 

   Sprites are image sprites which can be used to create animations of moving objects by moving the image quickly over the screen. For example the image at http://www.google.co.in/logos/2011/gumby11-gumby.jpg can be used to create an animation. 

        This can be done if you could enlarge the above picture we will see an animated image which changes itself as you scroll through the image. All we need to do now is to create a viewable portion of the image in the screen and change its position by setting the intervals. We can do this using CSS.

Friday 27 July 2012

DOM, Page layouts

The HTML-DOM tree

HTML DOM:
         The HTML DOM interprets the HTML document as a tree structure. The DOM is like an API which interprets a HTML document in the following format. The DOM has a tree structure which has the document as the parent. 
             
                     The DOM helps in retrieving individual elements in the script language using the structure provided above. In the above mentioned tree the attribute, text, elements and comments are placed in the nodes of the tree. HTML DOM allows scripting languages to get the nodes and to process or apply changes over them.

For example (javascript) : we can use Document.getElementbyID('name'); will get an element from the HTML document which contains the give ID.
                 There also exists relationship between the nodes.
                 The above picture gives a clear picture of the relationships between different nodes in the tree. Each node is associated with some properties and methods. Properties are the values of nodes which can be extracted to use or changed. Methods are the methods which can be done over the nodes.

Document.getElementbyID('something').innerHTML; here getting the element is a method and the innerHTML is a property which is being retrieved.

Browser Specific Elements:
         
       Browser is a rendering machine. It gets the HTML page is interpreted it and displays the contents in the programmer desired format.  The rendering of the web page has the following process.






        The Render tree is built by combining the HTML file along with the CSS file which is included by the HTML page. Each browser has its own method of creating the web page by interpreting the DOM. Not all browsers will interpret the web page in the same manner. The difference may arise in the compatibility of the web browser.
       Most of the HTML4 commands will execute properly in all the standard web browsers. But the recently developed HTML5 is not widely supported and the same page will not be rendered properly in all browsers. Hence it is better to go for HTML4 for the time being till HTML5 is well established so that it could be used in all the web browsers.

Thursday 26 July 2012

HTML as i know......


         HTML as you all know is a language that lets us design web pages. It contains tags which help in presenting such good visuals on the screen. There are a lot of browsers being used currently. Though all the browsers display the properties in the same way there are some browser specific attributes too.

          There are three parts in a web page. The HTML part, script part, css part. The HTML part contains all the tags which will appear on the screen. The script part helps in the web page being dynamic. This part will be similar to any other programming languages. The most popular one being javascript. We shall see about this in future.
         The css part helps in assigning the formatting to the tags in the HTML. There are class and id assigned to each element/tags in the HTML document. They both serve the same purpose, helping to assign the formatting to particular elements using css.
       The css and scripts can be either included in the same HTML document or written as separate files and include them into the HTML file.
       Id is is used in elements where the formatting will appear for only that element alone. Class is used when there are many elements which will contain the same formatting. For example : The text box whenever they appear on the screen will need to have the same formatting. So they will be having the same class name.
       The elements in HTML are either block elements or inline elements. <dev> is a block level element which acts as a container to contain other block level and inline elements. The formatting style for the block elements will be inherited in all the elements which it contains.
       <span> is an inline element which is used to span the formatting style in the text which it contains.
          To create the layout of the web page we can either go for <div> or <table>. Though it is now established that <div> is the proper way to do create the layout.
         Some characters are reserved in HTML. It is not possible to use the less than (<) or greater than (>) signs in your text, because the browser will mix them with tags. To actually display reserved characters, we must use character entities in the HTML source code. For example we can use @lt to make '<' to print on the screen.
        There are various events which are there to monitor the web page. Sometimes you may have to sign in in a new website. You will be giving a new password. If your password is small or not proper the website will print the problem once you leave the text box. This can be done by combining events and corresponding client side scripts.
        The webpage http://w3schools.com/html/html_quick.asp will contain quick view of syntax of all the available tags and entities available in the HTML.