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