Search

1/30/2010

javascript date

Here are some examples of using strings to initialize a date object. It's interesting how many different formats you can use to specify the date.

>>> new Date('2009 11 12')
Thu Nov 12 2009 00:00:00 GMT-0800 (Pacific Standard Time)
>>> new Date('1 1 2012')
Sun Jan 01 2012 00:00:00 GMT-0800 (Pacific Standard Time)
>>> new Date('1 mar 2012 5:30')
Thu Mar 01 2012 05:30:00 GMT-0800 (Pacific Standard Time)

It is good that JavaScript can figure out a date from different strings, but this is not really a reliable way of defining a precise date. The better way is to pass numeric values to the Date() constructor representing:
* Year
* Month: 0 (January) to 11 (December)
* Day: 1 to 31
* Hour: 0 to 23
* Minutes: 0 to 59
* Seconds: 0 to 59
* Milliseconds: 0 to 999

Let's see some examples.
Passing all the parameters:

>>> new Date(2008, 0, 1, 17, 05, 03, 120)
Tue Jan 01 2008 17:05:03 GMT-0800 (Pacific Standard Time)
Passing date and hour:
>>> new Date(2008, 0, 1, 17)
Tue Jan 01 2008 17:00:00 GMT-0800 (Pacific Standard Time)

If you call Date() without new, you get a string representing the current date, whether or not you pass any parameters. This gives the current time (current when this example was run):

>>> Date()
"Thu Jan 17 2008 23:11:32 GMT-0800 (Pacific Standard Time)"
>>> Date(1, 2, 3, "it doesn't matter");
"Thu Jan 17 2008 23:11:35 GMT-0800 (Pacific Standard Time)"

1/26/2010

[包包]TIMBUK2

[包包]TIMBUK2

我實在太常在Flickr--What's in your bag連播中看到TIMBUK2這個牌子的包...
還有不少人是這個包的Fans....所以更讓我好奇這個包的迷人之處了!
這個牌子的發源地是舊金山...算是美國國產包!Made in SF...
它的Logo非常容易辨識...就是一個小小的螺旋...

Branching


var xhrRequest = (function () {
if (ie) {
return function (method, url) { // Use ActiveX control.
};
} else {
return function (method, url) { // Use XMLHttpRequest.
};
}
})();

This is useful, because the branching logic is executed only once, at script load time. If done instead in the traditional way, the branching logic would be execute each time the function is called.

splice, slice

slice() returns a subset of the array it is called on:
slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

var a = ['a', 'b', 'c', 'd', 'e']
// var a = [ 'a' , 'b' , 'c' , 'd' , 'e' ]
// ^0 ^1 ^2 ^3 ^4(-1) ^5(0)
a.slice(0, 3) // ['a', 'b', 'c']
a.slice(2) // ['c', 'd', 'e']
a.slice(1, -1) // ['b', 'c', 'd']
a.slice(-3, -2) // ['c']


splice() is used to insert and remove elements from an array. It modifies the array in place
The first argument is an index where the inserting or removing is to begin
The second argument is how many elements to remove
The remaining arguments are elements to insert at the given index

var a = ['a', 'b', 'c', 'd', 'e'];
a.splice(4); // Returns ['e'], a is ['a', 'b', 'c', 'd']

var a = ['a', 'b', 'c', 'd', 'e'];
a.splice(2, 1, 'z', 'v'); //Returns ["c"], a is ["a", "b", "z", "v", "d", "e"]

1/25/2010

javascript string is Immutable

>>> s = 'hello world'
"hello world"
>>> s[0] = 'a'
"a"
>>> s
"hello world"

http://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-js
from the rhino book:

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it[1]

1/22/2010

魔鬼甄與天使嘉 - 《食記》板橋老夫子(平價)牛排

魔鬼甄與天使嘉 - 《食記》

板橋老夫子(平價)牛排
※板橋老夫子牛排※
地址:台北縣板橋市新生街59號
電話:(02)89699309
時間:11:00~22:00

※延伸閱讀※

食在板橋
http://www.wretch.cc/blog/bajenny&category_id=5960184

1/21/2010

The evolution of client-side scripting

The evolution of client-side scripting

After the completion of ECMA-262 edition 3, significant work was done to develop edition 4. However, ECMAScript's technical committee was split, with some members favoring ECMAScript 4 and others advocating ECMAScript 3.1, which is more modest in both semantic and syntactic innovation. After the 'Oslo meeting' in July 2008 both groups were reunited and agreed upon a new direction and roadmap:

* ECMAScript 4 was abandonded, due to political differences concerning language complexity. Because currently only ActionScript 3 is based on ECMAScript 4, the impact of this decision is that ActionScript will no longer be compliant with new versions of ECMAScript.
* ECMAScript 5 (previously: ECMAScript 3.1) was published as a final draft, planned to become a specification in December 2009.
* ECMAScript Harmony (likely to be renamed to ECMAScript 6) will be the next-generation version of ECMAScript.

1/04/2010

Comet with node.js and V8 - amix blog

Comet with node.js and V8 - amix blog, Youtube - Amir Salihefendic: Comet with node.js 1/6

What makes V8 special
* V8 JavaScript VM is sued in Google Chrome and is developed by a small Google team in Denmark. V8 is open-source.
* V8 team is led by Lars Bak, one of the leading VM engineers in the world with 20 years of experience in building VMs.
* Lars Bak was the technical lead behind HotSpot (Sun's Java VM). HotSpot improved Java's peroformance 20x times.
* Before HotSpot Lars Bak worked on a Samlltalk VM.
* No JIT, all JavaScript is compiled to assembler.
* Hidden classes optimization from Self (V8 does not dynamically lookup access properties, instead it uses hidden classes that are created behind the scene)
* Improved garbage collector. (stop-the-world, generational, accurate, garbage collector)
* Remarks/ "limitations": No bytecode language, no threads, no processes.

What is node.js
* A sysmtem built on top of v8
* The non-blocking nature makes node.js a good fit for comet and next generation realtime web-applications
* 8000 lines of C/C++, 2000 lines of JavaScript, 14 contributors.

Advantages of non-blocking
* nginx: non-blocking, apache: threaded.
* non-bocking can handle more req.pr.sec and uses a lot less memory.
* comet does not scale at all for threaded servers ...

Major point
* JavaScript programming is already geared towards event based programming:
* Closures (anonymouse functions) are natural part of the language.

Blocking vs. non-blocking
* The way to do it in most other languages:

puts("Enter your name: ")
var name = gets();
puts("Name: " + name)

* The way to do it in node.js!

puts("Enter your name: ")
gets(function(name) {
puts("Name: " + name)
})

* nodes.js design philosophy: To receive data from disk, network or another process there must be a callback.

Even in node.js
* All objects which emit events are instance of process.EventEmitter
* A promise is a EventEmitter which emits either success or error, but not both

var tcp = require("tcp");
var s = tcp.createServer();
s.addListener("connection", function (c) {
c.send("hello nasty!");
c.close()
});
s.listen(8000);


var stat = require("posix").stat,
puts = require("sys").puts;

var promise = stat("/etc/passwd");
promise.addClassback(function (s) {
puts("modified: " + s.mtime);
});
promise.addErrback(function(orgi_promise) {
puts("Could not fetch stats on /etc/passwd")
});


Implmenting comet
* Long polling
- works for most parts. Used in Plurk
- is more expensive and problematic than streaming
* Streaming without WebSockets:
- very problematic due to proxies and firewalls.
* Streaming with WebSockets (HTML5):
- Makes comet trivial on both client and server side

WebSockets
* Aims to expose TCP/IP sockets to browsers, while respecting the constraints of the web (security, proxies and firewalls)
* A thin layer on top of TCP/IP that adds:
- orgin based security model
* Addressing and protocol naming, mechanism for supporting multiple services on one port and multiple host names on one IP address
* framing mechanism for data transportation.

Other comet servers
* JBoss Netty: Java library for doing non-blocking networking, based on java.nio
* erlycomet: Erlang comet server based on MochiWeb
* Tornado: FriendFeed's Python non-blocking server.


via: Amir Salihefendic 演講: Comet with node.js 影片 與 筆記

1/02/2010

Extreme JavaScript Performance

Extreme JavaScript Performance

#1 avoid function calls.

function methodCall() {
function square(n) {return n*n};
var i=10000, sum=0;
while (i--) sum += square(i);
}
function inlineMethod() {
var i=1000, sum=0;
while(i--) sum += i*i;
}

#2 embrace the language

function literals() {
var a = [], o = {};
}
function classic() {
var a = new Array, o = new Object;
}

#4 cache globals

function uncached() {
var i = 10000;
while(i--) window.test = 'test';
}
function cached() {
var w = window, i = 10000;
while(i--) w.test = 'test';
}

(Firefox, Safari, Chrome)Modern JavaScript engines have JIT comilers, which don't support certain features well.
Avoid stuff that's not available in ECMA-262 5th Edition "strict" mode.


via: http://developer.yahoo.net/blog/archives/2009/11/jsconfeu_all_th.html

Reactor pattern

Reactor pattern

The reactor design pattern is a concurrent programming pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers.

* Resources: Any resource that can provide input or output to the system.
* Synchronous Event Demultiplexer: Uses an event loop to block on all resources. When it is possible to start a synchronous operation on a resource without blocking, the demultiplexer sends the resource to the dispatcher.
* Dispatcher: Handles registering and unregistering of request handlers. Dispatches resources from the demultiplexer to the associated request handler.
* Request Handler: An application defined request handler and its associated resource.


http://www.cs.wustl.edu/~schmidt/PDF/reactor-siemens.pdf

Event loop - Wikipedia, the free encyclopedia

Event loop - Wikipedia, the free encyclopedia

In computer science, the event loop, message dispatcher, message loop or message pump is a programming construct that waits for and dispatches events or messages in a program. It works by polling some internal or external "event provider", which generally blocks until an event has arrived, and then calls the relevant event handler ("dispatches the event"). The event-loop may be used in conjunction with a reactor, if the event provider follows the file interface (which can be select()ed or poll()ed). The event loop almost always operates asynchronously with the message originator.

When the event loop forms the central control flow construct of a program, as it often does, and is thus at the highest level of control within the program, it may be termed the main loop or main event loop.

Green threads

Green threads

In computer programming, green threads are threads that are scheduled by a Virtual Machine (VM) instead of natively by the underlying operating system. Green threads emulate multithreaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support[1].

Green and native threads -- what's the difference?
Green threads, the threads provided by the JVM, run at the user level, meaning that the JVM creates and schedules the threads itself. Therefore, the operating system kernel doesn't create or schedule them. Instead, the underlying OS sees the JVM only as one thread.

Green threads prove inefficient for a number of reasons. Foremost, green threads cannot take advantage of a multiprocessor system. Since the JVM simply runs from within one thread, the threads that the JVM creates are not threads at the OS level. Instead, the JVM splits its timeslice among the various threads that it spawns internally. Thus, the JVM threads are bound to run within that single JVM thread that runs inside a single processor.

In contrast, native threads are created and scheduled by the underlying operating system. Rather than create and schedule threads itself, the JVM creates the threads by calling OS-level APIs. As a result, native threads can benefit from multiple processors. Performance can improve because an IO-blocked thread will no longer block the entire JVM. The block will only block the thread waiting for the IO resource.

There are times when you might want to run green threads. First, native threads are not always available. Second, if your code is not thread-safe, you may experience errors when running native threads.

CommonJS

CommonJS

JavaScript is a powerful object oriented language with some of the fastest dynamic language interpreters around. The official JavaScript specification defines APIs for some objects that are useful for building browser-based applications. However, the spec does not define a standard library that is useful for building a broader range of applications.

The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java. The intention is that an application developer will be able to write an application using the CommonJS APIs and then run that application across different JavaScript interpreters and host environments. With CommonJS-compliant systems, you can use JavaScript to write:

* Server-side JavaScript applications
* Command line tools
* Desktop GUI-based applications
* Hybrid applications (Titanium, Adobe AIR)


CommonJS Spec Wiki

1/01/2010

Ruby / EventMachine - Trac

Ruby / EventMachine - Trac

EventMachine is a library for Ruby, C++, and Java programs. It provides event-driven I/O using the Reactor pattern. EventMachine is designed to simultaneously meet two key needs:

* Extremely high scalability, performance and stability for the most demanding production environments; and
* An API that eliminates the complexities of high-performance threaded network programming, allowing engineers to concentrate on their application logic.

This unique combination makes EventMachine a premier choice for designers of critical networked applications, including web servers and proxies, email and IM production systems, authentication/authorization processors, and many more.

Reactor pattern - Wikipedia, the free encyclopedia
http://www.cs.uu.nl/docs/vakken/no/reactor.pdf