opencs's posterous http://opencs.posterous.com Most recent posts at opencs's posterous posterous.com Mon, 20 Jun 2011 02:04:00 -0700 Learning Web Application Development With PHP and MySql http://opencs.posterous.com/learning-web-application-development-with-php http://opencs.posterous.com/learning-web-application-development-with-php

Recently, I enrolled in the Web Application Development with PHP and MySql course at diycomputerscience.com

The course is broken into four parts, where we start with an introduction to PHP, and end by making our own web application with PHP and MySql.

I just completed part 1, which is Introduction to PHP. I decided to pen my thoughts and notes below.

Part 1 of the course consisted of some learning material and 6 activities for practice. I started reading the book PHP and MySql Web Development, but soon realized that my natural style of learning is by doing and not by reading. So I decided to read just some basics from the PHP manual, and start doing the activities.

Activity 1:

The first activity was to create notes for PHP. I created this wiki page to record my PHP notes. I will continue to use this wiki page and add important facts, etc, which will make it a reference for me in the long run. More unorganized notes will be blogged on this blog.

Activity 2:

The second activity was to make a simple HelloWorld program in PHP. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • A PHP script must be enclosed within special characters <?php .. ?>
  • We use the echo command to print something to the console or the browser
  • PHP strings can be single quoted as well as double quoted. Single quoted strings can contain double quotes, and double quoted strings can contain single quotes. Double quoted strings also support string interpolation.
  • We can run PHP scripts on the command line, but we need a utility for it.

 

Activity 3:

The third activity was to create a greeting page using PHP. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • PHP has global variables which are available to the programmer for various tasks. One of the global variables is $_POST, which is an array containing all the post data (if the user made a POST request). PHP also provides us with _GET, and $_REQUEST
  • We use the '.' operator to concatenate Strings in PHP

 

Activity 4:

The fourth activity was to create a temperature conversion service, which will allow the user to enter temperature in either Fahrenheit, or Celcius, and the application would convert it to the other metric and display the result.

Here are two GIT commits I made for this activity. The first one accepts the temperature in Fahrenheit, and displays it in Celcius. The second one allows a user to enter the temperature in either metric, and displays it in the other. 

My main learnings in this activity are:

  • All variables in PHP are pre-pended with a $ sign
  • PHP arrays are actually key => value pairs. If we query the array for a non-existent key, we will get a NULL
  • PHP has support for the following types (Booleans, Integers, Floats, Strings, Arrays, Objects, Resources, and NULL)

 

Activity 5:

For the fifth activity we has to create a simple shopping cart using arrays. Here is the GIT commit

My main learnings for this activity are:

  • A PHP session has to be explicitly started with the session_start() command. I think there is a file setting which will create the session for us implicitly
  • We can include external PHP files using the include 'filename.php' statement. When we include an external file, it gets evaluated. I believe we can also use the require statement. I don't know the difference between the two, Need to find out.
  • session_unset will remove all the values which have been stored in the session
  • Most non boolean values will automatically evaluate to boolean when used in a conditional statement (need to figure out the exact rules)
  • In PHP we can iterate through an array using the foreach statement like this
    • foreach($array as $key => $value) {}
  • PHP supports the tertiary (cond ? something : something_else) operator
  • Comparison is done with the == operator. However PHP also has a === operator. Need to find out what it means.
  • PHP functions are declared thus:
    • function func_name ($param1, $param2) {}
    • We can have default parameters
    • We can have var args
  • Even though a PHP array consists of key value pairs, we can add an element to the array without specifying the key
    • $array[] = "new element";
    • In this case PHP will compute the key as 1 greater than the last numeric key
    • The key must be either Integers, or Strings
    • The gettype($var_name) function returns the type of a variable
    • The var_dump($var_name) function dumps all the details of a variable
    • The is_array($var_name) function will return a true if the specified variable is an array
    • We can find out the number of elements in an array, by using the count() function

 

Activity 6:

For the sixth activity we had to recreate the simple shopping cart using classes and objects. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • PHP 5 onwards supports Object Oriented programming
  • We can create a class thus:
    • class ClassName {}
    • Need to find out if classes can be public, private, etc
    • Classes support public, private, and protected variables as expected. Need to find out, what is the default.
    • The class constructor has to be a function named __construct()
    • An object of a class is created using the new keyword.
    • Objects have access to the $this variable which will refer to the calling object. In most cases it is the object to which the function belongs, but in certain cases, it could also mean the object which calls the function. If the function is called statically, then $this will not be set.
    • Members of an object are accessed like $obj->member_name

 

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Tue, 10 May 2011 05:56:00 -0700 Test Driven Development with JUnit 4.0 - week 2 activity 1 http://opencs.posterous.com/test-driven-development-with-junit-40-week-2 http://opencs.posterous.com/test-driven-development-with-junit-40-week-2

The first activity for this week is to create a test suite which will allow us to run all our unit tests together. JUnit 4.0 has an annotation @RunWith which let's us define a class in which we can declare all the test suites which willbe run when we run that test class.

I ceated a simple example for the two test cases which we have.

package practice;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses(
        {ComplexMoneyTest.class,
         MoneyTest.class}
)
public class AllTests {
   
}

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Thu, 05 May 2011 07:16:00 -0700 Introduction to Javascript for programmers - week 1 activity 2 http://opencs.posterous.com/introduction-to-javascript-for-programmers-we-0 http://opencs.posterous.com/introduction-to-javascript-for-programmers-we-0

Activity 2 for week 1 is to create a simple HTML page which contains a Javascript snippet which would pop up a 'Hello World' alert.

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Thu, 05 May 2011 04:57:00 -0700 Test Driven Development with JUnit 4.0 - week 1 homework 2 http://opencs.posterous.com/test-driven-development-with-junit-40-week-1 http://opencs.posterous.com/test-driven-development-with-junit-40-week-1

This is for activity 2 of the Test Driven Development with Junit 4.0 course.

 

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Thu, 05 May 2011 04:35:00 -0700 Test Driven Development with JUnit 4.0 http://opencs.posterous.com/test-driven-development-with-junit-40 http://opencs.posterous.com/test-driven-development-with-junit-40

I have enrolled in an online Study Group on Test Driven Development with JUnit 4.0 on diycomputerscience.com

The first homework activity is to write a unit test for a Money class. See activity 1 on the course page for week 1.

I recorded my desktop as I did the homework...

 

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Thu, 05 May 2011 02:55:00 -0700 Video : Javascript from the bottom up - My Notes http://opencs.posterous.com/video-javascript-from-the-bottom-up-my-notes http://opencs.posterous.com/video-javascript-from-the-bottom-up-my-notes

The first video to watch for week 1 is this video from Google HTML/CSS/Javascript from the ground up. My notes follow (along with the timeline in the video):

00:00 Introduction

Javascript helps make our webpages interactive. Things like validating forms, drag & drop, hiding and showing elements, changing the color of certain elements and so on.


01:13 Getting Javascript into your webpage
There are various ways by which we can include Javascript in our web pages.

  • Inline - though this is a bad idea
  • Embedded Javascript <SCRIPT> tag
  • Including a reference to a Javascript source file

The following code is an example of inline Javascript (someFunc() is a Javascript function probably defined elsewhere in the HTML file):

<div onmouseover="someFunc()">

We should avoid such inline usage of Javascript because it mixed presentation and logic... which is always a bad idea from a maintenance perspective.

A better way is to embed all your Javascript in <SCRIPT> </SCRIPT> tags, and then have an init function at the end of the page which adds event listeners, which in turn call certain functions when the event listener is invoked. We have not discussed event listeners, so I will not provide an example here.

The third way of including Javascript is to reference an external file which contains all the Javascript functions. In the line below, we include JQuery's external file containing it's Javascript code.

<script type="text/javascript" language="javascript" src="/public/javascripts/jquery-1.4.2.min.js">
</script>

Out of all the above ways, the third is the most preferable way of including Javascript in your web page.


03:10 What can we do with Javascript

Now that we know how to include Javascript in an HTML page, the next question that comes to mind, is what can we do with Javascript?
Many people confuse Javascript for Java, so it is wise to remember that Javascript != Java. Even though Javascript is not Java, it has all the basic features of programming.

04:04 Basic syntax

var foo = 7; //valriables
var baz = 4 + (3 * 2) //operators
var baz = 'a string'; //Strings
var arr = [1,2,3]; //arrays
var f = function(x, y) { //functions
    return x * y;
}
if(baz) {} //conditionals
while(i < 4) {} //while loop
for(var i=0; i<10; i++) {} //for loop

JavaScript is an object oriented programming language... objects can contain properties and functions (called methods). They are good at helping us organize our code.

05:42 How does Javascript interact with web pages

We said earlier that Javascript interacts with web pages. It does so through the DOM (Document Object Model). It (DOM) represents the HTML document as a tree of objects, such that we can manipulate these objects with Javascript code.

HTML elements -> node object (in the DOM)
Attributes of HTML elements -> property of the node object

Here is a blog post which shows the Javascript objects which represent the DOM.

In Javascript, the DOM is represented as a tree of Javascript objects. These objects expose properties to us and we can manipulate those properties to change the look and feel of the web page.         

To manipulate the elements, we first need to obtain a reference to them. We can get a reference either using the id of the element, or it's tag name. Let's use the following HTML as an example:

<div id="about">
   <p id="first"></a><p id="second"></a>
</div>

document.getElementById('about'); //get the node object of an element which has a specific id
document.getElementByTagName('p'); //will return all <p> nodes
//we can even chain these
document.getElementById('about').getElementsByTagName('p');

Javascript by itself gives us just these two methods of selecting a DOM node. However, it would be wonderful if we could access elements by their CSS classname, or in a way that CSS selectors do. Well it seems, we cannot do this directly in Javascript, but we can use 3rd party libraries, like JQuery, or one of many other libraries to do it. Some such libraries are listed at http://getelementsby.com

Once we have a reference to a DOM element, we can access those elements to which our element has a pointer to. A DOM element has pointers to it's parent, children, and siblings:

p.parentNode
p.childNodes //array
p.firstChild
p.lastChild
p.previousSibling
p.nextSibling

Something we should be aware of is that a browser parses the HTML page from top to bottom, and parses (and if possible executes) the Javascript as it encounters it.


10:56 What can we do with DOM elements
       
We can attach listeners to DOM events which are generated on DOM elements, so we can do something special when a user interacts with that element.

Some events:

  • click
  • mouseover
  • mouseout
  • mousedown
  • mouseup
  • blur
  • focus
  • load


Unfortunately, the way in which we attach listeners is different for IE and other browsers.

On IE we should use:
selectedElement.attachEvent('onclick', handlingFunction); //IE

and on all other browsers, we should use:
selectedElement.addEventListener('click', handlingFunction, false); //All other browsers

So how do we know which to use?
Bad Idea: Javascript will allow us to check which browser is being used, and based on that we can decode which function to call.
Good Idea: Use object detection ... check if the object has a certain property

if(selectedElement,attachEvent) {
  selectedElement.attachEvent('onclick', handlingFunction); //IE
} else {
  selectedElement.addEventListener('click', handlingFunction, false); //All other browsers
}
       
13:41 What can we do with the events after attaching listeners

Change the look of your page, change CSS styles, add elements, remore elements... REVIEW
Don't mix presentation and behaviour... manipulate class names of elements... be careful and don't remove existing classes of elements...

16:30 Default events

preventDefault() function allows us to prevent the browser from performing the default behavior.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Thu, 05 May 2011 01:44:00 -0700 Introduction to Javascript for programmers http://opencs.posterous.com/introduction-to-javascript-for-programmers-we http://opencs.posterous.com/introduction-to-javascript-for-programmers-we

I signed up for participation in the Introduction To Javascript (for programmers) course on diycomputerscience.com

In week 1, we are supposed to watch a video which explains the basic capabilities of Javascript in about 17 minutes, and then do 2 learning activities. The first week seems like a relatively low pressure week.

I will be blogging my notes for every video on this blog, and will also publish assignments and activities here.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 02 Mar 2011 02:11:00 -0800 Javascript 101 - Week 5 Assignment 2 http://opencs.posterous.com/javascript-101-week-5-assignment-2 http://opencs.posterous.com/javascript-101-week-5-assignment-2

Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.

 

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 02 Mar 2011 02:04:00 -0800 Javascript 101 - Week 5 Assignment 1 http://opencs.posterous.com/javascript-101-week-5-assignment-1 http://opencs.posterous.com/javascript-101-week-5-assignment-1
Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as <nodename>. The escapeHTML function from chapter 10 is available to properly escape the content of text nodes.

 

 

 

 

Click here to see the solution in full screen

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 02 Mar 2011 01:58:00 -0800 Javascript 101 - Week 5 Questions for reflection http://opencs.posterous.com/javascript-101-week-5-questions-for-reflectio http://opencs.posterous.com/javascript-101-week-5-questions-for-reflectio
1. Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?
Sometimes we have a scenario where there may be several (hundreds or thousands) of child elements. Let's assume these are image elements which have to support drag and drop. Now if we add an event listener to all these elements then the web page may get really huge (because of the onEvent="someJavascript()") code in each element. To prevent such code bloat, we may attach the event handler to the parent element of all these elements. By doing this we get away with just one event handler which will handle the event for all the child elements. However, this will work only of the event get's bubbled or tricked, enabling it to be dealt with by the parent. Normally we prefer bubbling of events, becasue MS does not support the trickling model, so it's better we stick with the bubbling model which is supported by all web browsers.
2. Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this?
We may want to prevent the browser from submitting a form, if the form fields do not have correct data. We often employ Javascript for client side validations of form data. The validation happens on the client side, and the form is submitted only if the form data is successfully validated.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 02 Mar 2011 01:56:00 -0800 Javascript 101 - Week 5 Notes http://opencs.posterous.com/javascript-101-week-5-notes http://opencs.posterous.com/javascript-101-week-5-notes

Changing attributes of dom elements [00:00]

 

if(my_image.complete) {

  my_image.src = srcurl;

}

recommended

if(my_image.getAttribute("complete")) {

  my_image.setAttribute("src", srcurl);

}

 

 

Getting and changing CSS properties [02:40]

node.className = newCssClass

node.style.styleName = newStyle

 

To see the current computed style of an object

node.currentStyle.styleName - only IE

document.defaultView.getComputedStyle(node,"").getPropertyValue(styleName) - not on IE

 

Creating & removing elements [6:00]

document.createElement(tagName)

document.createTextNode(text)

node.cloneNode()

node.cloneNode(true)

 

All these methods create a node but we still have to insert it into the DOM.

 

node.appendChild(new);

node.insertBefore(new, sibling);

node.replaceChild(new, old);

old.parentNode.replaceChild(new, old);

 

To remove elements

node.removeChild(old);

old.parentNode.removeChild(old);

 

Be sure to remove all event handlers which may have been set on a node before deleting the node.

 

innerHTML even though not a standard, is still supported by all modern browsers.

 

Browser event model [12:02]

Lot's of different types of events. For example there are mouse events where the targer is the topmost layer below the cursor.

 

Adding event handlers:

node["on" + type] = f;

IE: node.attachEvent("on"+type, f);

W3C: node.addEventListener(type, f, false); //false indicates the bubbling event model

 

When the event handler function is called, it is passed an optional value, which is the event. However, in IE the event must be obtained from the global event object.

 

function myEventHandler(e) {

  e = e||event;

  var target = e.target || e.srcElement;

  //...

 

Event dispatching: trickling or bubbling

}

 

Why do we want to use either trickling or bubbling. Why not just give the event to the node in question.

 

We have to explicitly stop propogating by (do both or use a platform library)

e.cancelBubble = true;

if(e.stopPropagation) {

  e.stopPropagation();

}

 

After the bubbling the browser will do what it would do next, like giving focus to a form element, or submitting a url, etc. To prevent the browser from doing the that, then we can do the following (do all)

e.returnValue = false;

if(e.preventDefault()) {

  e.preventDefault();

}

return false;

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Sun, 27 Feb 2011 21:01:00 -0800 Javascript 101 - Week 4 Assignments http://opencs.posterous.com/javascript-101-week-4-assignments http://opencs.posterous.com/javascript-101-week-4-assignments

Here are the assignments for week 4 of Javascript 101.

 

1. Download the source for the web page 'http://www.useit.com/about/nographics.html'. In the source page itself, write a Javascript function which counts the number of text nodes in the document and shows the count in an alert dialogue. You can choose how you want to trigger the function (through a button click, link click, or any other event).
2. Change the example above so that instead of displaying the count in an alert dialogue, it is displayed in a span tag in the HTML page itself.
3. Add a link besides the button, such that when the link is click, it changes the style on the span tag to make it's contents bold.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Sat, 26 Feb 2011 08:40:00 -0800 Javascript 101 - Week 4 Questions http://opencs.posterous.com/javascript-101-week-4-questions http://opencs.posterous.com/javascript-101-week-4-questions
1. There were two key innovations to the original (fetch-parse-flow-paint) linear workflow that the Mosaic browser used to render web pages. One allowed for a perception of faster rendering, and the other allowed for us to use AJAX. Explain both?

Early browsers used the fetch-parse-flow-paint workflow. In the fetch cycle the browser fetches a webpage and caches it in the browser's cache. In the parse page, the page is fetched from the cache and is parsed into a data structure which represents the structure and data in the HTML document. In the flow stage the browser determines the flow of the page. The flow is basically the order in the which the elements will be placed, things like element sizes, line breaks, etc. In the paint stage, the browser paints the HTML based on the flow it determined in the previous stage. The problem with this workflow is that it is linear and will not proceed to the next stage before the previous stage completes. A web page often contains references to images, etc. These images are identified in the parse stage. When the browser determines that the web page refers to images, it will fetch the images. The browser will not move to the next stage until all the images are fetched. This causes the user to stare at a blank page till all images are fetched, giving the user a perception that the page is loading slowly.

The first innovation which was made to this cycle was allowing the browser to proceed to the flow and paint stages even before the images are fetched. If the browser determines that the page needs to fetch images, it will create placeholders for the images and proceed to the flow and paint stages. It even starts painting the webpage. Once it starts getting the images, it repaints the page. Even though this may take slightly longer to actually render the webpage, the user gets a perception that something is happening.

The second innovation was to allow scripts to plug into the workflow and change the data structure which represents the webage and cause it to re-render. This allowed for AJAX to dynamically change webpages.

2. What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both?
In an HTML page when a form is submitted, it is submitted as name:value pairs. The name attribute is used in form elements such as input, textarea, to be used as the name in name:value pairs. In one HTML page (but in different forms) there may be multiple elements which have the same name attribute. The 'id' attribute on the other hand uniquely identifies an element on an HTML page. There can only be one element for a given id. The DOM provides a method document.getElementById(id) to fetch an element for a given id.
3. Which pointers does each node in the DOM tree typically have?
Each node in the DOM has the following pointers which refer to nodes near it.
  1. parentNode
  2. firsrtChild
  3. lastChild
  4. nextSibling
  5. previousSibling
  6. childNodes[]
4. Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
A. Every node in the DOM has a nodeName property. For text nodes the value of this property is "#text".

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Sat, 26 Feb 2011 08:36:00 -0800 Javascript 101 - HTML DOM http://opencs.posterous.com/javascript-101-html-dom http://opencs.posterous.com/javascript-101-html-dom

The 'document' object is the root object of the DOM, it has a single child node which is the HTML node. 

Every object has pointers to it's child nodes(childNodes[i], firstChild, lastChild), parent node (parentNode), and siblings (nextSibling, previousSibling).

The nodeName property of the node tells us the type of the node. So the nodeName for the HTML node will be "HTML". The nodeName for a text node is "#text", and for the document node is "#document".

document.documentElement refers to the HTML node

To directly access an object in the DOM by it's id, we can use 

document.getElementById(id);

 

We can also get objects by tag name. This will be useful if for instance we want to get all paragraph objects. This method can also be called on a specific node, to return all elements within that node.

document.getElementsByTagName("p");

 

We can change the value of a text node by setting the new value to it's nodeValue property. 

We can even change the values of node attributes.

node.setAttribute("align", newval);

 

We can even insert elements. First we must create an element and then insert it in the right place.

var x = document.createElement("HR"); document.getElementById('inserthere').appendChild(x);

 

We can even remove nodes. A node has to be removed through it's parent node.

var node = document.getElementById("inserthere"); node.parentNode.removeChild(node);

 

 

 

Document elements often have attributes. One such attribute 'id' is used to uniquely identify an element in a tree of elements. Earlier the 'name' element could also be used for the same purpose, but this is no longer true. The name element's true purpose is to be used in forms to represent values of various form elements. It can also be used to give names to windows, and frames.

node.className is the property which we can use to access the class attribute of a node in the HTML DOM.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 23 Feb 2011 08:08:00 -0800 Javascript 101 - Week 3 Assigments http://opencs.posterous.com/javascript-101-week-3-assigbments-0 http://opencs.posterous.com/javascript-101-week-3-assigbments-0

6.1 Write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it. Use reduce.

Then, write the higher-order function count, which takes an array and a test function as arguments, and returns the amount of elements in the array for which the test function returned true. Re-implement countZeroes using this function.

6.2 Write a function processParagraph that, when given a paragraph string as its argument, checks whether this paragraph is a header. If it is, it strips of the '%' characters and counts their number. Then, it returns an object with two properties, content, which contains the text inside the paragraph, and type, which contains the tag that this paragraph must be wrapped in, "p" for regular paragraphs, "h1" for headers with one '%', and "hX" for headers with X '%' characters.

Remember that strings have a charAt method that can be used to look at a specific character inside them.

6.3 Build a function splitParagraph which, given a paragraph string, returns an array of paragraph fragments. Think of a good way to represent the fragments.

The method indexOf, which searches for a character or sub-string in a string and returns its position, or -1 if not found, will probably be useful in some way here.

This is a tricky algorithm, and there are many not-quite-correct or way-too-long ways to describe it. If you run into problems, just think about it for a minute. Try to write inner functions that perform the smaller actions that make up the algorithm.

6.4 Looking back at the example HTML document if necessary, write an image function which, when given the location of an image file, will create an img HTML element.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Mon, 21 Feb 2011 03:25:00 -0800 Javascript 101 - Week 3 Reflections http://opencs.posterous.com/javascript-101-week-3-reflections http://opencs.posterous.com/javascript-101-week-3-reflections
1. In Javascript, functions are first class objects. What does it mean to be a first class object?
Javascript functions are called first class objects because they can be used anywhere an object can be used. They can be held in variables, and they can be passed to other functions as a parameter. Over and above this Javascript functions are actually objects and can contain name:value properties just like any other object in Javascript. Unrelated to the question, but I would like to state another important fact about Javascript functions, which is that they create a special scope called a lambda or a closure.
2. Functions and variables share the same namespace. What does this mean and what important implication does this have?
In Javascript, functions and variables are all created in the same namespace. What this means is they could collide with one another. I would like to illustrate this concept with a few examples. In the examples below, the webpage contains a button, which when clicked evaluates the value of the variable 'f' and prints the result in a span tag in the webpage.

The image below shows that we only have a variable f which holds the number 3. This is what gets printed when we click the button.

 

Onlyvar

The image below shows that we only have a function f. When we click the button, the body if the function is printed.

Onlyfunc

The image below shows that we have both a function f and a variable f. However, when we click the button, the value of the variable is printed. We will get the same result even if the order of the function and the variable holding the number are reversed. I am not sure if we should depend on the result, because it may also be a browser thing. This code was run on Firefox, and running it on another browser may yield a different result. However, it does point to the fact that we have to be careful and make sure that function names do not collide with variable names.

Varandfunc

3. Douglas Crockford equates Javascript functions with Lambdas, and also mentions that they are a secure construct. Can you do some research and reflect on what he means by 'secure construct'?
Lambdas in Javascript have very well defined scoping rules for what they can access. This is what Douglas Crockford means by secure construct. I also asked this question on StackOverflow, and here is the thread with two answers.
4. Can you explain the concept of a closure.
A closure is an inner function, which is a function defined within another function. This inner function has access to all the variables and input parameters of the outer function, and it continues having this access even after the outer function has returned. The 'greaterThan' function shown below is a closure. The fact that the variables of an outer function continue to exist even after it has exited is very confusing. It may make it slightly easier to remember this concept if we understand that Javascript functions, beyond fulfilling some functionality in the code, are also responsible for creating a scope. This scope may continue to exist after the function has returned, if it has any number of inner functions which have access to that scope.
5. What is the difference between a function and a method?
When a function is encapsulated within an object, we call it a method.
6. In Javascript there is no implicit type checking of arguments passed to functions. This could lead to bugs if programmers are not careful about what they pass to functions. If you create a function, how would you protect it from well meaning but careless programmers?
I first perform a count on the number of arguments by checking arguments.length, then I would do a typeof check on all the arguments to ensure that they are of the correct type.

7. Javascript functions have implicit access to something called this. this points to different things depending on how the function was created. Can you explain why we need 'this', and what it represents in different type of functions.
'this' is an implicit reference which is given to all functions in Javascript by the runtime. 'this' can point to different things based on the context of the function. If the function in question is a method which belongs to an object then 'this' will be a reference to that object. If the function does not belog to any object then 'this' will point to the global object. Inner functions also have a 'this', but unfortunately (because it is incorrect) within inner functions 'this' also points to the global object. When a function is created using the new Function() operator, 'this' points to the function object.
8. Why doesn't Javascript have a cast operator?
The cast operator is usually needed in languages which are statically typed. In such languages we may need the cast operator to convert an object's type to the type of the variable we are assigning it to. However, because Javascript is a dynamically typed language, it does not need a cast operator.
9. What is reflection and why is it easy in Javascript (you may need to do research to answer this question)?
Reflection is the act of getting details (such as properties, methods, etc) of an object at runtime, given a reference to the object. In Javascript reflection is easy because objects are a collection of name:value pairs and we can get all the information we want simply by getting the names and values.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Sun, 20 Feb 2011 08:45:00 -0800 Javascript 101 - Week 2 Assignments http://opencs.posterous.com/javascript-101-week-2-assignments http://opencs.posterous.com/javascript-101-week-2-assignments
Embedding my programming assignments from week 2 of the Javascript 101 course.
Assignment 1:

Assignment 2:

Assignment 3:

Assignment 4:

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Sun, 20 Feb 2011 05:10:00 -0800 Javascript 101 - Week 2 Reflections http://opencs.posterous.com/javascript-101-week-2-reflections http://opencs.posterous.com/javascript-101-week-2-reflections

1. Why do languages provide the switch statement, when we can achieve the same thing with multiple if... elseif statements? Show one example of how you might use the switch statement.

A switch statement is a more readable way to accomplish multiple if...elseif...else statements. An example of usage of switch statements is perhaps code that reads in an answer from a multiple choice quiz.

function answer(choice) {

    switch(choice) {

        case 'a':

            alert('wrong answer');

            break;

        case 'b':

            alert('wrong answer');

            break;

        case 'c':

            alert('right answer');

            break;

        case 'd':

            alert('wrong answer');

            break;

        default:

            alert('This choice was not provided... how did you get it?');

            break;

    }

}

answer('a');

Note that the break statement at the end of every case statement is very important. Without it flow of execution will go into the next case, even though it does not match. In my opinion, this is a disadvantage when we compare the switch with if...elseif...else statements. Javascript could have done away with the default statement, but they chose not to. 

 

 

2. What is encapsulation, and what do functions encapsulate?

In my opinion encapsulation is bundling related things together into one unit. In Javascript a function is a unit of code with related variables which accomplishes something. A weel designed function follows the Single Responsibility Principle. 

 

3. What is a pure function? Is the function show() provided in Eloquent Javascript a pure function?

A pure function is one which always produces the same result whenever it is invoked, and which does not have any side effects. The function 'show()' in Eloquent Javascript isnot a pure function because it does it's work through a side effect.

 

4. What do we mean when we say a variable in a function is shadowing a top level variable?
Javascript has the notion of scope. What this means is that a variable defined in some place is visible within it's scope. A variable which is declared in a function is visible only in that function. Also a variable declared within a function can have the same name as a top level variable outside of the function. When a variable in a function has the same name as a top level variable, we say that it is shadowing the top level variable. The function below shows this with an example. The value shown by the alert popup will be 9.
var i = 5;
function f() {
  //the variable i declared below is shadowing the top level variable i
  var i = 9;
  alert(i);
}

5. A recursive function, must have some sort of an end condition. Why would we get a "out of stack space" error message if a recursive function does not have an end condition?

A recursive function is a function which calls itself. If a function calls itself, then in that invocation, it will again call itself, and so on. This will result in an infinite series of calls to itself. When a function is invoked a frame gets created for it on the stack. If it is invoked infinitely then the runtime will attempt to alloate an infinite number if frames for it on the stack. At some point of time, the runtime will run out of stack space and give us the error "out of stack space".

 

6. Reflect about the difference between object inheritance and class inheritance

In programming languages which use classes, a class is like a blueprint. When an object of that class is created it contains everything which the blueprint contains. Classes define inheritance relationships, such that when an object is created it contains everything which is contained in it's class, as well as superclasses. Even though there are some rules which govern who can see what, essentially everything is contained within the same object. 

However, object inheritance is different. There are no classes or blueprints. An object is simply a collection of name:value pairs. When an object inherits from another object, it is linked with it's parent. When a property of the child object is looked up, and if the child does not contain the property, then it's parent object will be looked up to yield that property. We can establish any level of inheritance. The object at the very top of the inheritance chain is Object.prototype

7. What is object augmentation, and how do we do it?

At runtime we can dynamically add properties to an object. This is known as object augmentation. The example below shows an array object. We can add a method to it at runtime simply by assigning the function as a member of the object.

var someArr = [1, 2, 3];

someArr.sum = function() {

    var theSum = 0;

    for(var i=0; i<this.length; i++) {

        if(this.length instanceof Number) {

            theSum += this.length;

        }

    }

}

alert(someArr.sum());

If we want this method to be in all arrays we create, then we can add it to Array.prototype

Array.prototype.sum = function() {

    var theSum = 0;

    for(var i=0; i<this.length; i++) {

        if(this.length instanceof Number) {

            theSum += this.length;

        }

    }

}

var anotherArray = [4, 't', 5, 6];

alert(anotherArray.sum());

8. There is a way to add a method to String, such as any new String we create will have that augmented method (this is a bit different from object augmentation). How would you do this?

We can add the function to String.prototype. In answer 7, I have added the sum() function to Array.prototype. Similarly, we can add any function to String.prototype, and it will be in every String that is created in the system within that environment.

9. What is garbage collection?

In certain languages such as C and C++, prgrammers have to explicitly allocate and deallocate memory for their objects and data structures. However, many modern languages have what is known as Garbage Collection to relieve the programmer from this tedious and buggy filled task. In such languages the runtime has a garbage collector which figures out which objects are not being referenced anymore (hence not in use) and it automatically reclaims memory from those objects.

10. What is the difference between an array and an object?

An array is a special type of object. It's parent is Array.prototype and it has been enhanced with certain methods and properties which give it the array nature. For example an array always has the length property, and a few methods such as splice(),... etc. The subscripts which we use in an array (under the hoods) are actually converted to Strings and stored as names in the object. The example below shows an array and how it actually looks like in the object.

var animals = ['cat', 'dog', 'horse'];

In the actual array object looks like this

'0':'cat',

'1':'dog',

'2':'horse'

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Wed, 02 Feb 2011 09:53:00 -0800 Javascript Arrays http://opencs.posterous.com/javascript-arrays http://opencs.posterous.com/javascript-arrays

I finished reading the chapter in Arrays form Eloquent javascript. My notes:

  • arrays have methods (concat, join, push, pop, slice, sort, splice)
  • Deleting members from an array is tricky business, because they can leave a hold. Use splice() after deleting members of an array.
  • Array inherits from object, indexes converted into strings, so a regular array is also an associative array
  • Arrays have a length member which is 1 more than the highest integer subscript.
  • Array length does not need to be declared... because it does not matter
  • Do not use 'for in' with arrays... why?
  • Array literals

          var myArr = [100, 200, 5000];
          also myList[1000] = "something";

  • There are several ways of creating an array, [] is the most preferred
  • Arrays get linked to Array.prototype?
  • How do we determine if an object is an array?

          value.constructor == Array
          value instanceof Array
          Neither of these work if the val came from another frame...

  • Do not use an Array as a prototype because the resulting object will not be an array. Instead either augment one particicular array object, or augment Array.prototype

 

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah
Tue, 01 Feb 2011 09:02:00 -0800 Javascript Objects http://opencs.posterous.com/javascript-objects http://opencs.posterous.com/javascript-objects
  • Objects can contain data and methods, and objects can inherit from other objects.
  • JS objects are a collection of name value pairs, where names are strings (or just names), and the value can be any expression, or even an object literal.
  • We can use the dot . notation as well as the [] notation to access members. Reserved words can be accessed only with the [] notation, and they have to be strings.
  • We can also use maker functions which take params and return an object
  • Nested objects are also possible with object literals as well as maker functions.
  • The last property in the object cannot have a trailing comma
  • The video says that an Exception object must have three properties
  • We can add functions or properties to any object... just augment the object with what is desired
  • An object can inherit from any other object. Every object has a link to another object (at the top of the chain is Object.prototype)

         new Object()
         var newObj = object(existingObj);
         var newObj = {} - This is preferred

         Similarly Exceptions can also be created in multiple ways:

        throw new Error(reason);

        throw {

           name: exceptionName,

           message: reason

        };

  • Both objects can contain the same property...
  • In JS new objects are made from similar objects and then customized...(prototypal inheritance)
  • What happens to the new object if the old object is set to undefined?  The link is not broken because the variable is set to undefined and not the object... but the old object can be changed... in which case we cannot access that property... 
  • Just like properties can be augmented, properties can be also deleted

          delete myObj[name]
          delete myObj.name

  • Circular linkages? Will not happen.
  • JS has Garbage collection.
  • No equals() method for logical equality, only ==, or === for references
  • Objects are always passed by reference
  • Objects as well as prototypes can be augmented
  • Object.prototype is the object which is the last in the linkage (similar to Java's Object class)
  • Can we create our own something.prototype? which holds all the blog posts you have
  • In functions, we can simulate named parameters by using a single object literal instead of n parameters to a function.
  • Objects are always passed by reference and never by value.
  • JS does not have the notion of logical equality.

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/5BcaONmfzYk1 Parag Shah adaptives Parag Shah