Search

12/30/2009

HTML, SVG or Canvas Labels?

HTML, SVG or Canvas Labels?


1. //Add the name of the node in the correponding label
2. //and a click handler to move the graph.
3. //This method is called once, on label creation.
4. onCreateLabel: function(domElement, node){
5. domElement.innerHTML = node.name;
6. domElement.onclick = function(){
7. rgraph.onClick(node.id);
8. };
9. },
10. //Change some label dom properties.
11. //This method is called each time a label is plotted.
12. onPlaceLabel: function(domElement, node){
13. var style = domElement.style;
14. style.display = '';
15. style.cursor = 'pointer';
16.
17. if (node._depth <= 1) {
18. style.fontSize = "0.8em";
19. style.color = "#ccc";
20.
21. } else if(node._depth == 2){
22. style.fontSize = "0.7em";
23. style.color = "#494949";
24.
25. } else {
26. style.display = 'none';
27. }
28.
29. var left = parseInt(style.left);
30. var w = domElement.offsetWidth;
31. style.left = (left - w / 2) + 'px';
32. }

12/29/2009

Javascript accessor properties

Javascript properties | accessors | getter / setter

Getter and setter functions are nice for data hiding, and even nicer when you can use them invisibly like plain data.

//they can be declared on an object literal
var o = {_name : "Start name",
writes : 0,
reads : 0,
name getter : function () {this.reads++; return this._name;},
name setter : function (n) {this.writes++; return this._name = n;}
}

//and can be added to extant objects
o.numwrites getter = function() { return this.writes;}
o.numwrites setter = function() {throw "no";}

//then use them
o.name ="adsfasdfadsF";
var foo = o.name;

innerHTML for Mozilla (WebFX)
Defining Getters and Setters
A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

var o = {
a:7,
get b() { return this.a + 1},
set c(x) {return this.a = x/2}
}
console.log(o.a); //7
console.log(o.b); //8
o.c = 50;
console.log(o.a); //25

Getters and setters can also be added to an object at any time after creation using two special methods called __defineGetter__ and __defineSetter__. Both methods expect the name of the getter or setter as their first parameter, in form of a string. The second parameter is the function to call as the getter or setter. For instance (following the previous example):

o.__defineGetter__("b", function() { return this.a+1; });
o.__defineSetter__("c", function(x) { this.a = x/2; });

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ below) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, put the name of the getter after the get or set and then put the function name after it. The following example shows how to name getter functions in object literals:

var objects = [{get a b(){return 1}},
{a getter:function b(){return 1}},
{"a" getter:function b(){return 1}}];

for (var i=0; i<objects.length; ++i)
print(objects[i].__lookupGetter__("a")) // prints "function b(){return 1}" for every getter.

12/28/2009

ECMAScript Harmony

ECMAScript Harmony

It's no secret that the JavaScript standards body, Ecma's Technical Committee 39, has been split for over a year, with some members favoring ES4, a major fourth edition to ECMA-262, and others advocating ES3.1 based on the existing ECMA-262 Edition 3 (ES3) specification. Now, I'm happy to report, the split is over.

The committee has resolved in favor of these tasks and conclusions:

1. Focus work on ES3.1 with full collaboration of all parties, and target two interoperable implementations by early next year.
2. Collaborate on the next step beyond ES3.1, which will include syntactic extensions but which will be more modest than ES4 in both semantic and syntactic innovation.
3. Some ES4 proposals have been deemed unsound for the Web, and are off the table for good: packages, namespaces and early binding. This conclusion is key to Harmony.
4. Other goals and ideas from ES4 are being rephrased to keep consensus in the committee; these include a notion of classes based on existing ES3 concepts combined with proposed ES3.1 extensions.

Once namespaces and early binding are out, classes can desugar to lambda-coding + Object.freeze and friends from ES3.1. There's no need for new runtime semantics to model what we talked about in Oslo as a harmonized class proposal (I will publish wiki pages shortly to show what was discussed).

We may add runtime helpers if lambda-coding is too obscure for the main audience of the spec, namely implementors who aim to achieve interoperation, but who may not be lambda-coding gurus. But we will try to avoid extending the runtime semantic model of the 3.1 spec, as a discipline to guard against complexity.

John Resig - ECMAScript Harmony
The ECMAScript 4 specification development was very ad-hoc in nature (primarily tackled by Adobe, Mozilla, Opera, and Google): Implementors agreed upon a set of features that they wished to implement and a specification was molded out of the remaining consensus. Building a specification tailored by implementation is a very pragmatic means of reaching a reasonable result.

However there was a fundamental split related to how much of the specification should be implemented. Enter ECMAScript 3.1. This working group (lead by Microsoft and Yahoo) set out to implement some minor changes and bug fixes to ECMAScript 3 while remaining as a subset of full ECMAScript 4 functionality.

This means a couple things: First, you can forget a lot of what you learned about ECMAScript 4, previously. Many of the complicated concepts contained in the language have been tossed. Instead there is a considerable amount of effort going in to making sure that new features will be easily duplicable through other means.

For example, ECMAScript 3.1 provides a new method - called Object.freeze() - which allows you to pass in an object and "freeze" it, preventing it from being modified any further. This is a subset of the functionality that is needed to implement classes in ECMAScript 4 (classes are immutable).

This means that classes will be a part of the new language but they will be defined as simply being syntactic sugar for a series of plain methods or conventions (such as using closures and Object.freeze to create a Class-like experience). Making sure that complex concepts break down into a simplified form will serve users well - giving them a considerable amount of leverage in using the language.

Probably the most important development within all this is the codification of existing de-facto standards. For example, the concept of JavaScript getters and setters (implemented by Mozilla, Apple, and Opera) are going to be quickly fast-tracked into the specification (in the case of getters and setters they already have been). Seeing real-world code quickly make a bee-line for standardization is truly heartwarming.


Major Web Standard Updated: ECMA-262 5th Edition has been approved
This revision of ECMA-262 will be known as ECMAScript, Fifth Edition. It was previously developed under the working name ECMAScript 3.1, which will no longer be used.

The Fifth Edition codifies de facto interpretations of the language specification that have become common among browser implementations and adds support for new features that have emerged since the publication of the Third Edition. Such features include accessor properties, reflective creation and inspection of objects, program control of property attributes, additional array manipulation functions, support for the JSON object encoding format, and a strict mode that provides enhanced error checking and program security.

The last major revision of the ECMAScript standard was the Third Edition, published in 1999. After completion of the Third Edition, significant work was done to develop a Fourth Edition. Although development of a Fourth Edition was not completed, that work influenced ECMAScript, Fifth Edition and is continuing to influence the ongoing development of ECMAScript. Work on future ECMAScript editions continues as part of the previously announced ECMAScript Harmony project.

JS Bin

JS Bin, video introduction - 有點像是可執行的pastbin, 如果html沒有內容的時候,會return js的內容。

JS Bin is a webapp specifically designed to help JavaScript and CSS folk test snippets of code, within some context, and debug the code collaboratively.

JS Bin allows you to edit and test JavaScript and HTML (reloading the URL also maintains the state of your code - new tabs doesn't). Once you're happy you can save, and send the URL to a peer for review or help. They can then make further changes saving anew if required.

The original idea spawned from a conversation with another developer in trying to help him debug an Ajax issue. The original aim was to build it using Google's app engine, but in the end, it was John Resig's Learning app that inspired me to build the whole solution in JavaScript with liberal dashes of jQuery and a tiny bit of LAMP for the saving process.

Video: Brendan Eich — ECMA Harmony and the Future of JavaScript

Video: Brendan Eich — ECMA Harmony and the Future of JavaScript

Video: Douglas Crockford — The State and Future of JavaScript

Javascript面面觀:總結《現狀與展望》 - IT邦幫忙::IT知識分享社群

Javascript面面觀:總結《現狀與展望》 - IT邦幫忙::IT知識分享社群

前一陣子Yahoo舉辦了YUI Conference2009,請來了兩位大師級人物:Brendan Eich做開場演講,Douglas Crockford做閉幕(?我不太確定,應該是閉幕)演講。YUI Theater網站上面有他們演講的錄影及投影片:

Brendan Eich:
* http://developer.yahoo.com/yui/theater/video.php?v=eich-yuiconf2009-harmony (新聞及低畫質影片都先在YUI Blog上發布)
* http://www.yuiblog.com/blog/2009/11/03/video-eich-harmony/ (有高畫質版的影片及演講紀錄,建議看這裡的)

Douglas Crockford:
* http://developer.yahoo.com/yui/theater/video.php?v=crockford-yuiconf2009-state (新聞、低畫質影片及投影片都先在YUI Blog上發布)
* http://www.yuiblog.com/blog/2009/11/04/video-crockford-state/ (有高畫質版的影片及演講紀錄、投影片,建議看這裡的)


從這兩篇演講談起
接下來,就從這兩篇演講談起。

這兩位Javascript的重要人物,都做了一些回顧,裡面有幾個重點:

其一:雖然使用Javascript的人很多,但是直到2005年AJAX技術出現之前,它很缺乏殺手級應用,所以沒什麼人重視,真正理解這個程式語言的人也很少。(我也完全不理解)

其二:制定ECMA-262標準的TC39委員會,積極活動的成員其實很少,到Crockford參加時大概只有Yahoo, Adobe, Mozilla, Microsoft, Opera幾家公司的代表,更大的問題是,這些代表裡面幾乎沒有人真正在使用這個語言。等到TC39開始積極制定ECMA4時,當時的ECMA4與使用者其實有些脫節,更嚴重的問題是,這個標準沒有解決ECMA3的重要問題:「安全性」,只是制定出許多與舊規格不太相容的新功能...

Crockford想要改變這個方向,雖然大家都說不可能,不過他還是找到一個幫手:「微軟」,因為微軟也對用戶相關問題憂心重重。有了幫手之後,TC39委員會內部就決裂,分成ECMA4與ECMA3.1這兩派。後來ECMA主席出來調停,要求統一口徑,最後的結果就是ECMA5,而原本 ECMA4規格的東西就推遲到未來。

我把這個過程講得很簡單,不過當時的過程應該是針鋒相對,所以Brendan Eich形容Crockford是Gandolf,在橋上面對ES4Rog說:"You shall not pass." ...Crockford則形容當時針鋒相對的情況,就好像一部電影:「Twelve Angry Men」,十二個陪審團團員擠在窄小的陪審室中針鋒相對。(看過這個演講才明白,這個標準的幕後黑手其實是Crockford)

現在原本的ECMA3.1變成了ECMA5,而且進入公開review的過程,但是還是有一些危機,這個危機來自IBM...來龍去脈是這樣:如果用過 Javascript做計算,可能就會碰到數字不精確的問題,這個問題來自ECMA3中,規定數字是要符合IEEE754標準。IEEE754用二進未來表示十進位小數的方法,但是因為它是用二進位來表示,結果在一些狀況下數字會出現不精確,例如0.1+0.2...

IBM制定了一個IEEE754標準的延伸,叫做IEEE754r,他參與TC39委員會只為了一件事,就是要把這個標準綁到ECMA-262中。問題是這個標準中使用的演算法,會使數字計算的的速度慢上數十倍甚至百倍(詳情請參考Crockford的演講),所以ECMA5沒有把他納入,結果IBM就威脅,如果不納入,他就投反對票...看起來這個是標準通過的最後威脅了。Crockford也在演講中針對IBM的要求做了一些呼籲。

新規格的重要性
雖然很多人的焦點可能會放在JSON,不過我覺得真正重大的改變在於安全性。

熟悉Javascript的人應該都知道,這個語言有驚人的動態與彈性,透過 "." 與 "=",幾乎就可以修改任何東西。原生的Javascript物件properties可以有ReadOnly、DontEnum、DontDelete 等屬性,但是自訂的物件沒有。這在網站服務混搭成為主流趨勢的現在,就變成了安全的大問題。你寫好的Javascript物件,隨時可能被從第三方網站「混搭」進來的程式不小心甚至惡意改動。為了解決這個問題,Crockford曾經寫過一個東西叫做ADSafe:http://adsafe.org/,嘗試用Javascript做出一個Javascript直譯器,讓第三方的Javascript只能在這個直譯器的沙箱環境中執行。能做出這個方法很厲害,但是好像沒什麼人真正拿來使用。除了效能問題,我想功能上的限制也會讓人裹足不前。

所以最徹底的解決方案,還是從標準規格下手。ECMA5裡面有一個東西叫做Strict Mode,把他打開後所有嚴格(但是可能會讓程式不相容)的安全功能就會啟動。Crockford在演講中也強烈建議使用它,如果在strict mode中無法執行的程式,在未來的標準中就可能完全無法再執行。至於新規格在安全上最重要的東西,我想就是對於物件Properties的權限控制。除了在產生物件時可以控制屬性的讀寫、可擴充等權限,也可以透過freeze, seal等方法把物件加上存取限制,而在properties存取上,也可以透過accessor函數來進行,所以可以有彈性地透過這些函數來對存取加以控制。(有興趣的話,我在前文「Javascript面面觀:核心篇《ECMA-262 Edition 5》(上)」有做過一些介紹,也可以參考文中John Resig部落格文章的連結,或是直接看一下規格草案的pdf檔案)

其他部份主要都是加強這個語言的易用性、功能及表達能力,或是修正舊規格中一些不合理的地方。

(有興趣可以訂閱:https://mail.mozilla.org/listinfo/es-discuss,這是討論ECMAScript規格的主要maillist,內容很豐富,可以看到許多人建議許多各式各樣的功能跟語法,Brendan Eich常常在這裡出沒。)

展望
其實Crockford在演講後面還提到HTML5,他認為這也是個在畫大餅的規格,不如來個HTML4.2,修改目前規格不合理的地方,並且把DOM規格改得好用一點。(如果好用,就不會有jQuery了)

就算新規格通過了,要等到所有廠商都支援還是要花不少時間,要等到IE6消失可能需要花更多的時間...也許到時候,網頁前端的環境可以變得安全一點吧?另外前端工程師的工作也可以不那麼辛苦了吧?不過幕後的問題來源其實已經做了許多改變,除了推動ECMA5的制定,新版的瀏覽器對標準的支援也更好。另外,從一些地方可以看出他的努力:http://blogs.msdn.com/jscript/archive/2009/06/30/steps-toward-creating-compatible-ecmascript-5-implementations.aspx以及http://es5conform.codeplex.com/。(提示:部落格的作者身份?)

說實話,Javascript是個不好使喚的程式語言,因為不好使喚所以才讓人花時間研究阿,這真是個漫長的歷程...

(我寫這篇的素材,主要還是從Crockford的演講來的。Eich的演講提到很多技術細節的歷史淵源及決策過程(究竟他是Javascript的發明人,自始自終都在關心這個語言的發展),Crockford的演講主要集中在幾個攸關標準通過的重點上。兩個人的演講各有擅場,都值得一聽。)

12/24/2009

charting

28 Rich Data Visualization Tools

flot - Attractive Javascript plotting for jQuery
yui-flot

Highcharts: Really nice charting API

Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie and scatter chart types.


Raphaël—JavaScript Library
Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.

Raphaël uses the SVG W3C Recommendation and VML as a base for creating graphics. This means every graphical object you create is also a DOM object, so you can attach JavaScript event handlers or modify them later. Raphaël’s goal is to provide an adapter that will make drawing vector art compatible cross-browser and easy.

Raphaël currently supports Firefox 3.0+, Safari 3.0+, Opera 9.5+ and Internet Explorer 6.0+.

For more examples take a look at charting plugin: gRaphaël

Google Visualization API:
http://code.google.com/apis/ajax/playground/#motion_chart_time_formats


tag: chart

MathJax: Rich Math display from LaTeX and MathML

MathJax: Rich Math display from LaTeX and MathML


The Cauchy-Schwarz Inequality



\[ \left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right) \]

mathjax
google docs的方程式編輯器

他的語法為: \sum_{i=1}^{n}{i^2} =\frac{n(n+1)(2n+1)}{6}
圖檔連結為: http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Csum_%7Bi%3D1%7D%5E%7Bn%7D%7Bi%5E2%7D%20%3D%5Cfrac%7Bn%28n%2B1%29%282n%2B1%29%7D%7B6%7D

DHTML Tabs :: Templates :: DHTML Control XP Style

DHTML Tabs :: Templates :: DHTML Control XP Style



12/23/2009

SVG vs. Canvas on Trivial Drawing Application

SVG vs. Canvas on Trivial Drawing Application, presentation

Conclusions for pixels
* For Canvas, pixels are native
* Emulating pixels with SVG results in a huge DOM
* Winner: Canvas

Conclusions for vectors
* For SVG, vector shapes and mouse interaction are native
* With Canvas, you need to implement everything by yourself (or use a library)
* Winner: SVG

Canvas to SVG
* Canvas provides the .toDataURL() -method for reading its image data - This data can be inserted into SVG image element

function importCanvas(sourceCanvas, targetSVG) {

// get base64 encoded png from Canvas
var image = sourceCanvas.toDataURL();

// Create new SVG Image element.
var svgimg = document.createElementNS(
"http://www.w3.org/2000/svg",
"image");
svgimg.setAttributeNS(
"http://www.w3.org/1999/xlink",
"xlink:href",
image);

// Append image to SVG
targetSVG.appendChild(svgimg);
}

SVG to Canvas
* There is no .toDataURL() -method for SVG
* Solution: Server-side rasterization from serialized SVG
* Server-side conversion with ImageMagick



// Save SVG from POST
$svg_xml = $_POST["svg_xml"];
file_put_contents("input.svg",$svg_xml);

// Run conversion program (ImageMagick)
system("convert input.svg output.png");

// Return the name of rasterization for client
echo "output.png"

?>


function importSVG(sourceSVG, targetCanvas) {

var svg_xml = (new XMLSerializer()).serializeToString(sourceSVG);

$.post("convert.php", { svg_xml: svg_xml },
function(data) {
var ctx = targetCanvas.getContext('2d');
var img = new Image();

img.onload = function() {
ctx.drawImage(img,0,0);
img.src = data;
}
});
}

Conclusion
* For pixel flare and other demo effects, go with Canvas
* But for user interaction and shape stacking, S to the V to the G!

cakejs, demo, CAKE Programming Tutrorials
CAKE is a JavaScript library that allows you to use the HTML5 canvas element as a scenegraph, much like an SVG or other vector image. This article will show you how to get started with this powerful library.

var circle1 = new Circle(100,
{
id: 'myCircle1',
x: CAKECanvas.width / 3,
y: CAKECanvas.height / 2,
stroke: 'cyan',
strokeWidth: 20,
endAngle: Math.PI*2
}
);
circle1.addFrameListener(
function(t, dt)
{
this.scale = Math.sin(t / 1000);
}
);

12/22/2009

Functioning Form - The Apple Store's Checkout Form Redesign

Functioning Form - The Apple Store's Checkout Form Redesign

Labels inside input field
Apple's new checkout labels
A reliable interaction for labels within forms requires the label to disappear quickly when people place their cursor into the input field so they can easily provide their answer. Otherwise, the label might stay and become part of someone’s answer.

Because labels within fields need to go away when people are entering their answer into an input field, the context for the answer is gone. So if you suddenly forget what question you’re answering, tough luck—the label is nowhere to be found. As such, labels within inputs aren’t a good solution for long or even medium-length forms. When you’re done filling in the form, all the labels are gone! That makes it a bit hard to go back and check your answers.

Apple's solution may be able to mitigate this issue because the form is mostly asking for inputs with a known structure. Mailing addresses, for example, have a widely known structure that can be leveraged to help people understand how to answer questions about shipping or billing locations. Other examples include first name and last name, date and time, or the parts of a phone number. These input groups can be utilized within forms to provide additional clues on which questions were answered (once the labels are gone). The always visible section headers help as well.

Lastly, labels within input fields should be presented in a way that makes it obvious at first glance that they are labels and not answers. The Apple form grays out the label text to distinguish labels from answers.

Apple's new checkout Credit Card
Credit card numbers follow a consistent structure. American Express cards start with either 34 or 37. Mastercard numbers begin with 51–55. Visa cards start with 4. And so on. This information can be used to infer what type of credit card someone is using simply by looking at his credit card number.

In their redesigned checkout form, Apple does exactly that. When someone enters a credit card number, the appropriate card type is highlighted directly above. This eliminates the need to ask people what type of credit card they have—one less question to parse, think through, and respond to.

12/21/2009

Canvas Tutorial - The Bricks

Canvas Tutorial - The Bricks


var bricks;
var NROWS;
var NCOLS;
var BRICKWIDTH;
var BRICKHEIGHT;
var PADDING;

function initbricks() {
NROWS = 5;
NCOLS = 5;
BRICKWIDTH = (WIDTH/NCOLS) - 1;
BRICKHEIGHT = 15;
PADDING = 1;

bricks = new Array(NROWS);
for (i=0; i < NROWS; i++) {
bricks[i] = new Array(NCOLS);
for (j=0; j < NCOLS; j++) {
bricks[i][j] = 1;
}
}
}

//have we hit a brick?
rowheight = BRICKHEIGHT + PADDING;
colwidth = BRICKWIDTH + PADDING;
row = Math.floor(y/rowheight);
col = Math.floor(x/colwidth);
//if so, reverse the ball and mark the brick as broken
if (y < NROWS * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
}


if (x + dx + ballr > WIDTH || x + dx - ballr < 0)
dx = -dx;

if (y + dy - ballr < 0)
dy = -dy;
else if (y + dy + ballr > HEIGHT - paddleh) {
if (x > paddlex && x < paddlex + paddlew) {
//move the ball differently based on where it hit the paddle
dx = 8 * ((x-(paddlex+paddlew/2))/paddlew);
dy = -dy;
}
else if (y + dy + ballr > HEIGHT)
clearInterval(intervalId);
}

N Tutorial A - Collision Detection and Response
N Tutorial B - Broad-Phase Collision

12/20/2009

quotes

http://www.neverreadpassively.com/2009_11_01_archive.html


# LISP. Frankly, if you're a programmer you will eventually come to realise LISP is awesome. Although I've started my pilgrimage, I am a long way from mastering, let alone being productive in a dialect. I need to stop dancing around and either build something big and real in the language or to work through a book end-to-end (practical common lisp of course). Both of these strategies have worked for me before in rapidly acquiring new languages. I was thinking of dedicating the Christmas break to one of these tasks, we'll see...

Stackoverflow. I consume a lot of podcasts during my commute and while running. I subscribe to itconversations, and occasionally a stackoverflow podcast will find it's way into my playlist. I just about always skip it. The guys maybe smart dudes, or a the very least write about interesting things on occasion, but they produce a really crap podcast. Anyway, their joint venture - the stackoverflow site - is a pretty kick ass programmer Q/A repository. I have not contributed to it at all, but I have started searching various keywords and tags and I think I could contribute a lot, some of which might even be coherent or useful. What's holding me back is the investment. Each answer would be about the same investment as would be required for a small wikipedia entry (which I've been known to write). My problem is whether or not there is any return on that investment (as I think there is with wikipedia). Is it ego-fulfilling research (like making a slashdot/reddit/hackernews comment) or is it truly a contribution to the a community (however niche)?

12/17/2009

Web Sockets Now Available In Google Chrome

Web Sockets Now Available In Google Chrome


if ("WebSocket" in window) {
var ws = new WebSocket("ws://example.com/service");
ws.onopen = function() {
// Web Socket is connected. You can send data by send() method.
ws.send("message to send"); ....
};
ws.onmessage = function (evt) { var received_msg = evt.data; ... };
ws.onclose = function() { // websocket is closed. };
} else {
// the browser doesn't support WebSocket.
}

* Web Sockets are "TCP for the Web," a next-generation bidirectional communication technology for web applications being standardized in part of Web Applications 1.0.
* The protocol is not raw TCP because it needs to provide the browser's "same-origin" security model.
* Web socket communications using the new web socket protocol should use less bandwidth because, unlike a series of XHRs and hanging GETs, no headers are exchanged once the single connection has been established.
* We also developed pywebsocket, which can be used as an Apache extension module, or can even be run as standalone server.

WebSocket protocol
The Web Socket protocol is an independent TCP-based protocol. Its
only relationship to HTTP is that its handshake is interpreted by
HTTP servers as an Upgrade request.
Based on the expert recommendation of the IANA, the Web Socket
protocol by default uses port 80 for regular Web Socket connections
and port 443 for Web Socket connections tunneled over TLS.

server side implementation:
* python: pywebsocket
* js: Node.JS and the WebSocket protocol
* go: The Google GO team is working on a WebSocket server
* erlang: Comet is dead long live websockets
Handshake =
[
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n",
"Upgrade: WebSocket\r\n",
"Connection: Upgrade\r\n",
"WebSocket-Origin: http://localhost:2246\r\n",
"WebSocket-Location: ",
" ws://localhost:1234/websession\r\n\r\n"
],

12/16/2009

Dom.Point and Region.contains, check if event occus in some div.

http://chunghe.googlecode.com/svn/trunk/experiment/yui.event/event.in.region.htm


Event.on(document.body, 'click', function(e) {
var xy = Event.getXY(e);
var point = new YAHOO.util.Point(xy);
var region = Dom.getRegion('foo');
Dom.get('output').innerHTML = 'click inside? ' + '' + (region.contains(point)? 'true':'false') + '';
});

yui event

http://chunghe.googlecode.com/svn/trunk/experiment/yui.event/yui.event.htm

addListener/remoevListener/getListeners
1. removeListener must specify the event type, ex: Event.removeListener('foo', 'dblclick', hello)
2. getListeners doesn't have to specify the event type, ex: Event.getListeners('foo')

focusin / focusout
1. DOM focus and blur events don't bubble, use YUI focusin & focusout event to solve.
2. By giving it a tabindex you can make any element you like focusable. The focus and blur events should work on such elements.

event delegate (with mouseenter/mouseout)
1. event delegate needs selector.js for the fourth argument

Regular Expression Matching Can Be Simple And Fast

Regular Expression Article #2
Regular Expression Matching Can Be Simple And Fast
Regular Expression Matching: the Virtual Machine Approach

12/11/2009

永和大吃小巷平價超美食

永和大吃小巷平價超美食

推荐Steve Yegge:Rhino on Rails在服务器端JVM中运行JavaScript - Java编程 - JavaEye新闻

推荐Steve Yegge:Rhino on Rails在服务器端JVM中运行JavaScript - Java编程 - JavaEye新闻
Stevey's Blog Rants: Rhinos and Tigers

AppJet: The Platform behind EtherPad

AppJet: The Platform behind EtherPad

JavaScript execution on both the client and server

This enabled us to be more productive by writing all of EtherPad in the same language, and shuttle data between the client, server, and database all using JavaScript objects.

Scalable, cross-browser persistent client sockets
EtherPad changes show up on everyone's browser in real-time, so we needed to maintain a persistent connection to push data to client at all times. We have client and sever libraries that support "Comet" connections in a scalable and browser-compatible way.

Flexible, memory-cached JavaScript object database
All the objects that the EtherPad application code works with are JavaScript objects, so why on earth would we convert them to and from any other format when storing them in the database? EtherPad stores all its data in the AppJet Database, which automatically scales and caches itself in memory as necessary. This makes it fast to implement EtherPad features, fast to change storage models, and fast to serve requests in production.

Access to the world's biggest collection of libraries: the JVM
There are more high-quality and well-documented libraries written for the Java VM than for any other runtime. We wanted access to all of them when building EtherPad, so we made an easy way to import Java libraries for use in JavaScript, based on Rhino's JavaScript/Java bridge.

Obsessive focus on performance
We named it AppJet for a reason. Part of why AppJet is so fast is that it uses Rhino to compile JavaScript to Java bytecodes, which in turn run on top of the JVM. Many man-decades have gone into optimizing the JVM, and all of that work makes AppJet faster. To make the database fast, we automatically cache frequently used segments in memory. The net result is a full-stack platform for building web apps that supports rapid development and rapid performance in production.

Google Wave Operational Transformation

12/09/2009

你的程式語言可以這樣做嗎? - The Joel on Software Translation Project

你的程式語言可以這樣做嗎? - The Joel on Software Translation Project

當你一想到作為參數的無名函數,你也許想到對某個陣列的元素進行相同動作的程式碼。

var a = [1,2,3];

for (i=0; i<a.length; i++) {
a[i] = a[i] * 2;
}

for (i=0; i<a.length; i++) {
alert(a[i]);
}

常常要對陣列內的所有元素做同一件事,因此你可以寫個這樣的函數來幫忙:

function map(fn, a) {
for (i = 0; i < a.length; i++) {
a[i] = fn(a[i]);
}
}

現在你可以將上面的東西寫成:

map( function(x){return x*2;}, a );
map( alert, a );

另一個常見的工作是將陣列內的所有元素按某種方法合起來:

function sum(a)
{
var s = 0;
for (i = 0; i < a.length; i++)
s += a[i];
return s;
}

function join(a)
{
var s = "";
for (i = 0; i < a.length; i++)
s += a[i];
return s;
}

alert(sum([1,2,3]));
alert(join(["a","b","c"]));

'sum'和'join'長得很像,你也許想將它們抽象化,變成將陣列內所有元素按某種方法合起來的泛型函數:

function reduce(fn, a, init)
{
var s = init;
for (i = 0; i < a.length; i++)
s = fn( s, a[i] );
return s;
}

function sum(a)
{
return reduce( function(a, b){ return a + b; },
a, 0 );
}

function join(a)
{
return reduce( function(a, b){ return a + b; },
a, "" );
}

讓我們回到'map'函數。對陣列內的每個元素做事時,很可能並不在乎哪個元素先做。無論由第一個還是最後一個元素開始,結果都是一樣的,對不對?如果你手頭上有2個CPU,就可以寫段程式碼,使得它們各對一半的元素工作,於是'map'就變快兩倍了。

或者你在全球有千千百百台伺服器(只是假設),還有一個很大很大的陣列,存放整個互聯網的內容(同樣也只是假設)。現在你可以在這些伺服器上執行'map',讓各台伺服器只處理問題很小的一部份。

tag: map reduce mapreduce

12/04/2009

Google Visualization API

Google Visualization API
Geo map:
GeoMap
Gauge
Gauge
Annotated Time Line
Annotated Time Line

Using Google Public DNS

Using Google Public DNS

The Google Public DNS IP addresses are as follows:

* 8.8.8.8
* 8.8.4.4

OpenDNS创始人:谷歌DNS与
OpenDNS不完全相同_互联网新闻_科技_腾讯网
我们具有最大的DNS缓冲、最快的解析器,而且提供最大的灵活性让你控制DNS体验。举例来说,IT人士希望在DNS中阻挡恶意网站,父母有时希望阻挡孩子访问特定网站。我们的DNS服务可以实现上面这些和更多任务。谷歌DNS做不到这一点。当然,我们不强推这些功能,一切由用户自己选择。让用户选择是我们服务的核心所在。

12/03/2009

DD_roundies: Code-only rounded HTML boxes

DD_roundies: Code-only rounded HTML boxes
http://chunghe.googlecode.com/svn/trunk/project/DD_roundies/index.htm


Quick summary:

This uses Microsoft's implementation of VML for Internet Explorer. For other browsers, this adds simple border-radius styles to the document (IF and only if you specify the third argument in DD_belatedPNG.addRule).

The third argument in addRule defaults to false. This library does focus primarily on IE.
usage:
# addRule can take up to three arguments:
* (REQUIRED) A text string representing a CSS selector
* (REQUIRED) A text string representing a border radius or radii (anywhere from 1 to 4, separated by commas)
* (OPTIONAL) A boolean indicating whether or not you want to make roundies just in IE (set to false), or attempt to make roundies in "all" browsers (set to true).




Vim Cookbook

Vim Cookbook
Vim Recipes

12/02/2009

Setting Maxlength with javascript

Setting Maxlength with javascript
注意要用input.maxLength而不是input.maxlenth, 只會影響由 createElement('input')長出來的input.

http://chunghe.googlecode.com/svn/trunk/experiment/maxLength.htm

11/30/2009

小薑雜談 / 資訊月 98:Intel CPU 何其多!

小薑雜談 / 資訊月 98:Intel CPU 何其多!

# i7-720QM,透過自家Turbo Boost技術,時脈可以提升到2.8GHz,且該顆CPU為4核心,但全速功耗較高,為45W。(Funnypig比較想等Core i5)
# CPU前面的英文代表功耗,P與SP開頭為25W功耗,T開頭為35W或以上,SU開頭與Atom則可到10W以下(端看單核雙核)。
# P與SP功耗一樣,P系列為3MB L2快取,但SP則提昇為6MB,功耗同為25W。
# T3XXX以下就是Intel Celeron,L2快取1MB,且不支援虛擬化
T4XXX為L2快取1MB的Core 2,且不支援虛擬化
T6XXX為L2快取2MB的Core 2,且不支援虛擬化
T9XXX為L2快取6MB的Core 2,並且支援虛擬化
TDP功耗皆為35W
# SU2XXX開頭的是超低電壓版的Celeron,並且支援64bit與虛擬化
SU3XXX則是單核3MB L2快取超低電壓版Core 2 Solo,並且支援虛擬化
SU4XXX則是雙核2MB L2快取超低電壓版Core 2,並且支援虛擬化
SU7XXX為雙核3MB L2快取超低電壓版Core 2,並且支援64bit與虛擬化 。
SU9XXX為雙核3MB L2快取超低電壓版Core 2,且支援64bit與虛擬化 。
# 就目前的情況來看,Intel的P系列(如P8400)CPU是筆電選購時最超值選擇,等級也比T系列高(以筆電角度來看),當然,預算允許的話,SP系列(如SP9600)會更好。

2. Atom 330 其性能介於 Celeron 723 與 2300 之間,而 Celeron 723 (這款並沒有採用HT技術)性能略強於 Atom 230 (部分網站說明約為1.5倍左右,與 230 性能相近的 N270 處理器進行比較)。

AJAX APIs Playground

AJAX APIs Playground
closure simple:


/*
* When a function is defined in another function and it
* has access to the outer function's context even after
* the outer function returns
* An important concept to learn in Javascript
*/

function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}

outerFunction(1);

closure for events:

/*
* One great use is for event handlers
* If a handler prints a value, it prints the value at trigger time
* If you want to hardcode a value into handler, use closure
*/

var content = document.getElementById('content');

// BAD SETTING HANDLER
for (var i=0; i < 5; i++) {
var button = document.createElement('input');
button.type = 'button';
button.value = 'Closure-less Button number ' + i;
button.onclick = function() {
alert("Closure-less Button number " + i);
};
content.appendChild(button);
}
content.appendChild(document.createElement('br'));


// GOOD SETTING HANDLER
function buttonClick(buttonNumber) {
// buttonNumber is now snapshotted in this function that is returned!
return function() {
alert('Closure Button number ' + buttonNumber);
};
}
for (var i=0; i < 5; i++) {
var button = document.createElement('input');
button.type = 'button';
button.value = 'Closure Button number ' + i;
button.onclick = buttonClick(i);
content.appendChild(button);
}

Javascript Memory Leaks

JScript Memory Leaks

When a DOM object contains a reference to a JavaScript object (such an event handling function), and when that JavaScript object contains a reference to that DOM object, then a cyclic structure is formed. This is not in itself a problem. At such time as there are no other references to the DOM object and the event handler, then the garbage collector (an automatic memory resource manager) will reclaim them both, allowing their space to be reallocated. The JavaScript garbage collector understands about cycles and is not confused by them. Unfortunately, IE's DOM is not managed by JScript. It has its own memory manager that does not understand about cycles and so gets very confused. As a result, when cycles occur, memory reclamation does not occur. The memory that is not reclaimed is said to have leaked. Over time, this can result in memory starvation. In a memory space full of used cells, the browser starves to death.

IBM developerWorks - Memory leak patterns in JavaScript
Internet Explorer and Mozilla Firefox are two browsers that use reference counting to handle memory for DOM objects. In a reference counting system, each object referenced maintains a count of how many objects are referencing it. If the count becomes zero, the object is destroyed and the memory is returned to the heap. Although this solution is generally very efficient, it has a blind spot when it comes to circular (or cyclic) references.

What's wrong with circular references?
A circular reference is formed when two objects reference each other, giving each object a reference count of 1. In a purely garbage collected system, a circular reference is not a problem: If neither of the objects involved is referenced by any other object, then both are garbage collected. In a reference counting system, however, neither of the objects can be destroyed, because the reference count never reaches zero. In a hybrid system, where both garbage collection and reference counting are being used, leaks occur because the system fails to identify a circular reference. In this case, neither the DOM object nor the JavaScript object is destroyed. Listing 1 shows a circular reference between a JavaScript object and a DOM object.

<html>
<body>
<script type="text/javascript">
document.write("Circular references between JavaScript and DOM!");
var obj;
window.onload = function(){
obj=document.getElementById("DivElement");
document.getElementById("DivElement").expandoProperty=obj;
obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
};
</script>
<div id="DivElement">Div Element</div>
</body>
</html>

As you can see in the above listing, the JavaScript object obj has a reference to the DOM object represented by DivElement. The DOM object, in turn, has a reference to the JavaScript object through the expandoProperty. A circular reference exists between the JavaScript object and the DOM object. Because DOM objects are managed through reference counting, neither object will ever be destroyed.

Learning about closures

<html>
<body>
<script type="text/javascript">
document.write("Closure Demo!!");
window.onload=
function closureDemoParentFunction(paramA)
{
var a = paramA;
return function closureDemoInnerFunction (paramB)
{
alert( a +" "+ paramB);
};
};
var x = closureDemoParentFunction("outer x");
x("inner x");
</script>
</body>
</html>

In the above listing closureDemoInnerFunction is the inner function defined within the parent function closureDemoParentFunction. When a call is made to closureDemoParentFunction with a parameter of outer x, the outer function variable a is assigned the value outer x. The function returns with a pointer to the inner function closureDemoInnerFunction, which is contained in the variable x.

It is important to note that the local variable a of the outer function closureDemoParentFunction will exist even after the outer function has returned. This is different from programming languages such as C/C++, where local variables no longer exist once a function has returned. In JavaScript, the moment closureDemoParentFunction is called, a scope object with property a is created. This property contains the value of paramA, also known as "outer x". Similarly, when the closureDemoParentFunction returns, it will return the inner function closureDemoInnerFunction, which is contained in the variable x.

Because the inner function holds a reference to the outer function's variables, the scope object with property a will not be garbage collected. When a call is made on x with a parameter value of inner x -- that is, x("inner x") -- an alert showing "outer x innerx" will pop up.

Closures and circular references
In Listing 5 you see a closure in which a JavaScript object (obj) contains a reference to a DOM object (referenced by the id "element"). The DOM element, in turn, has a reference to the JavaScript obj(innerFunction). The resulting circular reference between the JavaScript object and the DOM object causes a memory leak.

<html>
<body>
<script type="text/javascript">
document.write("Program to illustrate memory leak via closure");
window.onload=function outerFunction(){
var obj = document.getElementById("element");
obj.onclick=function innerFunction(){
alert("Hi! I will leak");
};
obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
// This is used to make the leak significant
};
</script>
<button id="element">Click Me</button>
</body>
</html>

Avoiding memory leaks
Listing 6. Break the circular reference
<html>
<body>
<script type="text/javascript">
document.write("Avoiding memory leak via closure by breaking the circular
reference");
window.onload=function outerFunction(){
var obj = document.getElementById("element");
obj.onclick=function innerFunction()
{
alert("Hi! I have avoided the leak");
// Some logic here
};
obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
obj = null; //This breaks the circular reference
};
</script>
<button id="element">"Click Here"</button>
</body>
</html>

Listing 7. Add another closure
<html>
<body>
<script type="text/javascript">
document.write("Avoiding a memory leak by adding another closure");
window.onload=function outerFunction(){
var anotherObj = function innerFunction()
{
// Some logic here
alert("Hi! I have avoided the leak");
};
(function anotherInnerFunction(){
var obj = document.getElementById("element");
obj.onclick=anotherObj })();
};
</script>
<button id="element">"Click Here"</button>
</body>
</html>

Listing 8. Avoid the closure altogether
<html>
<head>
<script type="text/javascript">
document.write("Avoid leaks by avoiding closures!");
window.onload=function()
{
var obj = document.getElementById("element");
obj.onclick = doesNotLeak;
}
function doesNotLeak()
{
//Your Logic here
alert("Hi! I have avoided the leak");
}

</script>
</head>
<body>
<button id="element">"Click Here"</button>
</body>
</html>


Mozilla developer center - A re-introduction to JavaScript ( Simon Willison )
Browser hosts need to manage a large number of objects representing the HTML page being presented - the objects of the DOM. It is up to the browser to manage the allocation and recovery of these.

Internet Explorer uses its own garbage collection scheme for this, separate from the mechanism used by JavaScript. It is the interaction between the two that can cause memory leaks.

A memory leak in IE occurs any time a circular reference is formed between a JavaScript object and a native object. Consider the following:

function leakMemory() {
var el = document.getElementById('el');
var o = { 'el': el };
el.o = o;
}
The circular reference formed above creates a memory leak; IE will not free the memory used by el and o until the browser is completely restarted.
Closures make it easy to create a memory leak without meaning to. Consider this:

function addHandler() {
var el = document.getElementById('el');
el.onclick = function() {
this.style.backgroundColor = 'red';
}
}

The above code sets up the element to turn red when it is clicked. It also creates a memory leak. Why? Because the reference to el is inadvertently caught in the closure created for the anonymous inner function. This creates a circular reference between a JavaScript object (the function) and a native object (el).

There are a number of workarounds for this problem. The simplest is this:

function addHandler() {
var el = document.getElementById('el');
el.onclick = function() {
this.style.backgroundColor = 'red';
}
delete el;
}

Surprisingly, one trick for breaking circular references introduced by a closure is to add another closure:

function addHandler() {
var clickHandler = function() {
this.style.backgroundColor = 'red';
}
(function() {
var el = document.getElementById('el');
el.onclick = clickHandler;
})();
}

The inner function is executed straight away, and hides its contents from the closure created with clickHandler.

Fixing Leaks - Drip IE Leak Detector

function loadMyPage() {
var elem = document.getElementById('myelement');
elem.onclick = function () {
window.alert('hi!');
};
}

To solve this, you could add:
elem = null;

Or, you could refactor the code somewhat:

function onMyElemClick() {
window.alert('hi!');
}
function loadMyPage() {
var elem = document.getElementById('myelement');
elem.onclick = onMyElemClick;
}

Understanding and Solving Internet Explorer Leak Patterns
Leak Patterns
1. Circular References—When mutual references are counted between Internet Explorer's COM infrastructure and any scripting engine, objects can leak memory. This is the broadest pattern.
2. Closures—Closures are a specific form of circular reference that pose the largest pattern to existing Web application architectures. Closures are easy to spot because they rely on a specific language keyword and can be searched for generically.
3. Cross-Page Leaks—Cross-page leaks are often very small leaks of internal book-keeping objects as you move from site to site. We'll examine the DOM Insertion Order issue, along with a workaround that shows how small changes to your code can prevent the creation of these book-keeping objects.
4. Pseudo-Leaks—These aren't really leaks, but can be extremely annoying if you don't understand where your memory is going. We'll examine the script element rewriting and how it appears to leak quite a bit of memory, when it is really performing as required.

Circular References
Circular references are the root of nearly every leak. Normally, script engines handle circular references through their garbage collectors, but certain unknowns can prevent their heuristics from working properly. The unknown in the case of IE would be the status of any DOM elements that a portion of script has access to. The basic principle would be as follows:
Figure 1 Basic Circular Reference Pattern

CodeProject: Memory Leakage in Internet Explorer - revisited. Free source code and programming help
Fabulous Adventures In Coding : How Do The Script Garbage Collectors Work?
Interestingly enough though, JScript and VBScript have completely different garbage collectors. Occasionally people ask me how the garbage collectors work and what the differences are.

JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:

* Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.
* Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)
* Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)
* At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.
Actually it is a little more complex than that, as we must worry about details like "what if freeing an item causes a message loop to run, which handles an event, which calls back into the script, which runs code, which triggers another garbage collection?" But those are just implementation details. (Incidentally, every JScript engine running on the same thread shares a GC, which complicates the story even further...)

You'll note that I hand-waved a bit there when I said "every now and then..." Actually what we do is keep track of the number of strings, objects and array slots allocated. We check the current tallies at the beginning of each statement, and when the numbers exceed certain thresholds we trigger a collection.

The benefits of this approach are numerous, but the principle benefit is that circular references are not leaked unless the circular reference involves an object not owned by JScript.

However, there are some down sides as well. Performance is potentially not good on large-working-set applications -- if you have an app where there are lots of long-term things in memory and lots of short-term objects being created and destroyed then the GC will run often and will have to walk the same network of long-term objects over and over again. That's not fast.

The opposite problem is that perhaps a GC will not run when you want one to. If you say "blah = null" then the memory owned by blah will not be released until the GC releases it. If blah is the sole remaining reference to a huge array or network of objects, you might want it to go away as soon as possible. Now, you can force the JScript garbage collector to run with the CollectGarbage() method, but I don't recommend it. The whole point of JScript having a GC is that you don't need to worry about object lifetime. If you do worry about it then you're probably using the wrong tool for the job!

Raphaël—JavaScript Library

Raphaël—JavaScript Library

Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.

Raphaël uses the SVG W3C Recommendation and VML as a base for creating graphics. This means every graphical object you create is also a DOM object, so you can attach JavaScript event handlers or modify them later. Raphaël’s goal is to provide an adapter that will make drawing vector art compatible cross-browser and easy.

Raphaël currently supports Firefox 3.0+, Safari 3.0+, Opera 9.5+ and Internet Explorer 6.0+.

For more examples take a look at charting plugin: gRaphaël

Google Visualization API:
http://code.google.com/apis/ajax/playground/#motion_chart_time_formats

tag: svg, vml, Raphael

node.js

http://nodejs.org/

evented I/O for V8 javascript”. It’s a toolkit for writing extremely high performance non-blocking event driven network servers in JavaScript. Think similar to Twisted or EventMachine but for JavaScript instead of Python or Ruby.

http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf
node.js in brief:
Server-side Javascript
Built on Google’s V8
Evented, non-blocking I/O. Similar to EventMachine or Twisted.
CommonJS module system.
8000 lines of C/C++, 2000 lines of Javascript, 14 contributors.

Many web applications have code like this:

var result = db.query("select * from T");
// use result
What is the software doing while it queries the database?
In many cases, just waiting for the response.

I/O latency
L1: 3 cycles
L2: 14 cycles
RAM: 250 cycles
DISK: 41,000,000 cycles
NETWORK: 240,000,000 cycles

Better software can multitask.
Other threads of execution can run while waiting.
Nginx and Apache memory usage

Apache uses one thread per connection.
NGINX doesn't use threads. It uses an event loop.
Context switching is not free
Execution stacks take up memory
For massive concurrency, cannot use an OS thread for each connection.
Green threads or coroutines can improve the situation dramatically
BUT there is still machinery involved to create the illusion of holding execution on I/O.


Node.js is genuinely exciting

other http servers.
nginx
Tornado Web Server
Yaws, Apache vs. Yaws

11/26/2009

graphviz

Graphviz - Graph Visualization Software, documentation
canviz: graphviz on a canvas
Graphviz FAQ
http://graphviz.org/Documentation/dotguide.pdf

dot draws a graph in four main phases. The layout procedure used by dot relies on the graph being acyclic.
(1) Thus, the first step is to break any cycles which occur in the input graph by reversing the internal direction of certain cyclic edges.
(2) The next step assigns nodes to discrete ranks or levels. In a top-to-bottom drawing, ranks determine Y coordinates. Edges that span more than one rank are broken into chains of “virtual” nodes and unit-length edges.
(3) The third step orders nodes within ranks to avoid crossings.
(4) The fourth step sets X coordinates of nodes to keep edges short, and the final step routes edge splines.

* The dot language descries three kinds of objects: graphs, nodes, and edges. With in a main graph, a subgraph defines a subset of nodes and edges.
* It is often useful to adjust the representation or placement of nodes and edges in the layout. This is done by setting attributes of nodes, edgets or subgraphs in the input file. Attributes are name-value pairs of character strings.


2. Drawing Attributes
* Nodes are drawn, by default, width shape=ellipse, width=.75, height=.5 and labeled by the node name. Other common shapes include box, circle, recode and plaintext.
* The node shape plaintext draws a node without any outline, an important convention in some kinds of diagrams.
* In case where the graph structure is of main concern, and especially when the graph is moderately large, the point shape reduces nodes to display minimal content. When drawn, a node's actual size is the greater of the requested size and the area needed for its text label, unless fixedsize=true, in which case the width and height values are enforced.
* The shape polygon exposes all the polygonal parameters, and is useful for creating many shapes that are not predefined. In addition to the parameters regular, peripheries and orientation, polygons are parameterized by number of sides sides, skew and distortioin.
* Graphs and cluster subgraphs may also have labels. graph labels appear, by default, centered below the graph. Setting labelloc=t centers the label above the graph. Cluster labels appear within the enclosing rectangle, in the upper left corner. The value labelloc=b moves the label to the bottom of the rectangle. The setting labeljust=rmoves the label to the right.
* Sometimes avoiding collisions among edge labels and edges forces the drawing to be bigger than desired. If labelfloat=true, dot does not try to prevent such overlaps, allowing a more compact drawing.
* An edge can also specify additional labels, using headlabel and taillabel, which are be placed near the ends of the edge. The characteristic of these labels are specified using the attributes labelfontname, labelfontsize and labelfontcolor.
2.5 Node and Edge Placement
* The rank of a subgraph may be set to same, min, source, max or sink.
* A value same causes all the nodes in the subgraph to occur on teh same rank. If set to min, all the nodes in the subgraph are guaranteed to be on a rank at least as small as any other node in the layout.
* This can be made strict by setting rank=source, which forces the nodes in the subgraph to be on some rank strctly smaller than the rank of any other nodes (except those also specified by min or source subgraphs).

diagraph G {
size = "4, 4";
main [shape=box]; /* This is a comment*/
main -> parse [weight=8]
parse -> execute;
main -> init [style=dotted];
main -> clean up;
execute -> {make_string; printf} /* makes edges from execute to make_string and printf*/
init -> make_string;
edge [color=red];
main -> printf [style="bod, label="100 times"]
make_string [label="make a\nstring"];
node [shape=box, style=filed, color=".7 .3 1.0"];
execute -> compare;
}


graphviz

3.2 Clusters
* A cluster is a subgraph placed in its own distinct rectangle of the layout. A subgraph is recognized as a cluseter when its name has the prefix cluster.
* Labels, font characteristics and the labelloc attribute can be set as they would be for the top-level graph, though cluster labels appear above the graph by defaut.
* Clusters are drawn by a recursive technique that computes a rank assignment and internal ordering of nodes within clusters.
* If the top-level graph has the compound attribute set to true, dot will allow edges connecting nodes and clusters. This is accomplished by an edge defining an lhead or ltail attribute. The value of these attributes must be the name of a cluster containing the head or tail node, respectively.
How can I create edges between cluster boxes?
This only works in Graphviz version 1.7 and higher. To make edges between clusters, first set the graph attribute compound=true. Then, you can specify a cluster by name as a logical head or tail to an edge. This will cause the edge joining the two nodes to be clipped to the exterior of the box around the given cluster.
digraph G {
compound=true;
nodesep=1.0;
subgraph cluster_A {
a -> b;
a -> c;
}
subgraph cluster_B {
d -> e;
f -> e;
}
a -> e [ ltail=cluster_A,
lhead=cluster_B ];
}

output


node attributes
graph attributes
edge attributes
ref:
lf387, Graphics: Automate the creation of graphs with Graphviz

The CouchDB Project

The CouchDB Project

Apache CouchDB is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution.

CouchDB provides a RESTful JSON API than can be accessed from any environment that allows HTTP requests. There are myriad third-party client libraries that make this even easier from your programming language of choice. CouchDB’s built in Web administration console speaks directly to the database using HTTP requests issued from your browser.

CouchDB is written in Erlang, a robust functional programming language ideal for building concurrent distributed systems. Erlang allows for a flexible design that is easily scalable and readily extensible.

See the introduction and the technical overview for more information.

CouchDB了解(-) 特性及实现
CouchDB内部默认使用JavaScript作为View的编写语言,之所以采用Javascript,是和CouchDB一种半结构化面向文档的分布式,高容错的数据库系统,其提供RESTFul HTTP/JSON接口。其拥有MVCC特性,用户可以通过自定义Map/Reduce函数生成对应的View。

在CouchDB中,数据是以JSON字符的方式存储在文件中。

CouchDB面向Web开发相关的。CouchDB使用Mozilla的spidermonkey作为JavaScript的解析运行平台,为了和Erlang进行交互,其使用c书写了一个Port程序couchjs,/server/main.js作为View Server服务器。

CouchDB: The Definitive Guide
  • get a list of databases: curl -X GET http://127.0.0.1:5984/_all_dbs

  • create a database: curl -X PUT http://127.0.0.1:5984/baseball

  • delete a database: curl -X DELETE http://127.0.0.1:5984/plankton

  • tag: couch

    Recreating the button

    Recreating the button
    http://simonwillison.net/2009/Feb/5/recreating/
    Fascinating article from Doug Bowman on the work that went in to creating custom CSS buttons for use across Google’s different applications, avoiding images to improve performance ensure they could be easily styled using just CSS. I’d love to see the Google Code team turn this in to a full open source release—the more sites using these buttons the more familiar they will become to users at large.

    Automating PowerPoint with Python

    Automating PowerPoint with Python


    import win32com.client, sys
    Application = win32com.client.Dispatch("PowerPoint.Application")
    Application.Visible = True
    Presentation = Application.Presentations.Open(sys.argv[1])
    for Slide in Presentation.Slides:
    for Shape in Slide.Shapes:
    Shape.TextFrame.TextRange.Font.Name = "Arial"
    Presentation.Save()
    Application.Quit()


    import urllib2, csv
    url = 'http://spreadsheets.google.com/pub?key=phNtm3LmDZEOoyu8eDzdSXw&output=csv&range=B2:C51'
    # Open the URL using a CSV reader
    reader = csv.reader(urllib2.urlopen(url))
    # Convert the CSV into a list of (asset-size, bank-name) tuples
    data = list((int(s.replace(',','')), b.decode('utf8')) for b, s in reader)

    I created a simple Treemap class based on the squarified algorithm — you can play with the source code. This Treemap class can be fed the the data in the format we have, and a draw function. The draw function takes (x, y, width, height, data_item) as parameters, where data_item is a row in the data list that we pass to it.

    archive

    Fixing IE by porting Canvas to Flash
    Fixing IE by porting Canvas to Flash. Implementing canvas using Flash is an obvious step, but personally I’m much more interested in an SVG renderer using Flash that finally brings non-animated SVGs to IE.

    Practical, maintainable CSS
    Practical, maintainable CSS (via) Nat’s posted slides and a video from her latest talk at last week’s Brighton Girl Geeks evening.

    Google App Engine - Uploading and Downloading Data
    We've been working on a set of tools that will make the process of uploading and downloading data from App Engine applications easier. Today we're excited to announce an early release of our new bulk uploading client. You can try it out here. Let us know what you think in our Google Group!

    Yahoo! Query Language thoughts
    Yahoo! Query Language thoughts. An engineer on Google’s App Engine provides an expert review of Yahoo!’s YQL. I found this more useful than the official documentation.

    YQL opens up 3rd-party web service table definitions to developers
    YQL opens up 3rd-party web service table definitions to developers. This really is astonishingly clever: you can create an XML file telling Yahoo!’s YQL service how to map an arbitrary API to YQL tables, then make SQL-style queries against it (including joins against other APIs). Another neat trick: doing a SQL “in” query causes API requests to be run in parallel and recombined before being returned to you.

    rev=canonical bookmarklet and designing shorter URLs

    A rev="canonical" HTTP Header
    I like rev="canonical"

    favicon generator

    favikon.com. Small, easy to use online favicon generator.
    favicon.ico Generator
    favicon.cc is a tool to create or download favicon.ico icons, that get displayed in the address bar of every browser.

    11/25/2009

    How to submit blogger sitemap successfully and fix the maximum limit issue?

    How to submit blogger sitemap successfully and fix the maximum limit issue?

    Webmaster Tools > Sitemaps > Add Sitemap.

    Food for the thinking mind: If you don’t include redirect=false, webmaster tools will throw warning. If you don’t include start-index=1&max-results=100, the maximum number of URLs submitted will be shown as 26, always. Remember if you have more than 100 pages on your blogspot site, you would need to include two sitemaps one having an index starting with 1 and ending with 100(start-index=1&max-results=100) and the other having an index starting with 100 and ending with 200(start-index=100&max-results=100)

    jsbeautify : a javascript source code formatter

    jsbeautify : a javascript source code formatter
    http://www.jsbeautifier.org/

    DamnIT (beta) A JavaScript error reporting service

    DamnIT (beta) A JavaScript error reporting service
    https://damnit.jupiterit.com/home/learn

    11/24/2009

    F5 vs. ctrl+F5 IE Doesn’t Refresh Ajax Based Content Before Its Expiration Date

    Ajax Caching: Two Important Facts

    As you develop a page like this, it is tempting to refresh the page in an attempt to update the embedded Ajax content. With other embedded resources such as CSS or images, the browser automatically sends the following types of requests depending on whether F5 (Refresh) or Ctrl+F5 (Forced Refresh) is used:

    1. F5(Refresh) causes the browser to build a conditional update request if the content originally had a Last-Modified response header. It uses the If-Modified-Since request header so that server can avoid unnecessary downloads where possible by returning the HTTP 304 response code.
    2. Ctrl+F5 (Forced Refresh) causes the browser to send an unconditional GET request with a Cache-Control request header set to ‘no-cache’. This indicates to all intermediate proxies and caches that the browser needs the latest version of the resource regardless of what has already been cached.

    In Internet Explorer, the load-time Ajax request is treated as though it is unrelated to the rest of the page refresh and there is no propagation of the user’s Refresh action. No GET request is sent to the server if the cached Ajax content has not yet expired. It simply reads the content directly from the cache, resulting in the (Cache) result value in HttpWatch. Here’s the effect of F5 in IE before the content has expired:

    IE Refresh of Ajax Request

    Even with Ctrl+F5, the Ajax derived content is still read from the cache:
    IE Forced Refresh

    Let's make the web faster - Google Code

    Let's make the web faster - Google Code
    Capturing and analyzing browser paint events using Page Speed Activity

    Using Ctrl+F5 in IE 7 - HttpWatch Blog

    Using Ctrl+F5 in IE 7 - HttpWatch Blog

    Only the HTML of the page is returned with a 200 OK response; the other items return a 304 Not Modified response. Looking more closely with HttpWatch you can see that If-Modified headers were sent with every request. This is what you would expect from typing F5 or clicking the Refresh button.

    It turns out that Ctrl+F5 only works in IE 7 if the keyboard focus is on the web page itself. If you move the focus anywhere else, such as back to the location bar, it ignores the Ctrl key and behaves as if F5 were typed on its own.

    So if you really want to do a forced refresh in IE7 make sure you click on the web page or tab first.
    .
    I found this behavior in IE7 & IE8 too. I thought that IE 7/8 have changed “Ctrl + F5″ behaviors. Thanks for pointing out it is due to focus.

    11/23/2009

    Primitive Datatype Wrapper Objects

    from javascript the definitive guide, 3.13 Primitive Datatype Wrapper Objects

     
    >>> s = 'hello'
    "hello"
    >>> typeof s
    "string"
    >>> t = new String('hello')
    hello 0=h 1=e 2=l 3=l 4=o
    >>> typeof t
    "object"

    When we discussed strings earlier in this chapter, I pointed out a strange feature of that datatype: to operate on strings, you use object notation. For example, a typical operation involving strings might look like the following:

    var s = "These are the times that try people's souls.";
    var last_word = s.substring(s.lastIndexOf(" ")+1, s.length);

    If you didn't know better, it would appear that s was an object and that you were invoking methods and reading property values of that object.

    What's going on? Are strings objects, or are they primitive datatypes? The typeof operator (see Chapter 5) assures us that strings have the datatype "string", which is distinct from the datatype "object". Why, then, are strings manipulated using object notation?

    The truth is that a corresponding object class is defined for each of the three key primitive datatypes. That is, besides supporting the number, string, and boolean datatypes, JavaScript also supports Number, String, and Boolean classes. These classes are wrappers around the primitive datatypes. A wrapper contains the same primitive data value, but it also defines properties and methods that can be used to manipulate that data.

    JavaScript can flexibly convert values from one type to another. When you use a string in an object context i.e., when you try to access a property or method of the string JavaScript internally creates a String wrapper object for the string value. This String object is used in place of the primitive string value. The object has properties and methods defined, so the use of the primitive value in an object context succeeds. The same is true, of course, for the other primitive types and their corresponding wrapper objects; you just don't use the other types in an object context nearly as often as you use strings in that context.

    Note that the String object created when you use a string in an object context is a transient one; it allows you to access a property or method, and then it is no longer needed, so it is reclaimed by the system. Suppose s is a string and the length of the string is determined with a line like this:

    var len = s.length;

    In this case, s remains a string; the original string value itself is not changed. A new transient String object is created, which allows you to access the length property, and then the transient object is discarded, with no change to the original value s. If you think this scheme sounds elegant and bizarrely complex at the same time, you are right. Typically, however, JavaScript implementations perform this internal conversion very efficiently, and it is not something you should worry about.


    Primitives as objects
    It's possible to instantiate these wrapper objects; this is a bad idea, as it doesn't give you any benefit:

    var s = new String('abc');
    var n = new Number(5);
    var b = new Boolean(true);

    Avoid doing this.

    Programming languages datatype

    Programming languages datatype


    statically typed language
    A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
    dynamically typed language
    A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
    strongly typed language
    A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
    weakly typed language
    A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.

    So Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters).

    Weak typing - Wikipedia, the free encyclopedia
    In computer science, weak typing (a.k.a. loose typing) is a property attributed to the type systems of some programming languages. It is the opposite of strong typing, and consequently the term weak typing has as many different meanings as strong typing does (see strong typing for a list and detailed discussion).

    One of the more common definitions states that weakly typed programming languages are those that support either implicit type conversion (nearly all languages support at least one implicit type conversion), ad-hoc polymorphism (also known as overloading) or both. These less restrictive usage rules can give the impression that strict adherence to typing rules is less important than in strongly typed languages and hence that the type system is "weaker". However, such languages usually have restrictions on what programmers can do with values of a given type; thus it is possible for a weakly typed language to be type safe. Moreover, weakly typed languages may be statically typed, in which case overloading is resolved statically and type conversion operations are inserted by the compiler, or dynamically typed, in which case everything is resolved at run time.

    11/20/2009

    Preserve line break in textarea

    http://chunghe.googlecode.com/svn/trunk/experiment/textarea.preserve.line.break.htm
    * set the textarea's value by textarea.value, not textarea.innerHTML
    * use br2nl before inserting a<br>b into textarea


    var br2nl = function (str) {
    return str.replace(/<br\s*\/?>/img, "\r");
    }

    FreeRapid Downloader

    FreeRapid Downloader

    FreeRapid is my next application after Wordrider and Damaq. It's a simple Java downloader that supports downloading from Rapidshare and other file-sharing services.
    Simply copy and paste your links from a browser to this application. FreeRapid Downloader will handle the rest itself. No more clicking or uncomfortable waiting.

    Clear upload file input field

    Clear upload file input field
    1. inputFile.value = '': work for ff, not work for ie6.
    2. reset form: not very useful
    3. use filewrapper.innerHTML = filewrapper.innerHTML, workable for ff/ie, remember to re-bind event listeners.

    11/17/2009

    scripiting form elements

    "An important thing to know about event handlers is that within the code of an event handler, the this keyword refers to the document element that triggered the event. Since all form elements have a form property that refers to the containing form, the event handlers of a form element can always refer to the Form object as this.form. Going a step further, this means that an event handler for one form element can refer to a sibling form element named x as this.form.x."


    <form name="sample">
    <input type="text" name="text">
    </form>

    docuemnt.sample.text.form == document.sample

    * The <button> tag may be used anywhere in an HTML document and need not be placed within a <form>.

    * When the user clicks on a toggle button, the radio or checkbox element triggers its onclick event handler to notify the JavaScript program of the change of state. Newer web browsers also trigger the onchange handler for these elements. Both event handlers convey the same essential information, but the onclick handler is more portable.

    jsdoc-toolkit

    jsdoc-toolkit
    Annotating JavaScript for the Closure Compiler

    11/16/2009

    javascript templating

    Closure Templates
    #haml
    EJS - JavaScript Templates
    test.ejs // template file


    <%= title %>



      <% for(var i=0; i<supplies.length; i++) { %>

    • <a href='supplies/<%= supplies[i] %>'>
      <%= supplies[i] %>
      </a>

    • <% } %>

    test.html



    another form: // put data in comments.json

    new EJS({url: 'comments.ejs'}).update('element_id', '/comments.json')

    google closure

    http://erik.eae.net/archives/2009/11/05/22.27.29/

    At the time we were considering using Dojo as our base for this new library. We were very impressed with Dojo but back then Dojo was too unstable and we had heard too many horror stories of upgrade migration head aches. We also looked at MochiKit which was more stable but it did not really solve any of our problems. (*)

    http://www.moretechtips.net/2009/11/getting-closer-to-google-closure.html
    http://blog.louisgray.com/2009/11/story-and-impact-of-closure-googles.html
    http://blog.ericsk.org/archives/1366
    Closure Library API Documentation
    java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js hello.js --js_output_file output.js

    11/14/2009

    GNU ls for Microsoft Windows

    GNU ls for Microsoft Windows
    解開把"*.exe"丟到windows下就算裝完了,裝完後可以在cmd下這樣的指令:
    ls --color| grep 'avi' | sort | more
    GunuWin32 這邊還有一些其他的 porting, ex: sed, awk

    11/13/2009

    Modal window - Wikipedia, the free encyclopedia

    Modal window - Wikipedia, the free encyclopedia

    In user interface design, a modal window is a child window that requires the user to interact with it before they can return to operating the parent application, thus preventing the workflow on the application main window. Modal windows are often called heavy windows or modal dialogs because the window is often used to display a dialog box.

    Modal windows are commonly used in GUI systems to command user awareness and to display emergency states. In the web, they are often used to show images in detail.[1]

    11/11/2009

    yui panel - fixedcenter:contained

    http://developer.yahoo.com/yui/docs/YAHOO.widget.Overlay.html#config_fixedcenter

    fixedcenter - Boolean | String
    Determines whether or not the Overlay should be anchored to the center of the viewport.

    This property can be set to:

    true
    To enable fixed center positioning

    When enabled, the overlay will be positioned in the center of viewport when initially displayed, and will remain in the center of the viewport whenever the window is scrolled or resized.

    If the overlay is too big for the viewport, it's top left corner will be aligned with the top left corner of the viewport.
    false
    To disable fixed center positioning.

    In this case the overlay can still be centered as a one-off operation, by invoking the center() method, however it will not remain centered when the window is scrolled/resized.
    "contained"
    To enable fixed center positioning, as with the true option.

    However, unlike setting the property to true, when the property is set to "contained", if the overlay is too big for the viewport, it will not get automatically centered when the user scrolls or resizes the window (until the window is large enough to contain the overlay). This is useful in cases where the Overlay has both header and footer UI controls which the user may need to access.


    YUI 2: Overlay
    fixedcenter Boolean / String false

    Specifies whether the Overlay should be automatically centered in the viewport on window scroll and resize.

    It also supports the string value "contained", which will enable fixed center behavior, but only if the Overlay fits within the viewport. If the Overlay is larger than the viewport, automatic fixed centering will be disabled until the viewport is large enough to contain the Overlay.

    11/06/2009

    code printing

    TxtPrint homepage

    vim setting


    set printfont=monaco:h7
    set printoptions=header:1,syntax:n,left:4pc,top:4pc,right:2pc,bottom:2pc

    means:
    font-family: consolas,
    font-size: 9px
    header occupy 1 line,
    syntax off
    margin on each side.

    printer setting:
    雙面, 向上翻頁

    tag: text print

    11/02/2009

    How to disable automatic proxy caching in Internet Explorer

    How to disable automatic proxy caching in Internet Explorer

    When you configure Internet Explorer to use an automatic proxy configuration script, it caches the proxy that is returned by the FindProxyForURL call. The caching mechanism (Automatic Proxy Result Cache) is performed on a host basis (that is, not on an URL basis). This prevents you from using different proxies to gain access to the same Web server.

    Windows Registry Editor Version 5.00

    [HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings]"EnableAutoProxyResultCache"=dword:00000000"

    10/30/2009

    JavaScriptMVC 2.0: Major Rewrite, Strong Test Suite Integration and Improved Documentation

    JavaScriptMVC 2.0: Major Rewrite, Strong Test Suite Integration and Improved Documentation
    http://javascriptmvc.com/#&who=fixtures

    css - in the same line

    http://chunghe.googlecode.com/svn/trunk/experiment/css.experiment/same.line.htm

    <div class="meta">This article is public</div>
    <div class="date">published on 2009.10.10</div>
    <div class="navigate">
    <a class="prev"></a>
    <a class="next"></a>
    </div>


    meta{ float:left }
    date{float:left}


    now .navigate is the same line with meta and date.
    .navigate{text-align:right} the all elements same line now