Wednesday, April 27, 2011

Switching to MacBook Pro

  • How to view all processes?
    Windows: taskmgr
    Mac: cmd+option+esc
             Terminal:  ps -ef
  • How to switch window?
    Windows: alt+tab
    Mac: cmd + tab
             cmd + ~
  • How to switch browser tabs?
    Windows: ctrl + tab
    Mac: ctrl + tab
  • How to show desktop?
    Windows: win + D
                     win + M
    Mac: F11 (fn + F11)
             cmd + F3
             System Preferences -> Expose -> Active Screen Corners
  • How to do advanced text edit?
    Windows: Notepadd++
    Mac: TextWrangler
  • How to capture the screen?
    Windows: Print Screen
                     Alt + Print Screen
    Mac: cmd + shift + 3
             cmd + shift + 4
             cmd + shift + 4 + space (for capture current window, similar to Alt + Print in Windows)
             To capture to clipboard instead of desktop, add control key in above key combination
             Mac also has a utility called grab
  • How to copy to Clipboard?
    Windows: ctrl + c
    Configure Hot Corners

    Mac: cmd + c
  • How to lock the screen?
    Windows: win + L
                     ctrl + alt + delete
    Mac:  Hot Corners
              Keychain Access (show status in menu bar)
              option + cmd + eject (goes to sleep)
  • How to adjust date & time?
    Windows: Double click Date & Time on menu bar
    Mac: System Preference -> Date & Time
  • How to enable right click on TrackPad?
    Windows: Touchpad (built-in button)
    Mac:  Two fingers (default)
              System Preferences -> Trackpad -> Secondary Click (right bottom area)

  • How to enable Chinese language input support?
    Windows: Control Panel -> Regional and Language Options -> Languages (Install files for East Asian Languages)
    Mac: System Preferences -> Language & Text -> Input Sources -> Select input methods to use (Also Show/Hide Trackpad handwriting)

  • How to check OS EFI (Extensible Fireware Interface) version?
    ioreg -l -p IODeviceTree | grep firmware-abi
    you can either continue to hold "6" and "4" everytime you want to boot
    If you want to boot into 32-bit, just hold "3" and "2" at boot

  • How to copy files to FTP server?
    Windows: Explorer, browser, prompt command, or other ftp clients like cuteFTP
    Mac: Finder (Connect to server, cmd+K, but read only), Terminal, or other third party tools like Interarchy, Fetch, Transmit

  • How to show hidden files?
    Windows: Explorer -> Tools -> Folder Options -> View -> Show hidden files and folders
    Mac: Terminal -> defaults write com.apple.finder AppleShowAllFiles -bool true  -> restart Finder  (Also use SetFile utility to toggle hidden/visible file)
  • How to show hidden files?Windows: Task Manager
    Mac: Activity Monitor (or Terminal top command)
     
  • How to write NTFS folder?Windows: It is built-in supportMac: Read by default, but install NTFS-3G can write. Another paid software is Tuxera ntfs which is for read/write NTFS
  • How to find iPhoto original files?Windows: N/A
    Mac: iPhoto -> File -> Reveal in Finder
  •  

Sunday, April 24, 2011

Even Faster Web Sites

I borrowed Steve Souder's book "Even Faster Web Sites" but could not got a chance to complete the reading. However, this book is an addition to "High Performance Web Site", and is providing more info about building faster Web site. Here is some notes of one presentation from Yahoo!

  • Split the initial payload
  • Load scripts without blocking
  • Don't scatter scripts
  • Split dominant content domains
  • Make static content cookie-free
  • Reduce cookie weight
  • Minify CSS
  • Optimize images
  • Use iframes sparingly
  • To www or not to wwww

Load scripts without blocking - one example is msn.com

Advanced Script Loading
XHR Eval (same domain)
XHR Injection (same domain)
Script in Iframe (same domain)
Script DOM Element
Script Defer (IE only)
document.write Script Tag (IE only)

Optimize images:
Tools such as PNGOUT and pngcrush are a good place to start.

Here are some random Web Performance notes:
If you make XMLHttpRequests to services that return XML (or JSON, or plain text), make sure your server gzips this content as well.

However, we found in our study that regardless of usage patterns, the percentage of page views with an empty cache is always ~20%.

you can use the Vary: Accept-Encoding response header to tell the proxy to cache this response only for clients that send the same Accept-Encoding request header.

you can use a different header -- Cache-Control: Private -- which eliminates proxy caching completely. Another way to prevent proxy caching is to use the header Vary: *.

CSS Sprits is not intended for use with content images (those that appear in the HTML in <img /> tags, such as photos in a photo gallery

browsers block all downloads when they encounters a <script> tag. So until a script is downloaded and parsed, no other downloads will be initiated.

If you do decide to minify CSS, apart from the option of minifying manually (simply removing comments and whitespace), you can use some of the available tools, such as CSSTidy, PEAR's HTML_CSS library (http://pear.php.net/package/HTML_CSS/), or SitePoint's own Dust-me Selectors Firefox plugin.

most browsers (Opera is an exception) won't render anything on the page until the all the style sheets are duly downloaded and parsed. Additionally, none of the images referenced from the CSS will be downloaded unless the CSS parsing is complete. So it's better to include the CSS as early on the page as possible.

    * Firebug's Net panel for Firefox, at http://www.getfirebug.com
    * YSlow, Yahoo!'s performance extension to Firebug, at http://developer.yahoo.com/yslow/
    * LiveHTTP Headers for Firefox, at http://livehttpheaders.mozdev.org/
    * Fiddler -- for IE, but also a general-purpose packet sniffer, at http://www.fiddlertool.com/fiddler/
    * HTTPWatch for IE (commercial, free version), at http://www.httpwatch.com/
    * Web Inspector for Safari, at http://webkit.org/blog/?p=41

Three layers of the Web

Inspired by Simply Javascript, it is true that the Web has 3 layers: Content (HTML), Presentation (CSS) and Behavior (Javascript) which are very similar to MVC we often do in web application.
Figure 1: Three Layers of the Web

Web designers realized that the code they write when putting together a web page does three fundamental things:

    * It describes the content of the page. (HTML)
    * It specifies the presentation of that content. (CSS)
    * It controls the behavior of that content. (Javascript)

They also realized that keeping these three types of code separate, as depicted in "Separation of concerns", When building a site, we work through these layers from the bottom up:

   1. We start by producing the content in HTML format. This is the base layer, which any visitor using any kind of browser should be able to view.

   2. With that done, we can focus on making the site look better, by adding a layer of presentation information using CSS. The site will now look good to users able to display CSS styles.

   3. Lastly, we can use JavaScript to introduce an added layer of interactivity and dynamic behavior, which will make the site easier to use in browsers equipped with JavaScript.

The key to accommodating the broadest possible range of visitors to your site is to think of the Web in terms of three layers, which conveniently correspond to the three kinds of code I mentioned earlier. These layers are illustrated in Figure 1, “The three layers of the Web."

Due to the popularity of Web 2.0, there are many books about HTML/CSS/Javascript, and there are also many javascript frameworks to affiliate the development of the Web. In "Simply Javascript", it provides javascript explations and examples using a few Javascript frameworks:

    * Prototype
Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.

    * script.aculo.us
A collection of Web 2.0 style JavaScript libraries that help web developers to easily add visual and ajax effects to projects. Requires Prototype.

    * Yahoo! User Interface Library (YUI)
The YUI Library is a set of utilities and controls, written with JavaScript and CSS, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX.

    * Dojo
Unbeatable JavaScript Tools

    * jQuery
A fast, concise, library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.

    * MooTools
Mootools, a super lightweight web2.0 javascript framework.

Data Access using GemFire (from VMWare)

In the same week (4/18-2/22, Neo4j Graph DB webinar) I attended this online presentation about Spring GemFire. GemFire is a Spring top project and KV store (NOSQL store) with OQL support. Here are some notes from the the presentation.

Data Access Challenges:
#1: Scale Horizontally
  • RDBMS technology is under duress
  • Traditional RDBMS scaling is vertical, not horizontal
  •  Database replication is expensive and difficult
#2: Heterogeneous data access need
  • ACID (atomicity, consistency, isolation, durability) - Bank system
  • BASE (Basically Available, Soft state, Eventual consistency) - Social system
  • Speed is king, Scale is queen
#3: Extreme transaction processing
  • Partition operational data across many servers
  • Client should be partition unaware
  • Distributed transactions are evil
  • Compensating transactions are necessary evil
Spring Data
Spring Frameworks & Tools are on top of WMWare vFabric Platform Services to provide "Application Infrastructure for the Cloud"














Spring GemFire
  • Data Modeling
  • Data Access (OQL v.s. SQL)
  • Data Management

Saturday, April 23, 2011

Graph DB - Neo4j (from VMWare)

Last week I joined a webinar from WMWare about Neo4j (GPLv3 open source community edition) graph database. From wikipedia, A graph database is a kind of NoSQL database that uses graph structures with nodes, edges, and properties to represent and store information. General graph databases that can store any graph. Nodes are very similar in nature to the objects, Properties are pertinent information that relate to nodes, Edges are the lines that connect nodes to nodes or nodes to properties and they represent the relationship between the two.

There are four emerging NOSQL stores
  1. Key/value stores (Amazon Dynamo)
  2. Column Family store (Google Bigtable)
  3. Document database (MangoDB/CouchDB)
  4. Graph Databases (Neo4j)
Here are three screen snapshots from the presentation:
  1. Spring Data Graph (JPA for graph db)
  2. Neo4j API (Node, Property, Relationship)
  3. Neo4j Performance (comparing to MySQL) 
        

Facebook Graph API:
http://developers.facebook.com/docs/reference/api/ (Need login to facebook to see developer API reference). It is still focusing on Node (entity/object), Property (attribute) and Edge (relationship/connection).

Graph API presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph (e.g., people, photos, events, and pages) and the connections between them (e.g., friend relationships, shared content, and photo tags). Every object in the social graph has a unique ID. You can access the properties of an object by requesting https://graph.facebook.com/ID.

Thursday, April 21, 2011

JSON 101

Since I watched this video from Crockford last month, I think it is time for me to get out of XML world and start to use JSON (JavaScript Object Notation). JSON, lightweight data-interchange format, is very easy to learn and use. From its official website http://www.json.org/, we can quickly understand this format. JSON is a subset of the object literal notation of JavaScript, so it can be parsed trivially using the eval() procedure in JavaScript.

JSON has two structures: object and array. 
  • An object structure is represented as a pair of curly bracket surrounding zero or more name/value pairs (or members). 
  • An array structure is represented as square brackets surrounding zero or more values (or elements).

A JSON text is a serialized object or array.

A JSON value MUST be an object, array, number, or string, or one of three literal names (true, false, null). The literal names MUST be lowercase. No other literal names are allowed.

JSON uses 6 reserved characters:
  • [ left square bracket
  • { left curly bracket
  • ] right square bracket
  • } right curly bracket
  • : colon
  • , comma 

They are used for data structures description:
  • curry brackets for object
  • square brackets for array
  • colons for name/value pair (member)
  • commas for separate member or array element

JSON value (string data type) also need escape quotation mark, reverse solidus and other control characters.
  • "    quotation mark  U+0022
  • \    reverse solidus U+005C
  • /    solidus         U+002F
  • b    backspace       U+0008
  • f    form feed       U+000C
  • n    line feed       U+000A
  • r    carriage return U+000D
  • t    tab             U+0009

JSON text encoding SHALL be in Unicode.  The default encoding is UTF-8.

JSON text media type is application/json, which is defined in RFC 4627

JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua. 

JSON v.s. XML

Same:
  • Both are hierarchical. (i.e. You can have values within values.)
  • Both can be parsed and used by lots of programming languages

Difference:
  • JSON uses JavaScript syntax is the biggest advantage. It makes it extremely easy to work with on the client side. XML uses DOM and XSLT which is a bit complex.
  • JSON is that it is lightweight, half size than XML due to its opening and closing tags. However, if you were to represent the XML with attributes rather than elements, the difference would be much less.
  • JSON is not so human readable, so we need formatter; XML is widely supported and many supported tools.
  • JSON is not "XPathable" (JavaScript objects and arrays have no comparable built-in capability), XML has that. There are some JSON related projects like jsonpath.js/JPath.js to enhance this.
  • JSON you can't use reserved words from javascript, XML can use.

JSON Formatter & Validator

http://jsonformatter.curiousconcept.com/
http://www.jsonlint.com/
http://www.jsonlint.com/?reformat=compress

JSON.parse and JSON.stringify
JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
https://github.com/douglascrockford/JSON-js supports this.

JSON is a subset of Javascript
Example 1:
var name = jsonobj.name;
    This is the equivalent of: >>>>
var name = jsonobj["name"];   //Associative Array - an array who's index is a string than a number

Example 2:
var Beatles = ["Paul","John","George","Ringo"];
    This is the equivalent of: >>>>
var Beatles = new Array("Paul","John","George","Ringo");

Example 3:
var Beatles = {
 "Country" : "England",
 "YearFormed" : 1959,
 "Style" : "Rock'n'Roll"
}
    This is the equivalent of: >>>>
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";

Tuesday, April 19, 2011

jQuery ajax success callback not triggered

Recently I started to learn jQuery due to its popularity (jQuery IN ACTION has come to 2nd edition, and many companies/projects are using jQuery). One typical use of jQuery is for ajax call. I wrote a very simple testing code (see below) to check how it works but got a problem - the success callback function is not triggered.

I tried both $.getJSON() and $.ajax() methods but no luck. After further check, I found in the server side returned JSON string, there is a backslash (which is supposed to escape single quote, but it was wrongly composed because http://www.json.org/doesn't say we need escape single quote). Due to that, something like {"name": "hj", "description": "hj\'s blog"} will not trigger success callback. However, it will trigger error and complete callback.

There is an online tool called http://www.jsonlint.com/ where we can validate JSON string. For above mal-format string, we will get below error
syntax error, unexpected TINVALID at line 3
Parsing failed

The fix is easy - remove the extra invalid escape backslash, so the valid JSON string is:
{
    "name": "hj",
    "description": "hj's blog"
}

Here is the code snippet I wrote (googled) for test.

    <script type="text/javascript">
        $(document).ready(function() {
            $("#login_button").click(function() {
                var unameval = $("#username").val();
                var pwordval = $("#password").val();

                var thedata = "email="+unameval+"&pass="+pwordval;
                alert(thedata);

                //do ajax call -> method 1       
                /*
                $.getJSON("http://localhost:8080/api/login", thedata,
                       function(json){
                           alert("yes");
                           alert(json.user.email);                          
                    });
                */
                                                               
                //do ajax call -> method 2
                $.ajax({
                    type: "POST",
                    url: "http://localhost:8080/api/login",
                    data: thedata,
                    //crossDomain:true,
                    dataType:"json",
                    success: function(msg){
                        alert("success event");
                        $("#status").html(msg);
                        alert(msg.user.email);
                    },
                    error: function() { alert("error"); }
                    /*
                    complete: function(msg) {
                        alert("complete event");
                        alert(msg);
                    }
                    */
                });

                return false;
            });
        });
    </script>

PS: firebug trims backslash and displays the well-formed JSON in its JSON tab.

Friday, April 15, 2011

NoClassDefFoundError: org/apache/juli/logging/LogFactory

Today when I installed tomcat 7.0 and tried to start it from Eclipse, I see this familiar NoClassDefFoundError once discussed in one previous blog. The root cause is I somehow don't have the tomcat-juli.jar (which is for logging) in classpath, therefore the fix is:
  1. In Eclipse, open "Servers" tab and select the "Apache Tomcat v7.0 at localhost"
  2. Double click or select "Open" from right-click menu to open configuration 
  3. Select "open launch configuration"
  4. From the "Edit Configuration" dialog, select "Classpath" tab, then click "Add External JARs"
  5. Add TOMCAT_HOME/bin/tomcat-juli.jar to the classpath
  6. Start Tomcat v7.0
For juli details, refer to org.apache.juli package summary
For configuration details, refer to below screen snapshot


    Monday, April 4, 2011

    Javascript operators

    In Javascript, there are some seldom used operators:
    1. ++ Increment
    2. -- Decrement
    3. = = = Exactly equal to (both value and type)
    4. || Logical Or
    Here are some examples:
    1. x = y++  => {x = y; y = y + 1;}
    2. x = ++ y => {y = y + 1; x = y;}
    3. "5" === 5 => returns false, as type is not same.
    4. The Logical OR operator (||) will short-circuit and return the first truthy value.

    There is a common usage for Logical Or operator, which is to setting default values to function arguments, e.g.

    function doSomething(e) {
        e = e || window.event
        alert(e.type);
    }
    =>
    function doSomething(e) {
        if (!e) e = window.event;
        alert(e.type);
    }

    The Logical OR || operator will return its second operand if the first one is falsy
    Falsy values are: 0, null, undefined, an empty string, NaN, and false