Friday, December 24, 2010

[warn] (2)No such file or directory: Failed to enable the 'httpready' Accept Filter

When Apache web server
is starting up in FreeBSD system, Apache loads succcessfully and web server functioning properly, but the following warning error occurs:

[warn] (2)No such file or directory:
Failed to enable the ‘httpready’ Accept Filter

The resolution to the above problem is to a accf_http module, which function is to buffer incoming connections until a certain complete HTTP requests arrive, into FreeBSD kernel by using kernel linker:

kldload accf_http

To permanently load enable HTTP Accept Filter FreeBSD kernel module (accf_http), add the following line into /boot/loader.conf:

accf_http_load=”YES”

Note: The default settings is located in /boot/defaults/loader.cnf. To see the related settings about accf, use:

grep accf /boot/defaults/loader.conf

which will returns:

accf_data_load=”NO” # Wait for data accept filter
accf_http_load=”NO” # Wait for full HTTP request accept filter

============ [START] httpready accept filter problem solution ==============
Note: rc.d script for apache now manage this accf_http kernel module
Just add following line to your /etc/rc.conf
root@bmw0 [/root] # vi /etc/rc.conf
apache22_http_accept_enable="YES"

Please note that there is a line in httpd.conf:

Include etc/apache22/Includes/*.conf

the line above includes one of files called:

/usr/local/etc/apache22/Includes/no-accf.conf

This file above turns accf_http off.

So, make sure you do comment out two lines in /usr/local/etc/apache22/Includes/no-accf.conf:

<IfDefine NOHTTPACCEPT>
#AcceptFilter http none
#AcceptFilter https none
</IfDefine>
============ [END] httpready accept filter problem solution ==============

Adding to /boot/loader.conf will make the change permanent, but if you fancy testing this change out without rebooting your system, you can run this: -


# kldload accf_http

You can see that it’s been loaded by doing: -


# kldstat
Id Refs Address Size Name
1 5 0xc0400000 6f6544 kernel
2 1 0xc41f6000 2000 accf_http.ko <-- you just loaded this module!

You can now restart Apache and see that your previous error is no longer.

如用戶忘記登入密碼可按下列方法解決

如用戶忘記登入密碼可按下列方法解決

1. 在電腦啟動時按〔F8〕及選〔Safe Mode With Command Prompt〕

2. 選 〔Administrator〕後便會跳出〔Command Prompt〕的窗口

3. 用〔Net〕的命令增加一個用戶,例:增加一個用戶名為 alanhkg888,命令語法如下
net user alanhkg888 /add

4. 將新增用戶提升至 Administrator 的權力,例:提升剛才增加用戶 alanhkg888 的權力,命令語法如下
net localgroup administrators alanhkg888 /add

5. 完成上列步驟後重新啟動電腦,在啟動畫面上便增加了一個用戶 alanhkg888 了,選 alanhkg888 進入

6. 登入後在〔控制台〕→〔使用者帳戶〕→選忘記密碼的用戶,然後選〔移除密碼〕後〔等出〕

7. 在登入畫面中選原來的用戶便可不需密碼情況下等入 (因已移除了)

刪除剛才新增的用戶,在〔控制台〕→〔使用者帳戶〕→選〔alanhkg888〕,然後選〔移除帳戶〕便可
*不適用於忘記安裝時所設定〔administrator〕的密碼

PF + NAT + multiple external ips

PF + NAT + multiple external ips

Hi!

I got everything set and working fine, im connecting to a vpn on the machine that nats the user to the external interface, the only thing i do not manage to solve is that i got multiple ips on my external interface

Example of my ifconfig

Code:
inet 95.168.183.173 netmask 0xffffff00 broadcast 95.168.183.255
inet 84.16.247.166 netmask 0xffffffff broadcast 84.16.247.166
inet 84.16.247.167 netmask 0xffffffff broadcast 84.16.247.167
inet 188.72.222.11 netmask 0xffffffff broadcast 188.72.222.11
inet 188.72.222.12 netmask 0xffffffff broadcast 188.72.222.12
inet 188.72.222.13 netmask 0xffffffff broadcast 188.72.222.13
inet 188.72.222.14 netmask 0xffffffff broadcast 188.72.222.14
inet 188.72.222.15 netmask 0xffffffff broadcast 188.72.222.15
inet 188.72.222.16 netmask 0xffffffff broadcast 188.72.222.16
inet 188.72.222.17 netmask 0xffffffff broadcast 188.72.222.17
inet 188.72.222.18 netmask 0xffffffff broadcast 188.72.222.18

The only problem i got is that the vpn users randomly uses all the ips on that interface, one request can be with 84.16.247.166 and the next can be 188.72.222.18.

What im trying to do is that the vpn users only uses the 95.168.183.173 ip (its the default machine ip which all the other softwares also uses), how do i do that? I cant find anything about that in the nat section in pf nor in the openvpn config

===================================

Hello,

put

Code:
local 95.168.183.173 in your openvpn.conf


Quote:
--local host
Local host name or IP address for bind. If specified, OpenVPN
will bind to this address only. If unspecified, OpenVPN will
bind to all interfaces.

---

If you want exactly to tell PF which is the external IP address for NAT you can set for example as follow:

Code:
ext_if="em0"
int_if="em1"


ext_if_ip="95.168.183.173"


nat on $ext_if from $int_if:network -> $ext_if_ip

http://forums.freebsd.org/showthread.php?t=17586

Thursday, December 23, 2010

Add multiple IP addresses on one NIC network card in FreeBSD

IP aliasing is the process of assigning more than one IP address to a network interface. This is useful for Apache web server virtual hosting or other network servers such as ftp server.

# vi /etc/rc.conf
ifconfig_[card_type]="inet [primary ip address] netmask [your netmask]"
ifconfig_[card_type]_alias0="[secondary ip address] netmask 255.255.255.255"
ifconfig_[card_type]_alias1="[secondary ip address] netmask 255.255.255.255"

Note: the netmask of alias must be 255.255.255.255

Restart FreeBSD network service using network restart script:
# /etc/rc.d/netif restart && /etc/rc.d/routing restart

Sample:

hostname="sun.nixcraft.in"
# default vsnl router interface
defaultrouter="202.54.1.200"
# Force 10Mbps for both public and private LAN interace
ifconfig_em0="inet 10.20.110.2 netmask 255.255.255.192 media 10baseT/UTP mediaopt full-duplex"
ifconfig_em1="inet 202.52.1.2 netmask 255.255.255.248 media 10baseT/UTP mediaopt full-duplex"
ifconfig_em0_alias0="inet 10.20.1.226 netmask 255.255.255.255"
ifconfig_em0_alias1="inet 10.20.1.227 netmask 255.255.255.255"
ifconfig_em0_alias2="inet 10.20.1.228 netmask 255.255.255.255"
ifconfig_em0_alias3="inet 10.20.1.229 netmask 255.255.255.255"
ifconfig_em0_alias4="inet 10.20.1.230 netmask 255.255.255.255"
# static routing configuration
static_routes="lan0"
route_lan0="-net 10.0.0.0/8 10.20.110.1"

Reference: http://www.cyberciti.biz/tips/freebsd-how-to-setup-2-ip-address-on-one-nic.html

Tuesday, December 21, 2010

OpenLayers - Free Maps for the Web written in JavaScript

OpenLayers - Free Maps for the Web written in JavaScript

http://openlayers.org/

http://drupal.org/project/openlayers

Sunday, December 19, 2010

The True Story of Hello World

The True Story of Hello World

(or at least a good part of it)


Most of our computer science students have been through the
famous "Hello World" program at least once. When compared to a
typical application program ---almost always featuring a web-aware
graphical user interface, "Hello World" turns into an very
uninteresting fragment of code. Nevertheless, many computer science
students still didn't get the real story behind it. The goal of this
exercise is to cast some light in the subject by snooping in the
"Hello World" life-cycle.



The source code


Let's begin with Hello World's source code:



1.

2.

3.

4.

5.

6.

7.

#include <stdio.h>



int main(void)

{

    printf("Hello World!\n");

    return 0;

}

Line 1 instructs the compiler to include the declarations needed
to invoke the printf C library (libc) function.


Line 3 declares function main, which is believed to be our
program entry point (it is not, as we will see later). It is
declared as a function that takes no parameter (we disregard command
line arguments in this program) and returns an integer to the parent
process --- the shell, in our case. By the way, the shell
dictates a convention by which a child process must return an 8-bit
number representing it status: 0 for normal termination, 0
> n < 128
for process detected abnormal termination, and
n > 128 for signal induced termination.


Line 4 through 8 comprise the definition of function main,
which invokes the printf C library function to output the
"Hello World!\n" string and returns 0 to the parent process.


Simple, very simple!



Compilation


Now let's take a look at the compilation process for "Hello
World". For the upcoming discussion, we'll take the widely-used GNU
compiler (gcc) and its associated tools (binutils). We
can compile the program as follows:


# gcc -Os -c hello.c

This produces the object file hello.o. More
specifically,



# file hello.o

hello.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not
stripped


tells us hello.o is a relocatable object file, compiled for the
IA-32 architecture (I used a standard PC for this study), stored in
the Executable
and Linking Format (ELF)
, that contains a symbol table (not
stripped).


By the way,


# objdump -hrt hello.o

hello.o:     file format elf32-i386



Sections:

Idx Name          Size     VMA       LMA       File off  Algn

  0 .text         00000011 00000000  00000000  00000034  2**2

                  CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE

  1 .data         00000000 00000000  00000000  00000048  2**2

                  CONTENTS, ALLOC, LOAD, DATA

  2 .bss          00000000 00000000  00000000  00000048  2**2

                  ALLOC

  3 .rodata.str1.1 0000000d  00000000  00000000  00000048 2**0

                  CONTENTS, ALLOC, LOAD, READONLY, DATA

  4 .comment      00000033  00000000 00000000  00000055  2**0

                  CONTENTS, READONLY



SYMBOL TABLE:

00000000 l    df *ABS*  00000000 hello.c

00000000 l    d  .text  00000000

00000000 l    d  .data  00000000

00000000 l    d  .bss   00000000

00000000 l    d  .rodata.str1.1 00000000

00000000 l    d  .comment      
00000000

00000000 g    F  .text  00000011 main

00000000         *UND*  00000000 puts



RELOCATION RECORDS FOR [.text]:

OFFSET   TYPE              VALUE

00000004 R_386_32          .rodata.str1.1

00000009 R_386_PC32        puts


tells us hello.o has 5 sections:


  1. .text: that's "Hello World" compiled program,
    i.e. IA-32 opcodes corresponding to the program. This will be used
    by the program loader to initialize the process' code
    segment
    .
  2. .data: "Hello World" has neither initialized global
    variables nor initialized static local variables, so this section
    is empty. Otherwise, it would contain the variable initial values
    to be loaded into the data segment.
  3. .bss: "Hello World" also doesn't have any
    non-initialized variable, either global or local, so this section
    is also empty. Otherwise, it would indicate how many bytes must be
    allocated and zeroed in the data segment in addition to
    section .data.
  4. .rodata: this segment contains the "Hello World!\n"
    string, which is tagged read-only. Most operating systems do not
    support a read-only data segment for processes (running
    programs), so the contents of .rodata go either to the
    process' code segment (because it's read-only), or to the
    data segment (because it's data). Since the compiler
    doesn't know the policy adopted by your OS, it creates this extra
    ELF section.
  5. .comment: this segment contains 33 bytes of comments
    which cannot be tracked back to our program, since we didn't write
    any comment. We'll soon see where it comes from.

It also shows us a symbol table with symbol main
bound to address 00000000 and symbol puts
undefined. Moreover, the relocation table tells us how to
relocate the references to external sections made in section
.text. The first relocatable symbol corresponds to the "Hello
World!\n" string contained in section .rodata. The second
relocatable symbol, puts, designates a libc function
which was generated as a result of invoking printf. To better
understand the contents of hello.o, let's take a look at the
assembly code:



1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

# gcc -Os -S hello.c -o -


        .file   "hello.c"

        .section       .rodata.str1.1,"aMS",@progbits,1

.LC0:

        .string "Hello World!"

        .text

        .align 2

.globl main

        .type   main,@function

main:

        pushl   %ebp

        movl    %esp, %ebp

        pushl   $.LC0

        call    puts

        xorl    %eax, %eax

        leave

        ret

.Lfe1:

        .size   n,.Lfe1-n

        .ident  "GCC: (GNU) 3.2 20020903 (Red Hat Linux 8.0 3.2-7)"

From the assembly code, it becomes clear where the ELF section
flags come from. For instance, section .text is to be 32-bit
aligned (line 7). It also reveals where the .comment section
comes from (line 20). Since printf was called to print a
single string, and we requested our nice compiler to optimize the
generated code (-Os), puts was generated
instead. Unfortunately, we'll see later that our libc
implementation will render the compiler effort useless.


And what about the assembly code produced? No surprises here: a
simple call to function puts with the string addressed by
.LC0 as argument.



Linking


Now let's take a look at the process of transforming
hello.o into an executable. One might think the following
command would do:


# ld -o hello hello.o -lc

ld: warning: cannot find entry symbol _start; defaulting to 08048184



But what's that warning? Try running it!


Yes, it doesn't work. So let's go back to that warning: it tells
the linker couldn't find our program's entry point
_start. But wasn't it main our entry point? To be
short here, main is the start point of a C program from the
programmer's perspective. In fact, before calling main, a process
has already executed a bulk of code to "clean up the room for
execution". We usually get this surrounding code transparently from
the compiler/OS provider.


So let's try this:



# ld -static -o hello -L`gcc -print-file-name=` /usr/lib/crt1.o /usr/lib/crti.o hello.o /usr/lib/crtn.o -lc -lgcc


Now we should have a real executable. Static linking was used for
two reasons: first, I don't want to go into the discussion of how
dynamic libraries work here; second, I'd like to show you how much
unnecessary code comes into "Hello World" due to the way libraries
(libc and libgcc) are implemented. Try the following:



# find hello.c hello.o hello -printf "%f\t%s\n"

hello.c 84

hello.o 788

hello   445506



You can also try "nm hello" or "objdump -d
hello
" to get an idea of what got linked into the
executable.


For information about dynamic linking, please refer to Program
Library HOWTO
.



Loading and running


In a POSIX OS, loading a program for execution is accomplished by
having the father process to invoke the fork system
call to replicates itself and having the just-created child
process to invoke the execve system call to load and start
the desired program. This procedure is carried out, for instance, by
the shell whenever you type an external command. You can
confirm this with truss or strace:



# strace -i hello > /dev/null

[????????] execve("./hello", ["hello"], [/* 46 vars */]) = 0

...

[08053d44] write(1, "Hello World!\n", 13) = 13

...

[0804e7ad] _exit(0) = ?



Besides the execve system call, the output shows the call
to write that results from puts, and the call to
exit with the argument returned by function main
(0).


To understand the details behind the loading procedure carried
out by execve, let's take a look at our ELF executable:



# readelf -l hello

Elf file type is EXEC (Executable file)

Entry point 0x80480e0

There are 3 program headers, starting at offset 52



Program Headers:

  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align

  LOAD           0x000000 0x08048000 0x08048000 0x55dac 0x55dac R E 0x1000

  LOAD           0x055dc0 0x0809edc0 0x0809edc0 0x01df4 0x03240 RW  0x1000

  NOTE           0x000094 0x08048094 0x08048094 0x00020 0x00020 R   0x4



Section to Segment mapping:

  Segment Sections...

   00     .init .text .fini .rodata __libc_atexit __libc_subfreeres .note.ABI-tag

   01     .data .eh_frame .got .bss

   02     .note.ABI-tag


The output shows the overall structure of hello. The first
program header corresponds to the process' code
segment
, which will be loaded from file at offset 0x000000 into
a memory region that will be mapped into the process' address
space
at address 0x08048000. The code segment will be 0x55dac
bytes large and must be page-aligned (0x1000). This segment will
comprise the .text and .rodata ELF segments discussed
earlier, plus additional segments generated during the linking
procedure. As expected, it's flagged read-only (R) and executable
(X), but not writable (W).


The second program header corresponds to the process'
data segment. Loading this segment follows the same steps
mentioned above. However, note that the segment size is 0x01df4 on
file and 0x03240 in memory. This is due to the .bss section,
which is to be zeroed and therefore doesn't need to be present in
the file. The data segment will also be page-aligned (0x1000) and
will contain the .data and .bss ELF segments. It will
be flagged readable and writable (RW). The third program header
results from the linking procedure and is irrelevant for this
discussion.


If you have a proc file system, you can check this, as
long as you get "Hello World" to run long enough (hint: gdb),
with the following command:



# cat /proc/`ps -C hello -o pid=`/maps

08048000-0809e000 r-xp 00000000 03:06 479202     .../hello

0809e000-080a1000 rw-p 00055000 03:06 479202     .../hello

080a1000-080a3000 rwxp 00000000 00:00 0

bffff000-c0000000 rwxp 00000000 00:00 0


The first mapped region is the process' code segment, the
second and third build up the data segment (data + bss +
heap
), and the fourth, which has no correspondent in the ELF
file, is the stack. Additional information about the running
hello process can be obtained with GNU time,
ps, and /proc/pid/stat.



Terminating


When "Hello World" executes the return statement in
main function, it passes a parameter to the surrounding
functions discussed in section linking. One of these functions
invokes the exit system call passing by the return
argument. The exit system call hands over that value to the
parent process, which is currently blocked on the wait
system call. Moreover, it conducts a clean process termination, with
resources being returned to the system. This procedure can be
partially traced with the following:



# strace -e trace=process -f sh -c "hello; echo $?" > /dev/null

execve("/bin/sh", ["sh", "-c", "hello; echo 0"], [/* 46 vars */]) = 0

fork()                                 
= 8321

[pid  8320] wait4(-1,  <unfinished ...>

[pid  8321] execve("./hello", ["hello"], [/* 46 vars */]) = 0

[pid  8321] _exit(0)                    = ?

<... wait4 resumed> [WIFEXITED(s) && WEXITSTATUS(s) == 0], 0, NULL) = 8321

--- SIGCHLD (Child exited) ---

wait4(-1, 0xbffff06c, WNOHANG, NULL)    = -1 ECHILD (No child processes)

_exit(0)



Closing


The intention of this exercise is to call attention of new
computer science students to the fact that a Java applet doesn't get
run by magic: there's a lot of system software behind even the
simplest program. If consider it useful and have any suggestion to
improve it, please e-mail
me
.



FAQ


This section is dedicated to student's frequently asked questions.


  • What is "libgcc"? Why is included in linkage?
  • Internal compiler libs, such as libgcc, are used to implement language constructs not directly implemented by the target architecture. For instance, the module operator in C ("%") might not be mappable to a single assembly instruction on the target architecture. Instead of having the compiler to generate in-line code, a function call might be preferable (specially for memory limited machines such as microcontrollers). Many other primitives, including division, multiplication, string manipulation (e.g. memory copy) are typically implemented on such libraries.


Reference:
http://www.lisha.ufsc.br/teaching/os/exercise/hello.html

Linux 下程序的記憶體映射

Friday, December 17, 2010

make your custom menu link to support overlay in Drupal 7 D7

make your custom menu link to support overlay in Drupal 7 D7

Overlay (and admin)


Why: because people often lose context when doing an admin task. With the overlay module, when you are through with your admin task, you are returned to where you were before you started.

You tell a link to open in the overlay by specifying that it is an “admin” link. Implement hook_admin_paths()

<?php
/**
 * Implementation of hook_admin_paths()
 */
function mymodule_admin_paths() {
  $paths = array (
    'my_first_link' => TRUE,
    'my_second_link' => TRUE,
  );

  return $paths;
}
?>

To alter admin paths set by other modules, use hook_admin_paths_alter().

Additional Resources
http://drupal.org/ui-standards

Adding borrowing CCK FileField file field to a custom multiple upload form in Drupal 6 D6

Adding borrowing CCK FileField file field to a custom multiple upload form in Drupal 6 D6

1. create a cck field called "myfile" in a content type of your choice.

2. create a testing module called "mymodule".
<?php
/**
 * Implementation of hook_menu()
 */
function mymodule_menu() {
  $items = array();
  
  $items['test'] = array(
    'title' => 'test',
    'page callback' => 'mymodule_test',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_test() {
  return drupal_get_form('mymodule_test_form');
}

function mymodule_test_form() {
  module_load_include('inc', 'content', 'includes/content.node_form');

  $form = array();

  // Definition of the CCK fields array that we want to use in our custom form
  $fields = array('field_myfile');

  foreach ($fields as $name) {
    // Calling the CCK API function to create the field
    $field = content_fields($name);

    // Put element information into hidden non-displaying form container
    $form['#field_info'][$name] = $field;

    // Render the element, then add the rendered element to the form.
    $form += (array) content_field_form($form, $form_state, $field);

  }

  // You can set weight for the paticular element
  $form['field_myfile']['#weight'] = 1;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
    '#weight' => 2,
  );

  return $form;
}

function mymodule_test_form_submit($form, &$form_state) {
  echo '<pre>';
  print_r($form_state);
  echo '</pre>';
}
?>

Wednesday, December 15, 2010

賴世雄:學英語七步曲

賴世雄:學英語七步曲

1.用垃圾時間學英語:可以將時間化整為零,當然在學習的期間一定要讓自己的嘴巴忙碌起來,反覆複述一個句子或單字…

2.別太貪功:學英語不可能速成,因此起步別太急,「貪多嚼不爛」是有道理的。先以簡單入手,由淺入深循序漸進。

3.一定要撐下去:挫折感是常常出現的,在這時候一定要反覆告訴自己撐下去……撐下去……撐下去…… 一定要有恆心。

4.學英語可以不要臉:不要怕說錯,很多錯誤可以在與人交流的過程中慢慢改過來。

5.聽力練習追大意:練習聽力時注意不要過分專心,要追大意別中斷,另外要選用慢速英文聽力教材,反覆聽。

6.發音不必強求:要學美式發音還是英式或澳式發音都不要緊,就算發音中帶有地方口音也沒關係,關鍵在於讓對方聽懂即可。

7.單字夠用即可:不少人將背單字當作學實用(區別於應試)外語的第一關,其實一個道地美國人每日所使用的單字不過2000個左右,而對非英語國家的學習者來說,掌握常用的600個左右的單字,即可與人自由交流了!

Debug jQuery Event Ajax

星雨...@ home says:
你開始玩 jQuery 做 ajax 的時候 用 IE的話
HttpWatchPro 會是最好用的工具之一! 不過他是商業軟體!!

另外用 FireFox 的話還有三個更好用的工具 FireBug + FirePHP + yslow (Yahoo! YSlow)

[] HttpWatch or HttpWatchPro - is an integrated HTTP sniffer for IE and Firefox that provides new insights into how your website loads and performs. Change the way that you develop, debug and tune websites today!

[] FireBug - Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

[] FirePHP - FirePHP enables you to log to your Firebug Console using a simple PHP method call.

All data is sent via response headers and will not interfere with the content on your page.

FirePHP is ideally suited for AJAX development where clean JSON and XML responses are required.

[] Eventbug - is a Firebug extension that lists all of the event handlers on the page grouped by event type.

[] FireQuery - is a Firefox extension integrated with Firebug.

[] jQuery Trace Plug-in

[] Web Developer Toolbar - The Web Developer extension adds various web developer tools to a browser. The extension is available for Firefox and Chrome, and will run on any platform that these browsers support including Windows, Mac OS X and Linux.

[] yslow (Yahoo! YSlow) - YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages. YSlow is a Firefox add-on integrated with the Firebug web development tool. YSlow grades web page based on one of three predefined ruleset or a user-defined ruleset. It offers suggestions for improving the page's performance, summarizes the page's components, displays statistics about the page, and provides tools for performance analysis, including Smush.it™ and JSLint.

都是 WEB RD debug 的強力工具!

Event order - what is Event capturing and Event bubbling

On the Introduction to events page
I asked a question that at first sight seems incomprehensible:

“If an element and one of its ancestors have an event handler for the same event, which
one should fire first?” Not surprisingly, this depends on the browser.


The basic problem is very simple. Suppose you have a element inside an element


-----------------------------------
| element1                        |
|   -------------------------     |
|   |element2               |     |
|   -------------------------     |
|                                 |
-----------------------------------

and both have an onClick event handler. If the user clicks on element2 he causes
a click event in both element1 and element2. But which event fires first? Which event handler should
be executed first? What, in other words, is the event order?


Two models


Not surprisingly, back in the bad old days Netscape and Microsoft came to different conclusions.


  • Netscape said that the event on element1 takes place first. This is called
    event capturing.
  • Microsoft maintained that the event on element2 takes precedence. This is called
    event bubbling.

The two event orders are radically opposed. Explorer
only supports event bubbling. Mozilla, Opera 7 and Konqueror support both. Older Opera's and
iCab support neither.


Event capturing


When you use event capturing


| |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.



Event bubbling


When you use event bubbling


/ \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.


W3C model


W3C has very sensibly decided to take a middle position in this struggle.
Any event taking place in the
W3C event model is first captured until it
reaches the target element and then bubbles up again.


| |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------

You, the web developer, can choose whether to register an event handler in the capturing or
in the bubbling phase. This is done through the addEventListener()
method explained on the Advanced models page.
If its last argument is true the event handler is set for the capturing phase, if it is
false the event handler is set for the bubbling phase.


Suppose you do


element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)

If the user clicks on element2 the following happens:


  1. The click event starts in the capturing phase. The event looks if any
    ancestor element of element2 has a onclick event handler for the capturing
    phase.
  2. The event finds one on element1. doSomething2() is
    executed.
  3. The event travels down to the target itself, no more event handlers for the capturing
    phase are found. The event moves to its bubbling phase and executes doSomething(),
    which is registered to element2 for the bubbling phase.
  4. The event travels upwards again and checks if any ancestor element of the
    target has an event handler for the bubbling phase. This is not the case, so nothing happens.


The reverse would be


element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)

Now if the user clicks on element2 the following happens:


  1. The click event starts in the capturing phase. The event looks if any
    ancestor element of element2 has a onclick event handler for the capturing
    phase and doesn’t find any.
  2. The event travels down to the target itself.
    The event moves to its bubbling phase and executes doSomething(),
    which is registered to element2 for the bubbling phase.
  3. The event travels upwards again and checks if any ancestor element of the
    target has an event handler for the bubbling phase.
  4. The event finds one on element1. Now doSomething2() is executed.

Compatibility with traditional model


In the browsers that support the W3C DOM, a traditional event registration


element1.onclick = doSomething2;

is seen as a registration in the bubbling phase.



Use of event bubbling


Few web developers consciously use event capturing or bubbling. In Web pages as they are made
today, it is simply not necessary to let a bubbling event be handled by several different event handlers.
Users might get confused by several things happening after one mouse click, and usually you want
to keep your event handling scripts separated. When the user clicks on an element, something happens,
when he clicks on another element, something else happens.


Of course this might change in the future, and it’s good to have models available that
are forward compatible. But the main practical use of event capturing and bubbling today
is the registration of default functions.


It always happens


What you first need to understand is that event capturing or bubbling always happens.
If you define a general onclick event handler for your entire document


document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);

any click event on any element in the document will eventually bubble up to the document and
thus fire this general event handler.
Only when a previous event handling script explicitly orders the event to stop bubbling, it will not propagate to the
document.


Uses


Because any event ends up on the document, default event handlers become possible.
Suppose you have this page:


------------------------------------
| document                         |
|   ---------------  ------------  |
|   | element1    |  | element2 |  |
|   ---------------  ------------  |
|                                  |
------------------------------------

element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;

Now if the user clicks on element1 or 2, doSomething() is executed. You can
stop the event propagation here, if you wish. If you don’t the event bubbles up to
defaultFunction().
If the user clicks anywhere else defaultFunction() is also executed. This might be
useful sometimes.



Setting document–wide event handlers is necessary in drag–and–drop
scripts. Typically a mousedown event on a layer selects this layer and makes
it respond to the mousemove event. Though the
mousedown is usually registered on the layer to avoid browser bugs, both
other event handlers must be document–wide.


Remember the First Law of Browserology: anything can happen, and it usually does when you’re
least prepared for it. So it may happen that the user moves his mouse very wildly and the
script doesn’t keep up so that the mouse is not over the layer any more.


  • If the onmousemove event handler is registered to the layer,
    the layer doesn’t react to the mouse movement any more, causing confusion.
  • If the onmouseup event handler is registered on the layer,
    this event isn’t caught either so that the layer keeps reacting to the mouse
    movements even after the user thinks he dropped the layer. This causes even more confusion.

So in this case event bubbling is very useful because registering
your event handlers on document level makes sure they’re always executed.


Turning it off


But usually you want to turn all capturing and bubbling off to keep functions from
interfering with each other.
Besides, if your document structure is very complex (lots of nested tables and such) you may save system
resources by turning off bubbling. The browser has to go through every single ancestor element
of the event target to see if it has an event handler. Even if none are found, the search still takes time.


In the Microsoft model you must set the event’s cancelBubble property to true.


window.event.cancelBubble = true

In the W3C model you must call the event’s stopPropagation() method.


e.stopPropagation()

This stops all propagation of the event in the bubbling phase.
Stopping event propagation in the capturing phase is impossible. One wonders why.


For a complete cross-browser experience do


function doSomething(e)
{
 if (!e) var e = window.event;
 e.cancelBubble = true;
 if (e.stopPropagation) e.stopPropagation();
}

Setting the cancelBubble property in browsers that don’t support it doesn’t hurt.
The browser shrugs and creates the property. Of course it doesn’t actually
cancel the bubbling, but the assignment itself is safe.


currentTarget


As we’ve seen earlier, an event has a target or srcElement that
contains a reference to the element the event happened on. In our example this is element2,
since the user clicked on it.


It is very important to understand that during the capturing and bubbling phases (if any)
this target does not change: it always remains a reference to element2.


But suppose we register these event handlers:


element1.onclick = doSomething;
element2.onclick = doSomething;

If the user clicks on element2 doSomething() is executed twice. But how
do you know which HTML element is currently handling the event? target/srcElement
don’t give a clue, they always refer to element2 since it is the original source of the
event.


To solve this problem W3C has added the currentTarget property. It contains a
reference to the HTML element the event is currently being handled by: exactly what we need.
Unfortunately the Microsoft model doesn’t contain a similar property.


You can also use
the this keyword.
In the example above it refers to the HTML element the event is handled on, just like
currentTarget.


Problems of the Microsoft model


But when you use the Microsoft event registration model
the this keyword doesn’t refer to the HTML element. Combined with the
lack of a currentTarget–like property in the Microsoft model,
this means that if you do


element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)

you cannot know which HTML element currently handles the event. This is the most
serious problem with the Microsoft event registration model and for me it’s reason enough
never to use it, not even in IE/Win only applications.


I hope Microsoft will soon add a currentTarget–like property — or maybe
even follow the standard? Web developers need this information.


Continue


If you wish to go through all event pages in order, you should now continue with the
Mouse events page.


http://www.quirksmode.org/js/events_order.html

How live method works in jQuery. Why it does not work in some cases. When to use livequery

Following code has been tested with jQuery 1.3.2 version .

All the JavaScript code mentioned in this blog should be tried on firebug.


The super popular live method was added to jQuery 1.3 . It works just great. Except when it does not work. As per the documentation this method does not work in following cases: blur, focus, mouseenter, mouseleave, change, submit .

How binding events work in jQuery

$('a').click(function(){
  console.log('clicked');
});

In above case ‘click’ event is bound to all the links in the ‘document’. jQuery stores such binding information as ‘data’ attribute of the bound element. This is how I can access the list of all functions bound to an element.


$('a').data('events');// Object click=Object

If a new link is dynamically added then that new link will not get this click behavior. Tosolve this problem I can use live method.

Trying out live event

$('a').live('click',function(){
  console.log('clicked');
});

If I add a new ‘a’ tag dynamically then that tag will automatically get the new click behavior. That’s great.

Just like the previous section, now I am going to find the events bound to ‘a’ element. However when I execute following code I get undefined.


$('a').data('events')); //undefined

Why is that. In the previous section I showed that all the events bound to an element are stored as the data attribute of that element. Well, live is different. live events are not bound to the element directly. They are bound to the top level ‘document’. I can verify this by trying out this code

jQuery.data(document, 'events').live; //Object

How does live method work

live methods do not set anything on elements directly. All the event handlers are set at the document level. It means that in order for live methods to work, event bubbling is required. If you don’t know what event bubbling is then read here . It also means that event should not be stopped while it is propagating to document. If event propagation is stopped then event handlers bound at the document level will never know about that event and live method will fail.


The strategy to let someone else deal with the event is called ‘event delegation’. You can read more about event delegation here .

When live method is called then a binding is done at the document level. Loosely translated this is what is basically happening.

$(document).bind('click', function(event){
  var $target = $(event.target);
  if($target.is('p')){
    console.log('p was clicked');      
  }
});

As you can see when a click on ‘p’ bubbles all the way to the top then that event is captured by document and necessary action is taken if the target element matches.


It is clear that if the click event is stopped before it reaches document then live method will not work. I will show you an example.

<div id='parent'> 
 Languages 
 <p>Java</p> 
 <p>Javascript</p> 
</div>

$('p').live('click',function(e){ 
  console.log('p was clicked'); 
});

If I click on ‘Java’ or ‘Javascript’ I get a message on console. live is working great. Now I’ll stop the event propagation when event reaches to div.

$('p').live('click',function(e){ 
  console.log('p was clicked'); 
});

$('#parent').click(function(e){ 
  console.log('stopping propagation'); 
  e.stopPropagation();
});

Now you will notice that live is no more working.

live does not work when event bubbling is not supported


In the previous section I showed that when event does not bubble up to document then live fails. It means that all the events that do not bubble will not work. Which means that events like blur, focus, mouseenter, mouseleave, change and submit which do bubble in IE will not work in IE. However note that these events will continue to work in Firefox.

<select id='lab1a' name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>

<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div id='lab1b' style='color:red;'></div>

$("#lab1a").live('change',function () {
  var str = "";
  $("select option:selected").each(function () {
    str += $(this).text() + " ";
  });
  $("#lab1b").text(str);
});

Above code will work in firefox but it will not work in IE.

Here is an example of an event that does not work in IE: onchange event.

DOM models suggest that onchange event should bubble . However msdn documentation clearly says that onchange event does not bubble .


make all the live method problems go away

To recap live method will not work in following cases:

  • live method works on event propagation, if an event is stopped while it is bubbling then live will not work.
  • IE does not support bubbling for certain events. live method on those events will not work in IE.

There is a way to get around to both the problems.

Brandon Aaron developed livequery plugin which was finally merged into jQuery as live method. livequery plugin solves both the problems listed above and the code works in IE too.


First step is to include this plugin

<script src="http://github.com/brandonaaron/livequery/raw/master/jquery.livequery.js" type="text/javascript"></script>         

Now try this code.

$('p').livequery('click',function(e){ 
  alert('p was clicked'); 
}); 

$('#parent').click(function(e){ 
  alert('stopping progpagation'); 
  e.stopPropagation(); 
});

$("#lab1a").livequery('change',function () { 
  var str = ""; 
  $("select option:selected").each(function () { 
    str += $(this).text() + " "; 
  }); 
  $("#lab1b").text(str); 
});

<select id='lab1a' name="sweets" multiple="multiple">
  <option>Chocolate</option>

  <option selected="selected">Candy</option>
  <option>Taffy</option>
  <option selected="selected">Caramel</option>
  <option>Fudge</option>

  <option>Cookie</option>
</select>
<div id='lab1b' style='color:red;'></div>
<div id='parent'> 
 Languages 
 <p>Java</p> 
 <p>Javascript</p> 

</div>

If I click on ‘Java’ or ‘Javascript’ I will get proper response even though event propagation is being stopped. Also even though change event does not bubble in IE, above code works in IE.

livequery works because livequery ,unlike live, method does not do binding at the document level. livequery does binding at the element level. You can find that out by running following code.

$('p').data('events');

Above code will produce result if I am using livequery. Above code will not produce any result if I am using live method.


The key piece of code in the plugin that makes all this work is

// Create a timeout to check the queue and actually run the Live Queries
$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);

Every 20 milliseconds livequery runs all the bindings defined in livequery and then binds the matched element with the event.

By understanding the internals of how live and livequery are implemented, now you can choose to use livequery in certain cases where live will not work. Also it helps to understand how live actually works.

Live method finds elements and then throws it away. Not very efficient.

A typical use of live method is something like this.

$('p').live('click',function(e){ 
  console.log('p was clicked'); 
});

As it has already been discussed a live method registers events at document level.


However when $(‘p’).live(…) is evaluated then jQuery first goes and finds all the ‘p’ elements. And then what does it do with those elements. Nothing. That’s right. jQuery throws away all those ‘p’ elements which were just found without using them. What a waste.

If your application has a lot of live methods and this might slow down the performance of the application.


A better solution would have been to design an API like this one:

$.live('p', 'click', function(){..});

jQuery is flexible and I can create my own live method but it will add to the confusion. Another solution would be to make the call to live method without first finding all those ‘p’ element. Here is how it can be done.

var myDocument = $(document);
myDocument.selector = 'p';
myDocument.live('click', function(){
  console.log('p was clicked');
});

In the above case no element will be selected only to be thrown away. This is much better.


Seeing is believing

In the previous section, I showed how live method can be made to work without first selecting the elements. However a friend of mine asked me if I could conclusively prove that in the real live method a find is actually done. And in my solution a find call is not done.

Here I am showing you the overriding find method. In this method I am overriding the original find method. I will put a log message before passing the find method to the original method.

(function() {
  var originalFindMethod = jQuery.fn.find;
  jQuery.fn.find = function() {
    console.log('find was called');
    originalFindMethod.apply(this, arguments);
  };
})();

$(document).ready(function() {
  $('p').live('click', function() {
    console.log('p was clicked');
  });
});

In the above case you will get message on firebug console confirming that find is indeed invoked when live method is called.

Here is revised version of live. Try this one.

(function() {
  var originalFindMethod = jQuery.fn.find;
  jQuery.fn.find = function() {
    console.log('find was called');
    originalFindMethod.apply(this, arguments);
  };
})();

$(document).ready(function() {
  var myDocument = $(document);
  myDocument.selector = 'p';
  myDocument.live('click', function() {
    console.log('p was clicked');
  });
});

Above version does not print ‘find was called’.


http://www.neeraj.name/2009/10/14/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery.html

Drupal 7 database plans

http://www.garfieldtech.com/blog/drupal-7-database-plans

Understanding Scope and Binding in JavaScript

http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding

http://stackoverflow.com/questions/1960541/event-binding-jquery-vs-javascript

http://www.neeraj.name/2009/10/14/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery.html

http://www.bennadel.com/blog/1518-jQuery-metaData-Plugin-Leverages-data-Method-jQuery-Plugin-Example-.htm

http://www.bennadel.com/blog/1520-Binding-Events-To-Non-DOM-Objects-With-jQuery.htm

http://api.jquery.com/category/events/

http://api.jquery.com/bind/

邁向成功的 8 個秘密 ( by Richard St. John )

邁向成功的 8 個秘密 ( by Richard St. John )

今天收到朋友分享的一則影片,一則短短三分半的英文演說,淺顯易懂的成功觀念,價值 4,000 美金,值得一看。底下附上演說原文(含保哥的摘要註解),讓有興趣的人研讀,訓練英文閱讀能力與聽力。

[Video] Richard St. John's 8 secrets of success


若想直接看有中文字幕的版本,可以點選這個連結

This is really a two-hour presentation I give to high school students, cut down to three minutes. And it all started one day on a plane, on my way to TED, seven years ago. And in the seat next to me was a high school student, a teenager, and she came from a really poor family. And she wanted to make something of her life. And she asked me a simple little question: she said, what leads to success? And I felt really badly, because I couldn't give her a good answer. So I get off the plane and I come to TED. And I think, geez, I'm in a middle of a room of successful people. So why don't I ask them what helped them succeed and pass it on to kids? So here we are, 7 years, 500 interviews later and I'm going to tell you what really leads to success.

The first thing is Passion. ( 擁有熱情 )
Freeman Thomas says, "I'm driven by my passion". TED-sters do it for love, they don't do it for money. Carol Colleta says, "I would pay someone to do what I do". The interesting thing is, if you do it for love, the money comes anyway.

Work. ( 認真工作 )
Rupert Murdoch said to me, "It's all hard work. Nothing comes easily. But I have a lot of fun." Did he say fun?! Rupert? Yes, TED-sters do have fun working, and they work hard. I figure they're not workaholics (工作狂), they're workafrolics (工作玩家). [註: 演說者自創的字,是 work 與 frolic 的組合]

Good. ( 擅長某些事 or 擁有專長 )
Alex Garden says, "To be successful, put your nose down in something and get damn good at it." There's no magic; it's practice, practice, practice.

And focus. ( 專注於一件事 )
Norma Jewison said to me, "I think it all has to do with focusing yourself on one thing".

And push. ( 讓自己不斷進步 )
David Gallo says, "Push yourself. Physically, mentally, you gotta push, push, push." You've got to push through shyness and self-doubt. Goldie Hawn says, "I always had self-doubts. I wasn't good enough, I wasn't smart enough, I didn't think I'd make it." It's not always easy to push yourself and that's why they invented mothers. [笑..] Frank Geary said to me, "My mother pushed me".

Serve! ( 為他人提供服務 )
Sherwin Nulan says, "It was a privilege to serve as a doctor. "Now a lot of kids tell me they want to be millionaires. And the first thing I say to them is, "OK, but you can't serve yourself. You got to serve others something of value. Because that's the way people really get rich".

Ideas. ( 富有創意的想法 )
Bill Gates says, "I had an idea: founding the first micro-computer software company." I'd say it was a pretty good idea. And there's no magic to creativity and coming up with ideas. It's just doing some very simple things. And I give lots of evidence.
  • Listen (聆聽)
  • Observe (觀察)
  • Be Curious (好奇心)
  • Ask Questions (時常發問)
  • Problem Solve (解決問題)
  • Make Connections (多多交流)

Persist. ( 無條件的堅持下去 )
Joe Kraus says, "Persistence is the number one reason for our success". You got to persist through failure (遭遇失敗), you got to persist through CRAP, which of course means: Criticism (被批評), Rejection (被拒絕), Assholes (被小人中傷) and Pressure (與壓力共處). [笑..]

So, the big end. The answer to this question is simple. Pay $4,000 and come to TED! Or failing that, do the 8 things -- and trust me, these are the big 8 things that lead to success.
Thank you TED-sters for all your interviews!

這場演說讓我覺得最陌生的的單字不外乎是 Workafrolics 這個字了,這個字是演講者 Richard St. John 演說中自創的詞彙,是 work (工作) 與 frolic (歡樂) 的組合字,有「樂在工作」的意思,但我覺得翻譯成「工作玩家」還比較貼切一些。

有鑑於我時常被別人說成是個工作狂(workaholics),現在終於有個更貼切的名詞了,就是工作玩家(Workafrolics),下次不要再說我是「工作狂」了。

雖然我長時間工作,倒不如說我長時間在玩樂,因為心情上是差很多的,而且也比較沒壓力,我在查詢 Workafrolics 時看到一篇 Workafrolics work harder but live longer 文章,說 Workafrolics 的人比較長壽,而且新科學人(New Scientist)雜誌還有專文與數據證明這件事,不過要觀看全文必須買雜誌才看的到。

相關連結
Richard St. John's 8 secrets of success
Richard St. John's 8 secrets of success ( 有中文字幕的版本 )
TED: Ideas worth spreading
Passion - A Key Success Factor And Necessary Business Strategy Ingredient.
Workafrolics work harder but live longer
工作玩家努力工作,但卻活的更長命 [有科學數據證明]

lots of great video presentation

ted.com

Tuesday, December 14, 2010

Four Ways Javascript Binding Event Listeners

There is several ways in how to bind an event in Javascript. As far as I know four ways exist on behalf of binding a Javascript event. Here brief description of each way
1. Through inline HTML Code

The Javascript event declared inline in HTML code, for example:
<input type=”button” value=”Alert Message” onclick=”showAlert()” />
Then showAlert() is a Javascript function that merely show an alert message:
function showAlert()
{
      window.alert("Hello, World!!!");
}
This inline event binding works for all browsers.
2. Traditional Binding

I think this way is more elegance than the first one, but before we can do this we must get the desired element. We can use two useful methods of document object to get the element we want, there is getElementById() and getElementsByTagName(). Both method receive one string parameter which show the ID of an element (for getElementById()) or elements name (for getElementsByTagName()). Please aware that the result of getElementsByTagName() is always array of element.

Suppose that we have the following page:

    <html>
       <head>
          <title>Events Binding</title>
          <script lang="javascript" type="text/javascript">
          var txtContent;
    
          window.onload = function()
          {
             txtContent = document.getElementById("txtContent");
             txtContent.onfocus = txtFocusHandler;
             txtContent.onblur = txtBlurHandler;
    
             var all = document.getElementsByTagName("li");
             for (var i=0;i<all.length;i++) {
                all[i].onmouseover = liMouseOverHandler;
                all[i].onmouseout = liMouseOutHandler;
                all[i].onclick = liClickHandler;
            }
        };
    
       function txtFocusHandler(e)
       {
          e= e||window.event;
          var trgSrc = e.target||e.srcElement;
          trgSrc.style.backgroundColor = "gainsboro";
       }
    
       function txtBlurHandler(e)
       {
          this.style.backgroundColor = "white";
       }
    
       function liMouseOverHandler()
       {
          this.style.backgroundColor = "#EFEFEF";
       }
    
       function liMouseOutHandler()
       {
          this.style.backgroundColor = "white";
       }
    
       function liClickHandler(e)
       {
          e = e||window.event;
          var liElm = e.target||e.srcElement;
          var text = liElm.firstChild.nodeValue;
    
          txtContent.value = text;
       }
       </script>
    </head>
    <body>
       <form id="frm">
          Content: <input type="text" id="txtContent" width="200px" />
          (Hover the elements below and click one of it)
          <p>
          <ul>
             <li>Martial Arts, Swimming, Football, Basketball, Badminton</li>
             <li>Work, Office, Vacation, Holiday</li>
             <li>Computer, Internet, Blogging</li>
          </ul>
       </form>
    </body>
    </html>

For simplicity I mix the HTML and Javascript code (although it maybe looks messy). The above code will produce a TextBox element and three <li> element. Hover the <li> element and click it will copy paste the nodeValue of <li> element to TextBox.
Hover
Traditional binding works well for all browser.
3. W3C Binding

W3C binding works on browsers that comply with W3C standard. We need to remember one important method when attach event using W3C binding: addEventListener(). This method receives three parameters, first parameter is event name (such as: click, load, mouseout, etc.), second parameter is function that handle it, and third parameter is boolean values (true for event capturing or false for event bubbling).

Look at the following simple example on how to use addEventListener():
    <html>
       <head>
          <title>Test W3 Binding</title>
          <script lang="javascript" type="text/javascript">
          window.onload = function()
          {
             var elJ = document.getElementsByTagName("li");
             for (var i=0;i<elJ.length;i++) {
             elJ[i].addEventListener('mouseover',liMouseOver,false);
             elJ[i].addEventListener('mouseout',liMouseOut,false);
          }
       };
    
       function liMouseOver()
       {
          this.style.backgroundColor = "gainsboro";
       }
    
       function liMouseOut()
       {
          this.style.backgroundColor = "white";
       }
       </script>
    </head>
    <body>
       <ul>
          <li>First Element</li>
          <li>Second Element</li>
          <li>Third Element</li>
       </ul>
    </body>
    </html>

Run the code in W3C compliant browsers and hover the mouse cursor above an <li> element and you will see the background color of <li> element changed.
4. IE Binding

As usual, Internet Explorer (IE) has its own way on binding an event. Remember this method when binding an event using IE binding: attachEvent(). This methods receives two parameters, first parameter is event precede with ‘on’ word (such as: onclick, onload, onmouseout), the second parameter is function that handle it.

If we want do the same thing (hover and out mouse effect) in IE way we can do with this code:
    <html>
      <head>
        <title>Test IE Binding</title>
        <script lang="javascript" type="text/javascript">
        window.onload = function()
        {
          var allLi = document.getElementsByTagName("li");
    
          for (var i=0;i<allLi.length;i++) {
            allLi[i].attachEvent('onmouseover',liMouseOver);
            allLi[i].attachEvent('onmouseout',liMouseOut);
          }
        };
    
        function liMouseOver()
        {
          var e = window.event;
          var elm = e.srcElement;
          elm.style.backgroundColor = "gainsboro";
        }
    
        function liMouseOut()
        {
          var e = window.event;
          var elm = e.srcElement;
          elm.style.backgroundColor = "white";
        }
        </script>
      </head>
      <body>
        <ul>
          <li>First Element</li>
          <li>Second Element</li>
          <li>Third Element</li>
        </ul>
      </body>
    </html>

We must notice that this keyword inside a event handler function in IE point to window object not the current element, so we need a little more effort to achieve our goal. It something looks like this:



function liMouseOver()

{

var e = window.event;

var elm = e.srcElement;

elm.style.backgroundColor = "gainsboro";

}

Run the code in the browser and we should get the same result as before.

http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/

use Vim like an IDE

bufferexplorer
selectbuf
FuzzyFinder
minibufexpl

taglist

gtags (Integrates GNU GLOBAL source code tag system with VIM)

SourceCodeObedinece

0scan

NerdTree

Project

ctags, cscope

http://stackoverflow.com/questions/1457540/how-to-navigate-in-large-project-in-vim

http://vim.wikia.com/wiki/Use_Vim_like_an_IDE

Top 100 Best Software Engineering Books, Ever

This article contains a top 100 of the best software engineering books.

I have created this list using four different criteria:

  1. number of Amazon reviews;
  2. average Amazon rating;
  3. number of Google hits;
  4. Jolt awards.

Please refer to the second part of this article to find out how the calculations were performed.


The Top 100 List



#
Author(s) / Title
Year

ISBN13

Jolt

sum

avg

1
Steve McConnellCode Complete: A Practical Handbook of Software Construction (2nd Edition)
2004

978-0735619678

**

243

4.72

2
Elisabeth Freeman, etc.Head First Design Patterns
2004

978-0596007126

**

237

4.63

3
Steve McConnellRapid Development
2003

978-0072850604

**

112

4.74

4
Erich GammaDesign Patterns: Elements of Reusable Object-Oriented Software
1994

978-0201633610

*

244

4.55

5
Bruce SchneierApplied Cryptography: Protocols, Algorithms, and Source Code (2nd Edition)
1995

978-0471128458

*

99

4.61

6
Robert C. MartinAgile Software Development: Principles, Patterns and Practices
2002

978-0135974445

**

31

4.77

7
Joel SpolskyJoel on Software
2004

978-1590593899

*

48

4.71

8
Tom DeMarco, Timothy ListerPeopleware: Productive Projects and Teams (2nd Edition)
1999

978-0932633439


76

4.79

9
Frederick P. BrooksThe Mythical Man-Month, Anniversary Edition (2nd Edition)
1995

978-0201835953


124

4.54

10
Martin FowlerRefactoring: Improving the Design of Existing Code
1999

978-0201485677


138

4.54

11
Mike CohnAgile Estimating and Planning
2005

978-0131479418


43

4.74

12
Alistair CockburnWriting Effective Use Cases
2000

978-0201702255

*

45

4.62

13
Bertrand MeyerObject-Oriented Software Construction (2nd Edition)
2000

978-0136291558

**

43

4.47

14
Steve McConnellSoftware Estimation: Demystifying the Black Art
2006

978-0735605350

*

31

4.74

15
Mike CohnUser Stories Applied: For Agile Software Development
2004

978-0321205681


37

4.76

16
Donald E. KnuthThe Art of Computer Programming, Volumes 1-3 Boxed Set (2nd Edition)
1998

978-0201485417


109

4.39

17
Martin FowlerPatterns of Enterprise Application Architecture
2002

978-0321127426

*

54

4.46

18
Jeffrey FriedlMastering Regular Expressions
2006

978-0596528126


122

4.48

19
Andrew Hunt, David ThomasThe Pragmatic Programmer: From Journeyman to Master
1999

978-0201616224


127

4.42

20
Karl E. WiegersSoftware Requirements (2nd Edition)
2003

978-0735618794

*

44

4.48

21
Craig LarmanApplying UML and Patterns (3rd Edition)
2004

978-0131489066


178

4.37

22
Alistair CockburnAgile Software Development: The Cooperative Game (2nd Edition)
2006

978-0321482754

**

28

4.46

23
Gary McGrawSoftware Security: Building Security In
2006

978-0321356703


19

4.95

24
Gregor Hohpe, Bobby WoolfEnterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions
2003

978-0321200686


31

4.74

25
Tom DeMarcoThe Deadline: A Novel About Project Management
1997

978-0932633392

*

52

4.42

26
Craig LarmanAgile and Iterative Development: A Manager's Guide
2003

978-0131111554


46

4.52

27
Eric A. Marks, Michael BellService-Oriented Architecture: A Planning and Implementation Guide for Business and Technology
2006

978-0471768944


33

4.45

28
Thomas H. Cormen, etc.Introduction to Algorithms, Second Edition
2001

978-0070131514


167

4.08

29
Thomas ErlService-Oriented Architecture: A Field Guide to Integrating XML and Web Services
2004

978-0131428980


32

4.59

30
Martin FowlerUML Distilled: A Brief Guide to the Standard Object Modeling Language (3rd Edition)
2003

978-0321193681

*

139

3.95

31
Kent BeckExtreme Programming Explained: Embrace Change (2nd Edition)
2004

978-0321278654

*

126

3.98

32
Alan Shalloway, James TrottDesign Patterns Explained: A New Perspective on Object-Oriented Design (2nd Edition)
2004

978-0321247148


109

4.33

33
Grady Booch, etc.Object-Oriented Analysis and Design with Applications (3rd Edition)
2007

978-0201895513

**

37

3.95

34
Jim HighsmithAgile Project Management: Creating Innovative Products
2004

978-0321219770


20

4.80

35
Scott BerkunMaking Things Happen: Mastering Project Management
2008

978-0596517717


55

4.53

36
Jon BentleyProgramming Pearls (2nd Edition)
1999

978-0201657883


28

4.50

37
Paul Duvall, etc.Continuous Integration: Improving Software Quality and Reducing Risk
2007

978-0321336385

**

13

4.85

38
Andrew Stellman, Jennifer GreeneApplied Software Project Management
2005

978-0596009489


15

5.00

39
Clemens SzyperskiComponent Software: Beyond Object-Oriented Programming
1997

978-0201178883

**

13

4.69

40
Arthur J. RielObject-Oriented Design Heuristics
1996

978-0201633856


27

4.78

41
Thomas ErlSOA Principles of Service Design
2007

978-0132344821


24

4.58

42
Mary Poppendieck, Tom PoppendieckLean Software Development: An Agile Toolkit
2003

978-0321150783

*

35

4.57

43
Ken SchwaberAgile Project Management with Scrum
2004

978-0735619937


30

4.47

44
Ken Schwaber, Mike BeedleAgile Software Development with Scrum
2001

978-0130676344


35

4.51

45
Joshua KerievskyRefactoring to Patterns
2004

978-0321213358

*

42

4.10

46
Alistair CockburnCrystal Clear: A Human-Powered Methodology for Small Teams
2004

978-0201699470


12

4.75

47
Steve McConnellSoftware Project Survival Guide
1997

978-1572316218


63

4.33

48
Tom DeMarco, Timothy ListerWaltzing With Bears: Managing Risk on Software Projects
2003

978-0932633606

**

23

4.52

49
Venkat Subramaniam, Andy HuntPractices of an Agile Developer: Working in the Real World
2005

978-0974514086

*

26

4.58

50
Kathy SchwalbeInformation Technology Project Management
2007

978-1423901457


27

4.63

51
Randall HydeWrite Great Code: Volume 1: Understanding the Machine
2004

978-1593270032


17

4.82

52
Scott RosenbergDreaming in Code: Two Dozen Programmers, Three Years, 4,732 Bugs, and One Quest for Transcendent Software
2007

978-1400082476


59

3.78

53
Cem Kaner, etc.Lessons Learned in Software Testing
2001

978-0471081128


35

4.54

54
Andy Oram, Greg WilsonBeautiful Code: Leading Programmers Explain How They Think
2007

978-0596510046

**

27

3.81

55
Luke HohmannBeyond Software Architecture: Creating and Sustaining Winning Solutions
2003

978-0201775945


27

4.56

56
Grady BoochUnified Modeling Language User Guide, The (2nd Edition)
2005

978-0321267979


81

3.30

57
Karl FogelProducing Open Source Software: How to Run a Successful Free Software Project
2005

978-0596007591

*

13

4.85

58
Michael FeathersWorking Effectively with Legacy Code
2004

978-0131177055


21

4.86

59
Kent BeckTest Driven Development: By Example
2002

978-0321146533

*

27

4.11

60
Per Kroll, Philippe KruchtenThe Rational Unified Process Made Easy: A Practitioner's Guide to the RUP
2003

978-0321166098


14

4.79

61
Thomas ErlService-Oriented Architecture: Concepts, Technology, and Design
2005

978-0131858589


60

4.15

62
Cem Kaner, etc.Testing Computer Software (2nd Edition)
1999

978-0471358466


35

4.34

63
Frank Buschmann, etc.Pattern-Oriented Software Architecture Volume 1: A System of Patterns
1996

978-0471958697

*

16

4.50

64
Harold Abelson, Gerald Jay SussmanStructure and Interpretation of Computer Programs - 2nd Edition
1996

978-0262011532


157

3.44

65
Dan PiloneUML 2.0 in a Nutshell
2005

978-0596007959


14

4.57

66
Brett D. McLaughlin, etc.Head First Object-Oriented Analysis and Design
2006

978-0596008673

**

35

3.77

67
Johanna RothmanManage It!: Your Guide to Modern, Pragmatic Project Management
2007

978-0978739249

*

7

5.00

68
James Shore, Shane WardenThe Art of Agile Development
2007

978-0596527679


11

4.64

69
Brian W. Kernighan, Rob PikeThe Practice of Programming
1999

978-0201615869


49

3.96

70
Ron Jeffries, etc.Extreme Programming Installed
2000

978-0201708424


31

4.35

71
Scott W. Ambler, Pramodkumar J. SadalageRefactoring Databases: Evolutionary Database Design
2006

978-0321293534

*

19

4.42

72
Jared Richardson, William GwaltneyShip it! A Practical Guide to Successful Software Projects
2005

978-0974514048


24

4.46

73
Greg Hoglund, Gary McGrawExploiting Software: How to Break Code
2004

978-0201786958


27

4.41

74
Michael NygardRelease It!: Design and Deploy Production-Ready Software
2007

978-0978739218

*

17

4.47

75
Edward YourdonDeath March (2nd Edition)
2003

978-0131436350


68

3.82

76
Stephen P. Berczuk, etc.Software Configuration Management Patterns: Effective Teamwork, Practical Integration
2003

978-0201741179


23

4.57

77
Elfriede Dustin, etc.Automated Software Testing: Introduction, Management, and Performance
1999

978-0201432879


40

4.55

78
Donald C. Gause, Gerald M. WeinbergExploring Requirements: Quality Before Design
1989

978-0932633132


25

4.72

79
Tom GilbCompetitive Engineering
2005

978-0750665070


13

4.92

80
David J. AgansDebugging
2006

978-0814474570


15

4.80

81
Eldad EilamReversing: Secrets of Reverse Engineering
2005

978-0764574818


14

4.64

82
Robert L. GlassFacts and Fallacies of Software Engineering
2002

978-0321117427


23

4.30

83
Martin FowlerAnalysis Patterns: Reusable Object Models
1996

978-0201895421


15

4.40

84
Matt WeisfeldThe Object-Oriented Thought Process (2nd Edition)
2003

978-0672326110


42

4.07

85
John M. VlissidesPattern Hatching: Design Patterns Applied
1998

978-0201432930


25

4.68

86
Johanna RothmanBehind Closed Doors: Secrets of Great Management
2005

978-0976694021


24

4.38

87
Robert K. WysockiEffective Project Management: Traditional, Adaptive, Extreme
2006

978-0470042618


26

4.35

88
Ellen GottesdienerRequirements by Collaboration: Workshops for Defining Needs
2002

978-0201786064


14

5.00

89
Eric EvansDomain-Driven Design: Tackling Complexity in the Heart of Software
2003

978-0321125217


42

4.24

90
Nick Rozanski, Eóin WoodsSoftware Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives
2005

978-0321112293


12

5.00

91
Peter Rob, Carlos CoronelDatabase Systems: Design, Implementation, and Management (8th Edition)
2006

978-1418835934


27

3.37

92
Robert Orfali, etc.Client/Server Survival Guide (3rd Edition)
1999

978-0471316152


43

4.40

93
Douglas Schmidt, etc.Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects
2000

978-0471606956


21

4.33

94
Michael LoppManaging Humans: Biting and Humorous Tales of a Software Engineering Manager
2007

978-1590598443


21

4.29

95
Paul GrahamHackers and Painters: Big Ideas from the Computer Age
2004

978-0596006624


55

4.07

96
Philippe KruchtenThe Rational Unified Process: An Introduction (3rd Edition)
2003

978-0321197702


34

3.91

97
Joel SpolskyThe Best Software Writing I: Selected and Introduced by Joel Spolsky
2005

978-1590595008


22

4.14

98
James O. Coplien, Neil B. HarrisonOrganizational Patterns of Agile Software Development
2004

978-0131467408


13

5.00

99
Esther Derby, etc.Agile Retrospectives: Making Good Teams Great
2006

978-0977616640


17

4.53

100
Henry S. WarrenHacker's Delight
2002

978-0201914658


13

5.00


Legend


Year

= Year of Publication

Jolt **

= Jolt Winner

Jolt *

= Jolt Productivity Award

sum

= Number of reviews on Amazon

avg

= Average rating on Amazon

Scope of this List

For this Top 100 list I have included only books covering subjects found in the Software Engineering Body of Knowledge (SWEBOK). This means that I have left out books with main topics such as web design, computer science, business management and system administration. The main reason for this is that I had to limit the scope (or I would never be able to finish it).

I also excluded all books that dealt with specific technologies, such as Java, .NET, Ruby and PHP. I was only interested in the potentially timeless software engineering classics. In my opinion, technology books do not fall into that category. I did include books on project management (as project management is one of the competences in SWEBOK) but only when those books explicitly dealt with managing software development. (That's why there is no generic PMP-related material on the list.)


Finding the Books

To find all these potentially timeless classics, I checked the best-selling books in these five Amazon categories:

Books > Computers & Internet > Computer Science > Software Engineering
Books > Computers & Internet > Computer Science > System Analysis & Design
Books > Computers & Internet > Programming > Algorithms
Books > Computers & Internet > Programming > Software Design, Testing & Engineering
Books > Computers & Internet > Project Management

After I found all best-selling software engineering books, I subsequently found many other books through the "Customers Who Bought This Item Also Bought" cross-reference feature. And that's how I finally ended up with a list of 250 books.

Note: in case of multiple editions of the same book, only the most recent edition is listed on the chart, though reviews and ratings were combined for all available editions.


Doing the Calculations

When it was time to do the calculations, I checked the number of customer reviews on Amazon, and I ranked the books according to these numbers (= a measure of quantity). I also calculated the average Amazon ratings, and I ranked the books according to these ratings (= a measure of quality). I then checked the number of Google hits for each of the books, and I ranked them accordingly (= a measure of popularity). Finally, I took the three rankings, added extra points for all winners of Jolt awards, and then re-calculated it into a final ranking. This resulted in the list you now have before you.

Note: this little project was performed in the first week of June, 2008. Current Amazon reviews and ratings might have changed since then.

I admit that the system I used has no scientific basis. Nevertheless, I think the results are quite interesting, and I'm sure the list can be of great help if you want to broaden your knowledge of the field of software engineering, in all its exciting dimensions. I suggest you start with number 1, and then slowly work your way down. It shouldn't take you more than a couple of years…


Comments

Let's walk down the list and see what entries are worth pointing out...

First of all, it is obvious that Steve McConnell is the biggest hero among software engineers. (Well, at least among the reading part of the software engineering population...) Steve has no less than four entries on the list: Rapid Development (#3), Software Estimation (#14), Software Project Survival Guide (#47), and of course the Best Software Engineering Book Ever... Code Complete (#1). Congratulations to Steve for this stellar achievement!
There's only one other author with four entries on the Top 100 list. It's Martin Fowler, with Refactoring (#10), Patterns of Enterprise Application Architecture (#17), UML Distilled (#30) and Analysis Patterns (#83). And next in line is Alistair Cockburn, with three titles: Writing Effective Use Cases (#12), Agile Software Development (#22) and Crystal Clear (#46). It seems you cannot go wrong reading just about any of the books these guys are delivering!
After creating the top 100 list, one thing that immediately grabbed my attention was the #2 position for Head First Design Patterns, by Elisabeth Freeman, etc. The book ended two notches higher than the original (and more famous) Design Patterns (#4) by the Gang of Four (Erick Gamma, etc.) Several people had already informed me that Freeman's book is actually more readable than the classic one by the GoF. And now the Top 100 list seems to indicate that this is indeed the general public opinion. Freeman's book has a higher average rating on Amazon, and it was a Jolt Winner on top of that.
The best agile software development book is Agile Software Development: Principles, Patterns and Practices (#6), by Robert C. Martin. There are no less than 20 books on agile software development on the Top 100 list. It's obvious that no other topic has been so hot as the "agile" meme in the last decennium.
I would like to mention that I had a tough time deciding whether or not Mastering Regular Expressions (#18), by Jeffrey Friedl, actually belonged on the Top 100 list. I told you before that the list is about software engineering topics, and not about specific technologies. However, the book simply kept popping up in numerous searches and references. And I considered that regular expressions are actually not a technology but an (interpreted or compiled) technique or notation, just like UML, and useful for any software engineer, regardless of the type of application. So I relented, and Jeffrey got his #18 slot on the list.
For books with different editions I simply added the reviews and ratings for each edition, and used the last edition as the only Top 100 entry. Scott Berkun, the author of Making Things Happen (#35) was lucky that I knew that the previous edition of his book had a different name: The Art of Project Management. He wouldn't have ended so high if I had not been able to catch that essential piece of information.
One book that deserves a special treatment is Dreaming in Code (#52), by Scott Rosenberg. It was released in 2007 (first edition) and it has already scored Amazon 59 reviews.
And another newcomer that's worth point out is Manage It! (#67), by Johanna Rothman. Johanna's relatively new book still had only seven reviews on Amazon (at the time of calculation), but she scored a perfect 5.0 rating, and she added a Jolt award on top of that! Her book is the highest on the list with such a small crowd of enthusiastic supporters, and an almost perfect score for quality.
Speaking of Jolt awards, the top 7 books on the list all have received such an award. The highest entry on the list that did not receive a Jolt award is Peopleware (#8), by Tom DeMarco and Timothy Lister. The book is one of the highest rated books ever, and I'm sure that the Jolt jury regrets not having awarded Tom and Tim for their little (but visionary) masterpiece.
At the other side of the scale we find The Unified Modeling Language User Guide (#56), by Grady Booch. Of all the books on the Top 100 list, this one has the lowest average Amazon rating (3.30). But it is compensated by a large number of reviews (81) and a huge number of Google hits. It's a nice example of a book having popularity winning over quality.
Last of all, I think there's no better way of ending this post than including a reference to Hacker's Delight (#100), by Henry S. Warren. It seems like a nice book to close the list at the bottom. I had never heard of the book myself, but seeing that it has a perfect Amazon rating of 5.0 I'm sure that it's worth checking out.
Happy reading!
p.s. If you want to receive a nicely formatted Word-document of the list, you may email the author about it!
This article was originally published as a blog post at http://www.noop.nl/. The original post will not be kept up-to-date. All future updates will be made in this Knol.

http://knol.google.com/k/jurgen-appelo/top-100-best-software-engineering-books#