Search

12/28/2006

中永和之詩

捷運有幾個站還是換個站名比較好

永和有永和路,中和也有中和路,中和的中和路有接永和的中和路,永和的永和路沒接中和的永和路;永和的中和路有接永和的永和路,中和的永和路沒接中和的中和路。

永和有中正路,中和也有中正路,永和的中正路用景平路接中和的中正路;永和有中山路,中和也有中山路,永和的中山路就直接接上中和的中山路,永和的中正路,接上了永和的中山路,中和的中正路,卻不接中和的中山路

中正橋下來不是中正路,但永和有中正路;秀朗橋下來也不是秀朗路,但永和也有秀朗路。永福橋下來不是永福路,永和沒有永福路;福和橋下來也不是福和路,但福和路接的卻是永福橋

11/18/2006

Using DOM Scripting to Plug the Holes in CSS

Using DOM Scripting to Plug the Holes in CSS

HTML: Structure
CSS: Presentation
DOM Scripting: Behaviour


document.getElementsByClassName = function(name) {
var results = new Array();
var elems = document.getElementsByTagName("*");
for (var i=0; i<elems.length; i++) {
if (elems[i].className.indexOf(name) != -1) {
results[results.length] = elems[i];
}
}
return results;
};

function stripeLists() {
var lists = document.getElementsByTagName("ol");
for (var i=0; i<lists.length; i++) {
if (lists[i].className.match("striped")) {
var items = lists[i].getElementsByTagName("li");
for (var j=0; j<items.length; j=j+2) {
addClass(items[j],"odd");
}
}
}
}

tr:nth-child(2n+1) 
/* represents every odd row of an HTML table */
tr:nth-child(odd) /* same */
tr:nth-child(2n) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */

本週閱讀2006.11.08-2006.11.15

“书记员”──穷人的TextMate?
免费的 Windows Vista 桌面背景
What causes the noise when you crack a joint?

11/13/2006

Java Is Free

Java Is Free

Unmodified GPL2 for our SE, ME, and EE code. GPL2 + Classpath exception for the SE libraries. Javac and HotSpot and JavaHelp code drops today. The libraries to follow, with pain expected fighting through the encumbrances. Governance TBD, but external committers are a design goal. No short-term changes in the TCK or JCP. There are a ton of presentations and an (excellent) FAQ and so on, all to show up at sun.com/opensource/java sometime in the next few hours. I wanted to add a couple of remarks on areas that stuff doesn’t highlight.

Dojo Charting Engine Released

Dojo Charting Engine Released

11/08/2006

Comet: Low Latency Data for the Browser

比較有印象的例子就是整合在Gamil裡面的Gtalk,看起來很不錯阿。

本週閱讀2006.11.08-2006.11.15

Scott Meyers - The Most Important C++

駭客與畫家 Hackers & Painters Big Ideas from the Computer Age

  • 作者的Paul Graham的home page
  • Paul Graham - Wikipedia, the free encyclopedia
  • 作者的著作: ANSI Common Lisp
  • Ch06. How to Make Wealth
  • Ch11. The Hundred-Year Language - 駭客與畫家第11章 - 百年語言。
  • Ch13. Revenge of the nerds - 駭客與畫家第13章 - 書呆的復仇。
    "We were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp."
    - Guy Steele, co-author of the Java spec

  • Functional VS Imperative (未完)
  • 说说动态语言
  • 动态语言,别再说不
  • 漫談 lisp、scheme、ML
    嘻嘻,有一個LISP的笑話:某人自稱hack進了NASA的AI Lab,偷盜了不少程式。
    為了證明,它列出某個LISP程式的最後一頁:
    ......))))))))))))))))))))))))))))))))
    )))))))))))))))))))))
    一整頁的右括號。:)

  • Type system - Wikipedia, the free encyclopedia

    var x = 5;     // (1)
    var y = "hi"; // (2)
    var z = x + y; // (3)

    • In this code fragment, (1) binds the value 5 to x; (2) binds the value "hi" to y; and (3) attempts to add x to y. In a dynamically typed language, the value bound to x might be a pair (integer, 5), and the value bound to y might be a pair (string, "hi"). When the program attempts to execute line 3, the language implementation checks the type tags integer and string, and if the operation + (addition) is not defined over these two types it signals an error.
    • In dynamic typing, type checking often takes place at runtime because variables can acquire different types depending on the execution path.
    • C static weak unsafe nominative


  • Greenspun's Tenth Rule - Wikipedia, the free encyclopedia
    Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

  • Occam's razor - Wikipedia, the free encyclopedia
    All things being equal, the simplest solution tends to be the best one.

  • ANSI Common Lisp Ch2 - Welcome to Lisp

    When we evaluate a pure Lisp expression like (+ 1 2), there are no side-effects; it just returns a value. But when we call format, as well as returning a value, it prints something. That's one kind of side-effect.

    Functional programming means writing programs that work by returning values, instead of by modifying things. It is the dominant paradigm in Lisp. Most built-in Lisp functions are meant to be called for the values they return, not for side-effects.

    Just as we can use ' as an abbreviation for quote, we can use \#'
    as an abbreviation for function.

    The defun macro creates a function and gives it a name. But
    functions don't have to have names, and we don't need defun to
    define them. Like most other kinds of Lisp objects, we can refer
    to functions literally.

    To refer literally to an integer, we use a series of digits; to
    refer literally to a function, we use what's called a lambda
    expression. A lambda expression is a list containing the symbol
    lambda, followed by a list of parameters, followed by a body of
    zero or more expressions.

  • Common Lisp - Wikipedia, the free encyclopedia

    (sort (list 5 2 6 3 1 4) #'>)
    ; Sorts the list using the > function as the comparison operator.
    ; Returns (6 5 4 3 2 1).

    (sort (list '(9 a) '(3 b) '(4 c))
    #'(lambda (x y) (< (car x) (car y))))
    ; Sorts the list according to the first element (car) of each sub-list.
    ; Returns ((3 b) (4 c) (9 a)).


Articles from Thinker

Thinker, 很多都是用台語寫的
AJAX 如何傳送資料到不同 host?
登入 Yahoo! 奇摩
簡單的藝術
軟體元件的使用
Functional VS Imperative (未完)
動態 load javascript file
Javascript 和後臺的配合
計算 DOM 物件位置

11/03/2006

Firefox 2.0 Tunning Options

about:config

  • browser.tabs.closeButtons -> 改為0
    說明: 開很多tab的時候,預設的方式會常按到不該案的close button,另一個原因是我都用mouse gestures
    0 Display a close button on the active tab only
    1 Display close buttons on all tabs (Default)
    2 Don’t display any close buttons
    3 Display a single close button at the end of the tab strip (Firefox 1.x behavior)

  • network.http.pipelining -> 改為true
    參考 網頁瀏覽加速法
  • keyword.URL -> 改為 http://www.google.com/search?btnI=I%27m+Feeling+Lucky&q=
    預設是yahoo,改成google好手氣
  • network.dns.disableIPv6 -> 改為true
    雖然官方說這樣是probably a placebo effect,不過等到有用到再開起來就好了。

11/01/2006

本週閱讀2006.11.01-2006.11.07

pointer pointer pointer


void GetMemory( char *p ){
p = (char *) malloc( 100 );
}

void Test( void ) {
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( str );
}

在GetMemory中, p是local variable, 所以GetMemory( str )後,str仍然是NULL.
應改為

void GetMemory( char **p ){
p = (char *) malloc( 100 );
}

void Test( void ) {
char *str = NULL;
GetMemory( &str );
strcpy( str, "hello world" );
printf( str );
}

bit manipulation

int I,J;
I = 257 /8;
J = 456 % 32;

int I,J;
I = 257 >>3;
J = 456 - (456 >> 4 << 4);

10/31/2006

C++ Reference

    int ival = 1024;
int *pi = &ival;
int &rval = ival;

cout << ival << endl;
cout << rval << endl;
cout << *pi << endl;
cout << &ival << endl;
cout << &rval << endl; //rval跟ival是同一各記憶體位址
cout << pi << endl; // pi儲存的是ival的記憶體位址
cout << & pi << endl; // pi也是個變數, 有自己的記憶體位址
// cout << *rval << endl; // error
// cout << *ival << endl; // error

以下是輸出結果
1024
1024
1024
0xbf9ec99c
0xbf9ec99c
0xbf9ec99c
0xbf9ec998

把 int &rval = ival; 換成 int &rval = *pi; 結果一樣。

10/27/2006

Automatix

http://www.getautomatix.com/

Automatix is a graphical interface for automating the installation of the most commonly requested applications in Debian based linux operating systems.

Linux.com : Automatix kicks Ubuntu into gear
Ubuntu 2006.10(Edgy)的安裝過程在這裡, 包含的套件在這裡

10/25/2006

本週閱讀2006.10.25-2006.10.31

10/23/2006

Pointers and Constants

以下內容摘自The C++ Programming Language

void f1(char *p){
char s[] = "Gorm";

const char *pc = s;
pc[3] = 'g'; // error: pc points to constant
pc = p; // ok

char *const cp = s;
cp[3] = 'a'; // ok
cp = p; // error: cp is constant

const char *const cpc = s;
cpc[3] = 'a'; // error: cpc points to constant
cpc = p; // error: cpc is constant
}

char *const cp;  //const pointer to char
char const* pc; //pointer to const char
const char* pc2; //pointer to const char

to read each such declarations right-to-left. ex: "cp is a const pointer
to a char" and "pc2 is a pointer to a char const".

void f4(){
int a = 1;
const int c = 2;
const int *pl = &c; // ok

const int *p2 = &a; // ok
int *p3 = &c; // error: initialization of int* with const int*
*p3 = 7;
}

10/21/2006

Re: [問題] C/C++中char*與char[]的差異

Re: [問題] C/C++中char*與char[]的差異

其實只要 C code 裡面出現 "string" 這種 literal constant string,
那 's' 't' 'r' 'i' 'n' 'g' '\0' 這個 sequence 必會出現在 constant pool 中,
而當你寫 char str[] = "string"; 且 str 非 global variable 時,
compiler 並不會直接產生一群分別填入這些字元到 stack 上的 code,
而是產生 load 之類的指令將這些值從 constant pool 搬至 stack。

Re: [問題] C/C++中char*與char[]的差異

"xxxxxx" 都是放在 constant pool 中,
而且通常 compiler 會將 constant pool 設為 read only。

char *ptr = "xxxxxx"; 是讓 ptr 指向 constant pool 裡第一個 'x' 的位置。
char str[] = "xxxxxx"; 是在 stack 中開 7 個 bytes 的空間,
並將 'x' 'x' 'x' 'x' 'x' 'x' '\0' 七個字元從 constant pool 中複製過來。

10/16/2006

Calling Conventions Demystified

Calling Conventions Demystified
__cdecl,__fastcall, __stdcall 什么区别?
c/c++的參數壓棧順序

* __cdecl is the default calling convention for C and C++ programs. The advantage of this calling convetion is that it allows functions with a variable number of arguments to be used. The disadvantage is that it creates larger executables.
* __stdcall is used to call Win32 API functions. It does not allow functions to have a variable number of arguments.
* __fastcall attempts to put arguments in registers, rather than on the stack, thus making function calls faster.
* Thiscall calling convention is the default calling convention used by C++ member functions that do not use variable arguments.

本週閱讀2006.10.15-2006.10.21

Google Print secret revealed

  • Google Print secret revealed
  • [新知]天價級的書本掃描器
  • Google Book Search Project
    Google recently implemented a convoy of new machines from Kirtas Technologies called the APT BookScan 1200, which is capable of scanning up to 1200 pages per hour (Kirtas Technologies). The machine works by utilizing a 16-megapixel digital camera to photograph each page, then transfers the image to local storage. Then, a robotic arm gently turns the page of the book, and the process is completed for each additional page. The digital images are then ‘cleaned’ to remove smudges and other errors, cropped, and centered. At this point, the image can be posted online, but "searching through the text is impossible.

雖然有comment說不是這一台,不過至少可以確定不是人工掃瞄的了。

面試相關文章

Quick tip: Styling blockquotes with CSS

blockquote {
background: transparent url(quoleft.png) left top no-repeat;
}
blockquote div {
padding: 0 48px;
background: transparent url(quoright.png) right bottom no-repeat;
}

10/15/2006

[轉載]學程式設計的人不能不看的好文章


以pow為例,pow簡單好寫,不過常常會忘了有效率的寫法:
1. 最直覺的方法,iterative,一個一個乘,把結果傳回去。
int pow(int base, int power){ 
int result = base;

if(power==0)
return 1;
while(power-->1)
result *= base;

return result;
}

2. 用recusive來做,寫出來的比較容易理解。
int pow(int base, int power){
if (power==0)
return 1;
return base*pow(base, power-1);
}

3. 最後就是第一題考的東西。
int pow(int base, int power){

if(power==0)
return 1;
if(power%2==0)
return pow(base, power/2)*pow(base, power/2);
else
return base*pow(base, power-1);
}

4. 可能再快一點的寫法,不過這不重要了。
int pow(int base, int power){
int t;

if(power==0)
return 1;
if(!(power&1)){
t = pow(base, power/2);
return t*t;
}
else
return base*pow(base, power-1);
}

Union

  • a union is big enough to hold the wildest member.
  • a union is a structure in which all memebers have offset zero from the base.

利用union判斷是Big-endian or Litte-endian (from : C, A Reference Manual)
#include<stdio.h>
union{
long l;
char c[sizeof(long)];
}u;

int main(){
u.l = 1;
if(u.c[0] == 1)
printf("Addressing is right-to-left(Little-endian)\n");
else if (u.c[sizeof(long)-1] == 1)
printf("Addressing is left-to-right(Big-endian)\n");
else printf("Addressing is strangs\n");
}

32bit數0x12345678在litte-endian存放方式(假設從0x4000開始存放)
0x4000 0x78
0x4001 0x56
0x4002 0x34
0x4003 0x12

32bit數0x12345678在big-endian存放方式(假設從0x4000開始存放)
0x4000 0x12
0x4001 0x34
0x4002 0x56
0x4003 0x78

10/08/2006

本週閱讀2006.10.08-2006.10.14

10/02/2006

Calculating Fibonacci numbers

http://www.ics.uci.edu/~dan/class/161/notes/7/Fib.html

Divide-and-conquer:

Fib3(n)
i := 1
j := 0
k := 0
h := 1
while n > 0 do
if n is odd then
t := jh
j := ih + jk + t
i := ik + t
t := h2
h := 2kh + t
k := k2 + t
n := floor( n/2 )
return j

T(n) = Θ(log n)

Fib3 works by making use of the fact that
_ _ n _ _
| 0 1 | | fn-2 fn-1 |
| | = | |
|_ 1 1 _| |_ fn-1 fn _|

10/01/2006

codefreak

http://fsfoundry.org/codefreak/

  • C++ Terminology - 1. Variety of Types

    Template Class
    也是 user-defined type 的 subset. 為 class template 的 instance
    (具現), e.g.:
    typedef list IntList;


    POD

    Acronym for Plain Old Data. User-defined C-style structure. 為
    user-defined type 的 subset, 需符合下列條件:
    1. 沒有 user-defined constructor, destructor 以及 assignment operator
    2. 沒有 base class type, 換句話說非 derive 自 user-defined type
    3. 如果有 data member, 其所有 data member 必須為 fundamental type 或 POD
    下兩例皆為 POD:

    class SomePodType
    {
    public:
    unsigned int data0;
    };
    struct AnotherPodTypeWithDataMember
    {
    SomePodType data1;
    char data2;
    };


    User-defined Type

    Aka. class type. 使用者自訂型別, 也稱為類或類別. 泛指所有的 struct 與
    class, 包含 C++ Standard Library 定義的型別, e.g.:

    class SomeClass;
    struct SomeStruct;
    template class basic_string;

    對 C++ 來說, 在定義 user-defined type 時, class 與 struct 幾乎是沒有差別且
    能互相替換 (interchangable). 唯一的差別是預設 (默認) 的存取權限:

    class DerivedClass : /*private*/ BaseClass
    {
    /*private:*/
    int data;
    };
    struct DerivedStruct : /*public*/ BaseStruct
    {
    /*public:*/
    int data;
    };

  • C++ Terminology - 2. Instance and Instanciation
  • Misconception of C++ Efficiency
  • Is your Singleton Broken?
  • Pointer to What?
    foo const * b;
    定義一個名為 b 的 (非常數) 指標, 這個指標指向一個常數 (const) foo.
    foo * const c;
    定義一個名為 c 的常數 (const) 指標, 這個指標 指向一個 (非常數) foo.

  • Boost.Lambda
  • C++0x
  • C/C++ Tips - The Marco Assert
    assert() 是個用來 debug 的macro, 接受一個 expression. 如果 expression 被 evalute 的結果為整數零, 或能被 convert 成零 (如 null pointer), 則會引發 assertion failure.
    assert(str != NULL); //str == NULL時會引發assert

Travelstar 4K40 4k120 hard disk drives specifications

http://www.hitachigst.com/hdd/support/4k40/4k40.htm

Requirement   +5VDC(±5%)
Startup current (peak, max.) 4.7 W
Seek (avg.) 2.3 W
Read (avg.) 2.0 W
Write (avg.) 2.1 W
Performance idle (avg.) 1.85 W
Active idle (avg.) 0.85 W Low power idle (avg.) 0.65 W
Standby (avg.) 0.25 W
Sleep 0.1 W

http://www.hitachigst.com/hdd/support/4k120/4k120.htm
Requirement   +5VDC(±5%)
Startup (peak, max.) 4.5W
Seek 1.7W
Read (avg.) 1.4W
Write (avg.) 1.4W
Performance idle (avg.) 1.25W
Active idle (avg.) 0.65W
Low power idle (avg.) 0.45W
Standby (avg.) 0.15W
Sleep 0.1W

9/28/2006

本週閱讀2006.09.24-2006.09.30

  • 易學易用的 Windows PowerShell
  • MIT 開鎖指南
  • 深度學習C++
  • STLport
  • The Boost C++ Libraries
  • 使用Subversion进行版本控制
  • The following .vimrc produces, in our opinion, very nicely formatted C code:
    set  nocp incsearch
    set cinoptions=:0,p0,t0
    set cinwords=if,else,while,do,for,switch,case
    set formatoptions=tcqr
    set cindent
    syntax on
    source ~/.exrc
    The nocp option turns off strict vi compatibility. The incsearch option turns on
    incremental searching. The settings for cinoptions, cinwords, and
    formatoptions differ from the defaults; the result is to produce a fairly strict
    "K&R" C formatting style. Finally, syntax coloring is turned on, and then the rest
    of the vi options are read in from the user's .exrc file.

9/12/2006

本週閱讀2006.09.10-2006.09.16

科學人雜誌網站 - 政治腦

XSS
XSS, Cookies, and Session ID Authentication – Three Ingredients for a Successful Hack
Burp - a Java-based proxy
CGI 介紹

事實上, 使用者填在 Form 中的資料, 瀏覽器會先將其組合成一個

參數1=參數1內容&參數2=參數2內容&...

的參數串, 再傳給 Http server

接著看 Form標記中, Method 的種類

Method=GET 時,
Http server 會將參數串設成環境變數 QUERY_STRING, CGI 程式只要將這個環境變數抓出來用即可,
不過由於是透過環境變數在傳遞這個參數串, 所以會有長度上的限制.

Method=POST 時,
Http server 會將參數串透過標準輸入傳給 CGI

[ 永遠的UNIX > CGI之C語言篇 ]
 printf("%d\n", '\r'); // 13, carriage return
printf("%d\n", '\n'); // 10, new line character
printf("%d\n", '\0'); // 0

Vim 實用技術,第 3 部分: 定製 Vim
1. 在 Vim 中打開 .vimrc 文件;
2. 執行命令「:colorscheme koehler」(缺省配色可能在瀏覽器中效果不佳)
3. 執行命令「:%!nl -w4 -s' '」(1.11 節)
4. 執行命令「:TOhtml」(1.13 節)
5. 執行命令「:w」

9/09/2006

排列組合

在PTT看到[問題] 關於排列組合,就是印出集合的所有排列組合3的字的集合印出{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}

  • 最簡單的:用迴圈
    #include <iostream>
    using namespace std;void main() {
    char a[]="ABC";
    int i,j,k,n;
    n = strlen(a);
    for (i=0;i<n;i++) {
    for (j=0;j<n;j++) {
    for (k=0;k<n;k++) {
    if (a[i]!=a[j] && a[i]!=a[k] && a[j]!=a[k])
    cout << a[i] << a[j] << a[k] << endl;
    }
    }
    }
    }

  • 再來是用stack+迴圈
    #define MAX 5

    int mark[MAX+1]= {0};// 記錄某一元素是否已使用
    int stack[MAX+1]; // 記錄放進去的先後
    // mark[0]、stack[0] 不放資料

    run=1; // 記錄是不是還要找下去

    len=0; // 目前的長度
    while(run) {
    if(len<MAX) {
    從 mark[] 中找到第一個還沒放進去的為 k
    mark[k]=1;
    stack[++len]=k;
    }
    else // len==MAX
    {
    stack[1] 到 stack[MAX] 全部印出來
    stack[MAX] 往前找到第一個非遞增的數為 k, 其位置為 j
    // 例如 3 4 5 2 1, 從後前找 1 2 5 是遞增, 但是 4 不是,

    // 所以 k=4, j=2
    如果找不到, 則把 run 設成 0, 並且 break;
    // 例如 5 4 3 2 1, 這是最後一種排列, 找完這一個就可以結束了
    stack[j] 到 stack[MAX] 的所有數對應 mark[] 值都設為 0,
    // 也就是把這些數拿出來
    再找 k 的下一個還沒放進去的數為 m
    len=j;
    stack[j]=m;
    mark[m]=1;
    // 例如 3 4 5 2 1, 則把 4 5 2 1 拿出來之後剩 3,

    // 再找 4 的下一個為 5 放進去, 就變成 3 5
    }
    }

  • 用recursive的 良葛格的Algorithm Gossip
    #include <stdio.h>
    #include <stdlib.h>
    #define N 4

    void perm(int*, int);

    int main(void) {
    int num[N+1], i;

    for(i = 1; i <= N; i++)
    num[i] = i;
    perm(num, 1);
    return 0;
    }
    void perm(int* num, int i) {
    int j, k, tmp;

    if(i < N) {
    for(j = i; j <= N; j++) {
    tmp = num[j];
    // 旋轉該區段最右邊數字至最左邊
    for(k = j; k > i; k--)
    num[k] = num[k-1];
    num[i] = tmp;

    perm(num, i+1);

    // 還原
    for(k = i; k < j; k++)
    num[k] = num[k+1];
    num[j] = tmp;
    }
    }
    else { // 顯示此次排列
    for(j = 1; j <= N; j++)
    printf("%d ", num[j]);
    printf("\n");
    }
    }

9/05/2006

Maximum Interval Sum

  • 定義給n個整數num[0..n-1],maximum interval sum要求 0<=i<j<=n-1,
    sum = num[i]+...+num[j]中最大那一個
  • 作法: sweep from left to right, accumulate the sum one element by one
    element, start new interval whenever you encounter partial sum<0 (and record
    current best maximum interval encountered so far)
  • 範例:
    num: 4 -5 4 -3 4 4 -4 4 -5
    sum: 4 -1 4 1 5 9 5 9 4
  • 解釋,對某一個位置k, sum[k]要根據sum[k-1]決定要不要累加sum[k-1],
    如果sum[k-1]小於0, 捨棄, 從位置k開始累加, 如果大於0, 把sum[k-1]累加.
  • code:
    max = sum[0] = num[0];
    for(i=1 ; i<n ; i++) {
    if(sum[i-1] < 0)
    sum[i] = num[i];
    else
    sum[i] = sum[i-1] + num[i];
    if(sum[i] > largest)
    max = sum[i];
    }

  • 練習題: 507 - Jill Rides Again, 10684 - The Jackpot
tag: acm programming

9/02/2006

今日閱讀2006-09-02

Pastbin菲爾茲獎Wikipedia 條目

strchr

譬如要找在Hello World中W出現在第幾個char, 注意p-target的部分

int main() {
char target[] = "Hello World", *p;
 
p = strchr(target, 'W');
printf("The character W was found at position %d\n", p-target);
}

The character W was found at position 6

或者用strcspn, 注意這邊"W"是雙引號,因為第二個參數是個char *而不是char
int main()
{
char target[] = "Hello World";
int position;
 
position = strcspn(target, "W");
printf("The character W was found at position %d\n", position);
}

The character W was found at position 6

類似的還有strpbrk, 跟strchar在於第二個函式是個char *, 可以match多個char

hex, oct -> decimal -> hex, oct

int main()
{
char hex[100], oct[100];
long num = 32712;

puts(hex);
sprintf(hex, "%X", num);
puts(hex);
sprintf(oct, "%o", num);
puts(oct);

sscanf(hex, "%x", &num);
printf("%d\n", num);
sscanf(oct, "%o", &num);
printf("%d\n", num);
}

7fc8
7FC8
77710
32712
32712

scanf + size_t

int main()
{
char dummy[100];
char buf[100];
 
scanf("%s\n", dummy);
gets(buf);
 
printf("|%s|\n", buf);
}

input:
ABCDEF
123
output:
|123|
注意scanf會吃掉123前面的三個space
int main()
{
char dummy[100];
char buf[100];

scanf("%s", dummy);
gets(buf);
printf("|%s|\n", buf);
}

input:
ABCDEF
123
output:
||
注意scanf會吃掉空白但是不會吃掉'\n'

http://beej.us/guide/bgc/output/html/scanf.html
%[

This is about the weirdest format specifier there is. It allows you to specify a set of characters to be stored away (likely in an array of chars). Conversion stops when a character that is not in the set is matched.

For example, %[0-9] means "match all numbers zero through nine." And %[AD-G34] means "match A, D through G, 3, or 4".

Now, to convolute matters, you can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."

To match a close square bracket, make it the first character in the set, like this: %[]A-C] or %[^]A-C]. (I added the "A-C" just so it was clear that the "]" was first in the set.)

To match a hyphen, make it the last character in the set: %[A-C-].

So if we wanted to match all letters except "%", "^", "]", "B", "C", "D", "E", and "-", we could use this format string: %[^]%^B-E-].

8/28/2006

7/31/2006

GCC重要的選項或旗標(FLAGS)

GCC重要的選項或旗標(FLAGS)

一些常用到的編譯旗標,如下
-c: 只建立obj檔,留待後面才來連結(link)
-S: 只建立assemblely檔。
-g: 建立一些除錯資訊給可執行檔,這樣debug工具ddd,gdb才能除錯。
-o: 把建立的二位元檔給另外名字,因為可執行檔最後內定名字是a.out。
-D: 條件編譯,搭配#ifdef #define用。如果有defined才編譯
-W: 編譯時出錯時,顯示錯誤訊息的條件。
-L: 給連結時要用到的函式庫的搜尋目錄。
-I: 標頭檔.h的搜尋目錄。
-l: 正常連結只會在libc這個函數庫,其他函數庫需要用這個指定連結。
-O1 -O2 -O3: 最佳化,會根據CPU的架構編出好的程式碼,需要多一點編譯時間。
-O2 是不錯的選擇。

像這樣的例子
$ gcc -c -o test.o test.c
$ gcc -S -o test.s test.c
$ gcc -g -o test.o test.c
$ gcc -D_SOLARIS_ -o test test.c
$ gcc -Wall -L./lib/ -I./include/ -o foo.o foo.c
$ gcc -Wall -L../lib -I../include -lX11 -lXext -lm -o xprog xprog.c

W用all表示所有的編譯warning都要秀出來。

Static, Shared, Dynamic 函式庫撰寫

Static,Shared, Dynamic 函式庫撰寫
Program Library HOWTO
三個檔案分別為: libhello.c libhello.h demo_use.c
最簡單的作法就是 gcc demo_use.c libhello.c -o result
不過這邊講的是要做成library, 所以以下

[static library]
GCC 的Static Library 副檔名通常為.a。用ar將很多object file 放進一個archive就是static library了。
用法: ar rcs libutil.a util_file.o util_net.o util_math.o
把util_file.o util_net.o util_math.o 產生一個static library叫作libutil.a

step1: 把.c檔都先弄成.o(object)的二進位檔
gcc -c -o libhello.o libhello.c //產生一個libhello.o
gcc -c -o demo_use.o demo_use.c //產生一個demo_use.o

step2:將obj檔弄成static libary的.a檔
ar rcs libhello.a libhello.o //產生一個libhello.a

step3: demo_use.c就可以呼叫static library裏面的函式了, 下面兩種寫法都可
gcc -o result demo_use.o -L. -lhello
gcc -o result demo_use.c libhello.a
* -L.意思是搜尋在目前目錄(.)的library
* Note that we omitted the "lib" prefix and the ".a" suffix when mentioning the library on the link command.

[shared library]

----libhello.c-------
#include
hello(){
printf("hello world\n");
}
---------------------
----main.c-----------
#include
printf("Inside main\n");
hello();
return 0;
}
---------------------

step1: gcc -fPIC -c libhello.c
The -fPIC option is to tell the compiler to create Position Independent Code (create libraries using relative addresses rather than absolute addresses because these libraries can be loaded multiple times).

step2: gcc -shared -o libmylib.so libhello.o
將數個.o檔做成一個.so檔
The -shared option is to specify that an architecture-dependent shared library is being created.

step3: gcc -c -o main.o main.c

step4:
gcc -o result -L. -lhello main.o

執行:
LD_LIBRARY_PATH="." ./result

[dynamic loading]
#include <dlfcn.h> /* defines dlopen(), etc.       */
#include
<stdio.h>
 
main(){
void *libc; /* handle of the opened library */
void (*printf_call)();
/* define a function pointer variable to hold the function's address */

if(libc=dlopen("/lib/libc.so.5",RTLD_LAZY)){
/*use the lazy approach(RTLD_LAZY) of checking only when used */
printf_call=dlsym(libc,"printf");
/*Calling Functions Dynamically Using dlsym()*/
(*printf_call)("hello, world\n");
}
}
"When we discussed static libraries we said that the linker will try to look for a file named 'libutil.a'. We lied. Before looking for such a file, it will look for a file named 'libutil.so' - as a shared library. Only if it cannot find a shared library, will it look for 'libutil.a' as a static library. Thus, if we have created two copies of the library, one static and one shared, the shared will be preferred. This can be overridden using some linker flags ('-Wl,static' with some linkers, '-Bstatic' with other types of linkers."

參考資料
Creating Libraries
GCC產生Static Library
Building And Using Static And Shared "C" Libraries
用Open Source工具開發軟體

7/28/2006

Stiff asks, great programmers answer

Stiff asks, great programmers answer
電腦相關書籍
Linus Torvalds: D&D "The C Programming Language", Crawford & Gelsinger’s "Programming the 80386″
Peter Norvig[Research Director at Google]: Structure and Interpretation of Computer Programs
David Heinemeier Hansson[Author of the Rails Framework]: Extreme Programming Explained
Dave Thomas[Author of the „Pragmmatic Programmer”]: "IBM/360 Principles of Operation."
Guido Van Rossum[The Python language creator]: Neil Stephenson’s Quicksilver.
James Gosling[The Java language creator]:Programming Pearls by Jon Bentley.
Tim Bray[One of the XML and Atom specifications author]:Bentley’s Programming Pearls

非電腦相關書籍
Linus Torvalds: Selfish Gene by Dawkins
David Heinemeier Hansson[Author of the Rails Framework]:1984, George Orwell
James Gosling[The Java language creator]:Guns, Germs & Steel by Jared Diamond
Tim Bray[One of the XML and Atom specifications author]:One Day in the Life of Ivan Denisovich

Introduction to Programming in C/C++ with Vim

Introduction to Programming in C/C++ with Vim
《用vim 寫程式快n 倍》
1. ctags
ctags是vim附代的工具, 可以讓從函式跳到該函式的定義處,
[/home/someuser/src]$ctags *
-R: Recurse into directories supplied on command line [no].
會在所在目錄下產生一個tags檔案,下面是檢索用的指令
control-] : 跳到指標關鍵字定義的位置
control-T : 可以用這個指令返回之前的位置

2.
set makeprg=gcc\ -o\ %<\ %
set errorformat=%f:%l:\%m
:make
:cl 列出所有錯誤
:cn 列出下一個錯誤
:cp 列出上一個錯誤

3.taglist
把taglist.txt放到~/.vim/doc
taglist.vim放到~/.vim/plugin
安裝完後
Tlist 打開Taglist視窗
c-w h, c-w l 可以在兩視窗互換
s Change the sort order of the tags (by name or by order)
Jump to the location where the tag under cursor is
defined.

Linux環境下的Socket編程

7/27/2006

bash script

把數行合併成一行, 有幾種作法:

1.tr -d '\n'
2.cat file|xargs echo
3.echo $(<filename)
4.sed -e 'N' -e 's/\n//' input

bash中用.來match任意字元, \1 \2代表第一個以及第個二match
$ cat test1
first:second
one:two
$ sed 's/\(.*\):\(.*\)/\2:\1/' test1
second:first
two:one

7/15/2006

今日閱讀2005-07-15


IE mhtml redirection漏洞利用方法


Project RainbowCrack
RainbowCrack is a general propose implementation of Philippe Oechslin's faster time-memory trade-off technique.
In short, the RainbowCrack tool is a hash cracker. A traditional brute force cracker try all possible plaintexts one by one in cracking time. It is time consuming to break complex password in this way. The idea of time-memory trade-off is to do all cracking time computation in advance and store the result in files so called "rainbow table". It does take a long time to precompute the tables. But once the one time precomputation is finished, a time-memory trade-off cracker can be hundreds of times faster than a brute force cracker, with the help of precomputed tables.

6/30/2006

Doing nothing in Bash

http://ynniv.com/blog/2005/04/doing-nothing-in-bash.html
像是C語言中的;
bash中沒有do nothing的語法

* touch /dev/null [Keystrokes: 15. Runtime: 0.02s]
* sleep 0 [Keystrokes: 7. Runtime: 0.03s]
* A=0 [Keystrokes: 3. Runtime: 0.00s]

interesting

6/19/2006

今日閱讀2006-06-19

tag: linux

6/18/2006

Ubuntu Tips- virtual pdf printer

  1. sudo apt-get install cups-pdf
  2. sudo chmod +s /usr/lib/cups/backend/cups-pdf
  3. 系統->管理->printing->新增印表機->印表機類型選"本地印表機", 使用偵測到的印表機選"PDF Printer"->下一步
  4. 製造商選Generic -> 型號選postscript color printer rev3b->下一步
  5. 套用
參考: Print to PDF using cups-pdf

歷史股價查詢

歷史股價查詢
start,end,stockid分別是起迄以及股票代號
開一個文字檔, 複製上面網址, 副檔名改為.iqy, 即可用excel處理

tag: 股票

6/16/2006

An Inside View From a Google Employee

http://blog.outer-court.com/archive/2006-06-15-n22.html

  • ZorbaTHut says that Google is mostly C++, Java, and Python (or so he’s been told).

  • “We’ve got extensive automated unit tests, all of which (obviously) must pass.”

  • Zorba writes that he has only about one meeting per month.

  • The company’s structure, at least for engineers, is amazingly flat.
    Zorba says the Google hierarchy is just five levels: Programmer - Tech lead - Manager -
    Department lead - Larry/Sergey/Eric. Google just assumes their workers are competent,
    Zorba adds.

  • “[M]ost people are Linux-only

  • Zorba says that in his opinion, C++ is the best single programming language out
    there
    . He says however that it also doesn’t protect you from shooting yourself in the foot.

  • On how Google goes about staffing a Test Engineer position, Zorba replies: “I don’t know
    what other teams are like, but on my team everyone owns their own tests and handles
    their own quality
    .”

6/15/2006

如何寫一份好的師程工簡歷

如何寫一份好的師程工簡歷
1.談到你做過的技術時,應該提到用的程序語言、你的個人貢獻和產品細節。
2.多講事實, 少用形容詞。
3.你獲得的獎、商業的榮譽或表揚、受用戶歡迎的產品和你做過的有難度的業餘項目都該包括在簡歷裡。
4.分清主次,刪掉相比之下不起眼的成績,以免沖淡更加突出的成績。

greasmonkey script example

因為每次yahoo登入都記不住帳號跟密碼, 所以寫了一個簡單的來自動填
順便練習了一下addEventListener的用法,
這樣寫的優點可以等到整各頁面load完之後在開始執行function()的部份.
這邊有人寫一樣的東西


// ==UserScript==
// @name yahoo username & password filler
// @namespace http://birdegg.tw
// @description 懶人的工具
// @inclue http://tw.login.yahoo.com/
// @inclue http://login.yahoo.com/
// ==/UserScript==
window.addEventListener(
'load',
function() {
var login = document.getElementsByName('login')[0];
var passwd = document.getElementsByName('passwd')[0];
login.value = "username";
passwd.value = "passwd";
},
false
);

HTML META Tags

A Dictionary of HTML META Tags


<META HTTP-EQUIV="refresh" CONTENT="0;URL=http://us.imdb.com/title/tt0414387">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-2022-JP">
<META HTTP-EQUIV="Window-target" CONTENT="_top">
<META NAME="ROBOTS" CONTENT="NOINDEX,FOLLOW">
<META NAME="keywords" CONTENT="oranges, lemons, limes">

6/09/2006

Shell Script Practice

一個shell script, 可以把活躍會員帳號轉為lftp的bookmark

#!/bin/bash
user="birdegg1108"
passwd=""

#sort -n 以數字排序
datas=`cat active.account|grep 3322.org|sort -n -t's' -k2|uniq`

for data in $datas
do
number=`echo $data|cut -d'.' -f1|cut -d'f' -f2`
if [ "$passwd" == "" ]; then
echo "$number \"ftp://$user@$data\""
else

echo "$number \"ftp://$user:$passwd@$data\""
fi
done

tag: linux bash shell script

6/08/2006

今日閱讀2006-06-08

Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken
一開始是一個簡單的binary search

1:     public static int binarySearch(int[] a, int key) {
2: int low = 0;
3: int high = a.length - 1;
4:
5: while (low <= high) {
6: int mid = (low + high) / 2;
7: int midVal = a[mid];
8:
9: if (midVal < key)
10: low = mid + 1;
11: else if (midVal > key)
12: high = mid - 1;
13: else
14: return mid; // key found
15: }
16: return -(low + 1); // key not found.
17: }

如果low+high比int(2^31-1)大的話, 會有bug

作者提供了解決的方法

6: int mid = low + ((high - low) / 2);

或者
6:             mid = ((unsigned) (low + high)

6/06/2006

今日閱讀2006-06-06

6/05/2006

利用Javascript對用戶端資訊的蒐集

http://qtutu.com/blog/?p=11
http://www.chedong.com/tech/click.html


/* (C) 2003 - 2004 www.chedong.com

* Free for all users, but leave in this header

* click based user analysis:
* usage: touch a empty click.gif or create a static page on at server
* including following script into your html page
*/

document.onclick = clickStat;

function clickStat() {
// create a new empty element
var image = document.createElement("<img src="" />");

// record client screen size and mouse coordinate
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
image.src = "http://www.chedong.com/click_stats.php?width=" + screen.width + "&x="
+ tempX + "&amp;y=" + tempY;
image.height = 0;
image.width = 0;

//send request to stat server
document.body.insertBefore(image);
return true;
}

Random Files

http://googlesystem.blogspot.com/2006/05/random-files.html
Google indexes not just web pages and documents, but also interesting file types like executables, databases or source code files. To search for a file with a specific extension, you need to use the operator filetype.

1. Find applications.
If you search for [winamp filetype:exe], the first result is a direct link to Winamp 5.08. Searching for [python filetype:msi] brings many direct links to Python 2.4 setup. It's interesting to see that Google actually indexes the files and gets some metadata from them.

2. Find source code.
There's a lot of code available on Google: some on governmental sites, other useful for educational purposes. You can even restrict your search to a certain type of license.

3. Find databases.
You can find CSV files, SQL scripts, DBF files, MDB files.

4. Find feeds.
Get a list of great feeds to import to your favorite feed reader. This way you can search for the feed address of your favorite site, without looking in the source code.

5. Other interesting files.
Registry files, configuration files and, my favorite, Inno Setup scripts.

So the next type you need a file to test an application or to use it as an example, try Google.

今日閱讀2006-06-05

Levels of JavaScript Knowledge

Serving JavaScript Fast
via
He talks about several different approaches, including:

* Monolith - the bigger the chunks the better, less overhead of loading more than one file for each page execution
* Splintered Approach - divide it up into multiple subfiles and only load what you need
* Compression - gzipping up the content to reduce its filesize as sent to the browser
* Caching- sending headers to correctly cache the javascript file(s)

6/01/2006

今日閱讀2006-06-01

Web Development Bookmarklets
Dive Into Greasemonkey
Gecko DOM Reference, Index
A look at the FreeNAS server


<form action=http://www.google.com/search name=f>
<input type=hidden name=hl value=zh-TW>
<input maxlength=2048 size=55 name=q title="Google 搜尋">
<input type=submit value="Google 搜尋" name=btnG>
</form>



// ==UserScript==
// @name google at yahoo
// @namespace http://birdegg.tw
// @description add a search box at http://tw.yahoo.com
// @include http://tw.yahoo.com/
// @include http://localhost/*
// ==/UserScript==
var hotsch = document.getElementById('hotsch');
hotsch.innerHTML = "";
var googlediv = document.createElement("DIV");
googlediv.innerHTML = "
<form action=\"http://www.google.com/search\" name=f>
<input type=hidden name=hl value=zh-TW><
input maxlength=2048 size=39 name=q title=\"Google\">
<input type=submit value=\"Google\"
name=btnG></form>"

hotsch.appendChild(googlediv);

5/30/2006

今日閱讀2006-05-30

TrueCrypt
Free open-source disk encryption software for Windows XP/2000/2003 and Linux
tag: encrypt

W3C-XHTML
tag: html xhtml web

5/25/2006

Google Services

Blogger Favicon

換了Favicon,參考這一篇
把圖(假設是favicon.png)放到可以link的地方(ex: flickr),然後在範本的</head>前面加入這三行。不過ie好像看不到?

<link rel="shortcut icon" href="http://example.com/favicon.png" />
<link rel="icon" href="http://example.com/favicon.png" />
<link rel="shortcut icon" href="http://example.com/favicon.png" />

Gmail的寫法
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">

5/23/2006

Linux Tools

Faster remote desktop connections with FreeNX

synergy
Synergy lets you easily share a single mouse and keyboard between multiple computers with different operating systems, each with its own display, without special hardware. It's intended for users with multiple computers on their desk since each system uses its own monitor(s).

CLI Magic: Viewing pictures on the console with fbida
Fbida (previously known as fbi) is an image viewer for the Linux console.
tag: linux tools remote control

How Shellcodes Work

How Shellcodes Work

  • shell code不能有data segment
    The problem is that both programs use their own data segments, which means that they cannot execute inside another application. This means in chain that an exploit will not be able to inject the required code into the stack and execute it.
  • eax存的是function codes(can be found in /usr/include/asm/unistd.h), ebx存的是第一各parameter, ecx存的是第二各parameter,...
  • array的話反著push進去stack, esp(enhanced stack pointer)會儲存stack的top element address
  • int 0x80 ; Call the kernel to make the system call happen

Related Shellcodes links

tag: hack shell code programming

5/22/2006

RealVNC 4.1.1 Remote Compromise

http://marc.theaimsgroup.com/?l=bugtraq&m=114771408013890&w=2

1) Server sends its version, "RFB 003.008\n"
2) Client replies with its version, "RFB 003.008\n"
3) Server sends 1 byte which is equal to the number of security types offered
3a) Server sends an array of bytes which indicate security types offered
4) Client replies with 1 byte, chosen from the array in 3a, to select
the security type
5) The handshake, if requested, is performed, followed by "0000" from the server

Server -> Client: 52 46 42 20 30 30 33 2e 30 30 38 0a <- Server version
Client -> Server: 52 46 42 20 30 30 33 2e 30 30 38 0a <- Client version
Server -> Client: 01 02 <- One field follows... and that field is 02
(DES Challenge)
Client -> Server: 01 <- Ahh, the lovely 1 byte exploit! Beautiful, isn't it?
Server -> Client: 00 00 00 00 <-- Authenticated!

realvnc_41_bypass
Metasploit Framework
The Framework was written in the Perl scripting language and includes various components written in C, assembler, and Python. The widespread support for the Perl language allows the Framework to run on almost any Unix-like system under its default configuration. A customized Cygwin environment is provided for users of Windows-based operating systems. The project core is dual-licensed under the GPLv2 and Perl Artistic Licenses, allowing it to be used in both open-source and commercial projects.

今日閱讀2006-05-22

Ubuntu Dapper Drake 6.06 Guide
Unofficial Ubuntu 6.06 (Dapper Drake) Starter Guide
Ubuntu Dapper Installation Guide: Unofficial ATi Linux Driver
tag: ubuntu linux

PHP4 Benchmark
PHP5 Benchmark
tag: php programming

5/17/2006

簡易DIY迷你攝影棚

DIY簡易迷你去背攝影棚
沒比他更簡單的簡易DIY迷你攝影棚

pagerank

pagerank的專利申請
The Anatomy of a Large-Scale Hypertextual Web Search Engine

物件導向的Javascript

1.先看這一篇,寫得很好
Quick guide to somewhat advanced Javascript (cache)

2.再來看
Quick Guide to Prototype
Developer Notes for prototype.js (cache),當然要跟prototype.js對照著看。

3.再來還有一拖拉庫的Javascript Library可以看, ex:

VIM改造

http://blog.othree.net/log/2006/04/08/vim_7_beta/.vimrc (cache)
目前的vimrc

ctrl+c : copy
ctrl+x : cut
ctrl+v : paste
ctrl+s : 存檔
ctrl+z : 回復上一步
ctrl+n : new tab
ctrl+\ : 切換tab

Firefox Extensions

Leak Monitor Extension

This Firefox extension detects one very specific type of leak in chrome JavaScript and in Web pages. (Not in JavaScript components, though.) It detects when JavaScript objects in the chrome or Web page are still held by native code after the window is closed.

VideoDownloader
Download videos from Youtube, Google, Metacafe, iFilm, Dailymotion... and other 60+ video sites ! And all embedded objects on a webpage (movies, mp3s, flash, quicktime, etc) ! Directly !

5/12/2006

Javascript - DOM

HTML文件的階層結構在DOM中是以樹結構來表達。樹的節點是代表文件中各種型態的內容。

<html>
<head>
<title>Sample Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>Simple</i> document.
</body>
</html>

以DOM的觀點來看這份文件,結構如下


  • Node物件的childNodes屬性會傳回該節點的子節點清單。
  • firstChild, lastChild,nextSibling, previousSibling,parentNode屬性讓你尋訪樹結構中的節點的手段
  • appendChild(), removeChild(), replaceChild(), insertBefore()可以在文件數中新增移除節點

介面                      NodeType常數                nodeType之值
Element Node.ELEMENT_NODE 1
Text Node.TEXT_NODE 3

<head>
<script>
function counterTags(n){
var nTags = 0;
if(n.nodeType==1){
nTags++;
// alert(n.tagName);
}
var children = n.childNodes;
for(var i=0; i<=children.length-1; i++){
nTags += counterTags(children[i]);
}
return nTags;
}
</script>
</head>
<body onload = "alert('this document has '+counterTags(document)+' tags')">
<h1>This is a <i>sample</i> document.</h1>
</body>

會alert "this document has 7 tags",分別是HTML,HEAD,TITLE,SCRIPT,BODY,H1,I,
雖然沒有HTML, TITLE不過也會計算進去。

找出文件中特定的元素

getElementsByTagName("body")[0]
//getElementByTagName()傳回一個NodeList物件。視為陣列

如果想對文件中的第四段落做些什麼事
var myParagraph = document.getElementsByName("p")[3]
不是最佳做好->在文件的開頭新插入一段,程式就不能用了。最好是給一個id標籤,替元素指定獨一無二的名稱。
<p id="specialParagraph">
就可以用var myParagraph = document.getElementById("specialParagraph")
注意getElementById()不像getElementsByTagName()傳回含有元素的陣列。因為每個id特性之值都是唯一的,getElementsById()只會傳回一個吻合id特性的單一元素。

可以使用getElementById()來找出特定元素,再用getElementsByTagName()來找出該元素下特定型態的所有子孫節點。
//在文件中找出特定的表格元素,在計算其資料列數目
var tableOfContents = document.getElementById("TOC");
var rows = tableOfContents.getElementByTagName("tr");
var numrows = rows.length;

修改文件
利用document.createTextNode()來建立新的Text節點
<script>
// This function recursively looks at node n and its descendants,
// replacing all Text nodes with their uppercase equivalents.
function uppercase(n) {
if (n.nodeType == 3 /*Node.TEXT_NODE*/) {
// If the node is a Text node, create a new Text node that
// holds the uppercase version of the node's text, and use the
// replaceChild() method of the parent node to replace the
// original node with the new uppercase node.
var newNode = document.createTextNode(n.data.toUpperCase());
var parent = n.parentNode;
parent.replaceChild(newNode, n);
}
else {
// If the node was not a Text node, loop through its children,
// and recursively call this function on each child.
var kids = n.childNodes;
for(var i = 0; i < kids.length; i++) uppercase(kids[i]);
}
}
</script>

<!-- Here is some sample text. Note that the p tags have id attributes -->
<p id="p1">This <i>is</i> paragraph 1.</p>
<p id="p2">This <i>is</i> paragraph 2.</p>

<!-- Here is a button that invokes the uppercase() function defined above -->
<!-- Note the call to Document.getElementById() to find the desired node -->
<button onclick="uppercase(document.getElementById('p1'));">Click Me</button>

利用document.createElement建立新的元素(html tag)

<script>
// This function takes a node n, replaces it in the tree with an Element node
// that represents an html <b> tag, and then makes the original node the
// child of the new <b> element.
function embolden(node) {
var bold = document.createElement("b"); // Create a new <b> Element
var parent = node.parentNode; // Get the parent of node
parent.replaceChild(bold, node); // Replace node with the <b> tag
bold.appendChild(node); // Make node a child of the <b> tag
}
</SCRIPT>

<!-- A couple of sample paragraphs -->
<p id="p1">This <i>is</i> paragraph #1.</p>
<p id="p2">This <i>is</i> paragraph #2.</p>

<!-- A button that invokes the embolden() function on the first paragraph -->
<button onclick="embolden(document.getElementById('p1'));">Embolden</button>

<script>
function changelink(){
document.getElementById('myAnchor').innerHTML = "visit W3Schools";
document.getElementById('myAnchor').href = "http://www.w3schools.com";
document.getElementById('myAnchor').target = "_blank";
}
</script>

<a id="myanchor" href="http://www.microsoft.com">Visit Microsoft</a>
<input type="button" onclick=changelink() value="change link">
</pre>

DIR Command

http://www.ss64.com/nt/dir.html

在這個目錄下找出所有有foobar字的目錄(不包含檔案)。
dir *.* /a:d /b /s /l | find "foobar"
/A:D 只列出Folder
/B Bare format (no heading information or summary).
/S include all subfolders.
/L use Lowercase. (因為find是case sensitive)

在這個目錄下列出所有目錄
dir *.* /a:d /b /s