XML: Tài liệu XML có cấu trúc Cây

Người đăng: share-nhungdieuhay on Thứ Hai, 29 tháng 7, 2013

Các tài liệu XML phải có một yếu tố gốc. Yếu tố này là "cha mẹ" của tất cả các yếu tố khác.
Các yếu tố trong một tài liệu XML tạo thành một cây tài liệu. Cây bắt đầu ở gốc và các nhánh đến mức thấp nhất của cây.

Tất cả các yếu tố có thể có yếu tố phụ (các phần tử con):
<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>

Các điều khoản cha mẹ, con, anh chị em và được sử dụng để mô tả mối quan hệ giữa các yếu tố. Yếu tố cha mẹ có con. Con trên cùng một mức độ được gọi là anh chị em ruột (anh chị em).

Tất cả các yếu tố có thể có nội dung văn bản và các thuộc tính (giống như trong HTML).
Ví dụ:

<bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Phần tử gốc trong ví dụ này là <bookstore>. 
Tất cả các yếu tố <book> trong các tài liệu được chứa trong <bookstore>.

Các yếu tố <book> có 4 con: <title>, <author>, <year>, <price>.

More about

PHP: Hàm trả về vị trí xuất hiện của chuỗi s1 trong chuỗi s2

Người đăng: share-nhungdieuhay on Chủ Nhật, 21 tháng 7, 2013


<?php 
/*  This  function  returns  the  position  of  string  s1  within  string  s2. 
      The  position  is  1  based.    If  s1  is  not  in  s2,  0  is  returned. 
*/ 
function  InStr($s1,  $s2) 

        //Check  for  valid  input 
        if(!(is_string($s1)  &&  is_string($s2)))  return  0; 

        $s1len  =  strlen($s1); 
        $s2len  =  strlen($s2); 

        //Check  if  s1  in  s2  at  all 
        if(!ereg($s1,  $s2))  return  0; 

        //Resolve  simple  case 
        if($s1  ==  $s2)  return  1; 

        //Set  initial  search  limits 
        $begin  =  0; 
        $end  =  $s2len  -  $s1len; 

        //Initialize  position 
        $position  =  0; 

        //Do  binary  search  of  s2  for  s1 
        //Check  left  side  first  to  find  first  occurance  of  s1 
        //Check  right  side  first  to  find  last  occurance  of  s1 
        while($end  >  $begin  +  1) 
        { 
                $middle  =  ceil(($begin  +  $end)  /  2); 
                $leftBegin  =  $begin; 
                $rightBegin  =  $middle  +  $s1len; 
                $leftEnd  =  $middle; 
                $rightEnd  =  $end  +  $s1len; 

                //Check  left  first 
                if(ereg($s1,  substr($s2,  $leftBegin,  $rightBegin  -  $leftBegin))) 
                { 
                        $end  =  $middle; 
                } 
                else  //(ereg($s1,  substr($s2,  $leftEnd,  $rightEnd  -  $leftEnd))) 
                { 
                        $position  +=  $middle  -  $begin; 
                        $begin  =  $middle; 
                } 
        } 

        //Resolve  1  off  problems  introduced  by  ceil 
        if(ereg($s1,  substr($s2,  $end,  $s1len)))  $position++; 

        //Return  position  1  based 
        return  $position  +  1; 

?>

More about

Assembly: Hiển thị bộ nhớ (Show Memory)

Người đăng: share-nhungdieuhay on Thứ Tư, 17 tháng 7, 2013


kbd             equ     16h             ;keyboard irq
msdos           equ     21h             ;MSDOS irq

reset           equ     0dh             ;disk reset
dfopen          equ     0fh             ;open disk file
dfclose         equ     10h             ;close disk file
searchf         equ     11h             ;search first
searchn         equ     12h             ;search next
seqread         equ     14h             ;sequential disk read
seqwrite        equ     15h             ;     "       "  write
setdta          equ     1ah             ;set disk transfer area address
createf         equ     3ch             ;create file with handle
openf           equ     3dh             ;open file with handle
closef          equ     3eh             ;close file with handle
readf           equ     3fh             ;read from file with handle
writef          equ     40h             ;write to file with handle
setfp           equ     42h             ;set file pointer
allocmem        equ     48h             ;allocate memory
freemem         equ     49h             ;free memory
changebs        equ     4ah             ;change block size
findfirst       equ     4eh             ;find first file
exit            equ     4c00h           ;msdos exit

[BITS 16]                               ;NASM stuff
[ORG 0x100]

s1:
        mov     ax,cs                   ;get code segment
        mov     ds,ax                   ;use it now
        mov     [comseg],ds             ;save it there        

        mov     si,0080h                ;DOS command line page 0
        lodsb                           ;load size of command line
        cmp     al,0                    ;anything on command line ?
        jbe     usage                   ;noo, show usage
        cbw                             ;extend AL to AX
        xchg    bx,ax                   ;swap size to bx for indexing
        mov     byte [bx+si],0          ;null terminate command line
        call    parse                   ;parse command line
        jmp     main                    ;go on with main
usage:  mov     bx,utext                ;pointer usage text
        jmp     errout                  ;skip this
main:
        mov     si,inbuff               ;check for valid HEX input
        mov     bx,errt1                ;proper text
ishex:  lodsb                           ;get the char
        cmp     al,'0'
        jb      errout
        and     al,0dfh                 ;force UPPERCASE
        cmp     al,'F'                  ;>F ?
        ja      errout                  ;yeahh, dump this
        loop    ishex
        call    hexbin                  ;make hex bin
                                        ;start address now in EDX
        mov     ax,dx                   ;get low word (segment)
        mov     es,ax                   ;start segment
        shr     edx,16                  ;shift in offset
        mov     di,dx                   ;start offset
dopage:
        push    es                      ;save registers
        push    di
        push    ds
        push    si
        mov     ax,es
        mov     ds,ax                   ;make ds=es
        mov     si,di                   ;and si=di
        
        call    showpage                ;show it
        
        pop     si                      ;restore registers
        pop     ds
        pop     di
        pop     es
        add     di,512                  ;adjust memory position

        ;xor     ah,ah                  ;wait for ANY key
        ;int     kbd
        
        mov     bx,text                 ;show message
        call    write
        mov     ah,0                    ;wanna see next screen  ?
        int     kbd                     ;chek out keyboard buffer
        and     al,0DFh                 ;force UPPER CASE
        cmp     al,"Q"                  ;wanna quit ?
        je      quit                    ;yeahh
        jmp     dopage
errout:
        call    write
quit:   
        mov     ax,exit
        int     msdos

;***********************************************************
;*      Convert ascii hex to 32 bit binary
;*      Input = command line buffer, output EDX
;***********************************************************
hexbin:
        mov     si,inbuff               ;pointer command line buffer
        xor     edx,edx                 ;clear binary output
aschexbin:
        lodsb
        cmp     al,'0'                  ;< 0
        jb      notasc                  ;yes invalid character
        cmp     al,'9'                  ;<= 9
        jbe     astrip                  ;yes, strip high 4 bits
        and     al,05fh                 ;force upper case
        cmp     al,'A'                  ;< ascii A
        jb      notasc                  ;yes, invalid character
        cmp     al,'F'                  ;> ascii F
        ja      notasc                  ;yes, invalid character
        add     al,9                    ;ok, add 9 for strip
astrip:
        and     al,0fh                  ;strip high 4 bits
        mov     cx,4                    ;set shift count
        shl     edx,cl                  ;rotate EDX 4 bits
        xor     ah,ah                   ;zero out AH
        cbw
        add     edx,eax                 ;add digit to value
        jmp     aschexbin               ;continue
notasc: ret

;*********************************************************************
;*      Format and show the stuff in a "sector"
;*      Input SI
;*********************************************************************
showpage:
        mov     cx,32                   ;32*16=512
arow:   push    cx
        mov     di,outline              ;output buffer
        mov     cx,16                   ;process 16 bytes
hexrow: push    cx
        lodsb                           ;load al with byte
        mov     dl,al                   ;get value
        mov     cx,2                    ;2 nibbles
chexb:  push    cx                      ;save that
        mov     cl,4                    ;4 bits
        rol     dl,cl                   ;rotate source left
        mov     al,dl                   ;move digit into AL
        and     al,15                   ;clear high nibble
        daa                             ;adjust AL if A through F
        add     al,240                  ;bump the carry
        adc     al,40h                  ;convert HEX to ASCII
        stosb                           ;copy to buffer
        pop     cx                      ;get digit counter
        loop    chexb                   ;next digit
        mov     al,32                   ;copy a SPACE
        stosb
        pop     cx                      ;restore loop counter
        loop    hexrow                  ;loop on
        mov     al,32                   ;copy 2 spaces
        stosb
        stosb
        sub     si,16                   ;adjust source back
        mov     cx,16                   ;copy ASCII bytes
cccp:   lodsb
        cmp     al,32                   ;< SPACE ?
        jb      noa                     ;yeahh, skip it
        stosb                           ;no, store in buffer
        jmp     next
noa:    mov     al,'.'
        stosb
next    loop    cccp   
        mov     al,13
        stosb
        mov     al,10
        stosb
        mov     al,0                    ;null terminate line
        stosb
        mov     bx,outline              ;show the line
        call    write
        pop     cx
        cmp     cx,17
        jne     nopause
        push    ds
        mov     ax,cs
        mov     ds,ax
        mov     bx,text1
        call    write
        pop     ds
        xor     ah,ah
        int     kbd
nopause:
        loop    arow                    ;next 16 bytes
        ret

;************************************************************************'
;*      Convert bin WORD to HEX ascii. Input DX. Result in Numbuff      *
;************************************************************************
binhex: pusha       
        mov     di,numbuff              ;destination buffer
        mov     dx,[count]              ;binary number
        mov     cx,4                    ;four nibbles
convhex:
        push    cx                      ;save counter
        mov     cl, 4                   ;4 bits
        rol     dx, cl                  ;rotate source left
        mov     al, dl                  ;move digit into AL
        and     al, 15                  ;clear high nibble
        daa                             ;adjust AL if A through F
        add     al, 240                 ;bump the carry
        adc     al, 40h                 ;convert HEX to ASCII
        stosb                           ;copy to buffer
        pop     cx                      ;get digit counter
        loop    convhex                 ;next digit
        mov     al,32                   ;copy a space
        stosb
        mov     al,0                    ;null terminate
        stosb
        popa
        ret

;*************************************************************************
;*       Writes out the NULL terminated text supplied in BX.             *
;*       OR writes out data,BX and size,CX if called at lwrite.          *
;*************************************************************************
write:  pusha
        mov     si,bx                   ;copy to SI
        mov     cx,0                    ;clear count
wloop:  lodsb                           ;load AL with SI
        cmp     al,0                    ;end of line ?
        je      lwrite                   ;yeahh
        inc     cx                      ;no, incrase byte count
        jmp     wloop                   ;test next byte
lwrite: mov     dx,bx                   ;text address in DX
        mov     bx,1                    ;filehandle standard output = 1
        mov     ah,writef               ;MS-DOS writefile with handle is 040
        int     msdos                   ;write buffer to standard output
        popa
        ret                             ;done

;*************************************************************************
;*      My kind of command line parsing. It just checks if there�s
;*      any blankspaces between the options. The parameters ends up
;*      in the inbuff separated by 0:s, binary zeroes.
;*************************************************************************
parse:
        mov     di,inbuff               ;our buffer
ifspc:  cmp     byte [si],32            ;leading space  ?
        jne     nospc                   ;noo
        inc     si                      ;yeahh, dump that
        jmp     ifspc                   ;check next
nospc:  mov     cx,1                    ;were here, so we got one arg
copy1:  lodsb                           ;load byte SI to AL
        cmp     al,0                    ;0 ?(end of line)
        je      done                    ;yeahh
        cmp     al,32                   ;SPACE ?
        je      cop2                    ;yeah
        stosb                           ;noo, move AL to DI, incrase DI
        jmp     copy1                   ;go on
cop2:   mov     byte [di],0             ;null terminate
        add     cx,1
        inc     di                      ;dump that byte(SPACE)
        jmp     copy1                   ;back
done:   mov     byte [di],0             ;null terminate
        ret                             ;return


;*************************** DATA STUFF **********************************

XMS_SEGMENT     dw 0
XMS_OFFSET      dw 0

inbuff          times 64 dw 0           ;128 byte command line buffer
outline         times 40 dw 0           ;buffer output line
numbuff         times 7 dw 0            ;word ascii number buffer
comseg          dw 0
count           dw 0
bcount          dw 0
acount          dw 0

;outbuff         times 512 db 0

utext           db      'WWW',13,10
                db      'Usage: Showmem [start address].',13,10
                db      'Start address = Hexadecimal.',13,10,0
text:           db      13,10,'Q = Quit. Any key = Next page.',13,10,0
text1:          db      13,10,'Any Key = Next 256 Bytes.',13,10,0
errt1:          db      'That address is not hexadecimal.',13,10,0

s2:

END

More about

Java: Xây dựng chương trình Client - Server ở chế độ KHÔNG kết nối (UDP)

Người đăng: share-nhungdieuhay on Thứ Hai, 15 tháng 7, 2013


Chương trình UDPEchoServer cài đặt Echo Server ở chế độ không nối kết, cổng mặc định là 7. Chương trình chờ nhận từng gói tin, lấy dữ liệu ra khỏi gói tin nhận được và gởi ngược dữ liệu đó về Client.

1. UDPEchoServer.java
import java.net.*;
import java.io.*;
public class UDPEchoServer {
    public final static int port = 7; // Cong mac dinh cua Server
    public static void main(String[] args) {
        try {
            DatagramSocket ds = new DatagramSocket(port); // Tao socket voi cong la 7
            byte[] buffer = new byte[6000]; // Vung dem chua du lieu cho goi tin nhan 
            while(true) {    // Tao goi tin nhan
                DatagramPacket incoming = new DatagramPacket(buffer,buffer.length);
                ds.receive(incoming); // Cho nhan goi tin gui den
                 // Lay du lieu khoi goi tin nhan
                String theString = new String(incoming.getData(),0,incoming.getLength());   
                //  Tao goi tin gui chua du lieu vua nhan duoc
                DatagramPacket outsending = new DatagramPacket(theString.getBytes(), 
                incoming.getLength(),incoming.getAddress(), incoming.getPort()); 
                ds.send(outsending);
            }
        }
        catch (IOException e) {
            System.err.println(e);
        } 
    }
}
        Chương trình EDPEchoClient sẽ cho phép người sử dụng nhận các chuỗi từ bàn phím, gởi chuỗi sang EchoServer ở chế độ không nối kết ở cổng số 7, chờ nhận và in dữ liệu từ Server gởi về ra màn hình.

2. UDPEchoClient.java

import java.net.*;
import java.io.*;
public class UDPEchoClient extends Object{
        public final static int serverPort = 7; // Cong mac dinh cua Echo Server
        public static void main(String[] args) {
        try {
            if (args.length ==0) { //Kiem tra tham so, là dia chi cua Server
                System.out.print("Syntax: java UDPClient HostName"); 
            return;
            }
            DatagramSocket ds = new DatagramSocket();     // Tao DatagramSocket
            InetAddress server = InetAddress.getByName(args[0]);   // Dia chi Server
            while(true) {
                InputStreamReader isr = new InputStreamReader(System.in);      
                BufferedReader br = new BufferedReader(isr);                        
                String theString = br.readLine();                                            
                byte[] data = theString.getBytes();     // Doi chuoi ra mang bytes
                // Tao goi tin gui
                DatagramPacket dp = new DatagramPacket(data,data.length,server, serverPort); 
                ds.send(dp); // Send goi tin sang Echo Server 
                byte[] buffer = new byte[6000];     // Vung dem cho du lieu nhan
                // Goi tin nhan
                DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); 
                ds.receive(incoming); // Cho nhan du lieu tu EchoServer gui ve
                // Doi du lieu nhan duoc dang mang bytes ra chuoi và in ra man hinh
                System.out.println(new String(incoming.getData(), 0, incoming.getLength())); 
            }
        }
        catch (IOException e) {
            System.err.println(e);
        }
    }
}
        Chú ý: khi thực hiện chương trình UDPEchoClient phải đưa vào đối số là địa chỉ của máy tính đang thực thi chương trình UDPEchoServer. Trong ví dụ trên, Server và Client cùng chạy trên một máy nên  địa chỉ của UDPEchoServer là  localhost (hay 127.0.0.1). Nếu UDPEchoServer chạy trên máy tính khác thì khi thực thi, ta phải biết được địa chỉ IP của máy tính  đó và cung cấp vào  đối số của chương trình. Chẳng hạn, khi UDPEchoServer  đang phục vụ trên máy tính  ở  địa chỉ 172.18.250.211, ta sẽ thực thi UDPEchoClient theo cú pháp sau:

        java UDPEchoClient 172.18.250.211
More about

Java: Xây dựng chương trình Client - Server ở chế độ có nối kết (TCP)

Người đăng: share-nhungdieuhay

         
 Dịch vụ Echo được thiết kế theo kiến trúc Client-Server sử dụng Socket làm phương tiện giao tiếp. Cổng mặc định dành cho Echo Server là 7, bao gồm cả hai chế độ có nối kết và không nối kết.
Chương trình TCPEchoClient sẽ nối kết đến EchoServer ở chế độ có nối kết, lần lượt gửi đến Echo Server 10 ký tự từ ‘0’ đến '9', chờ nhận kết quả trả về và hiển thị chúng ra màn hình.

1. Lớp TCPEchoClient.java
import java.io.*;
import java.net.Socket;
public class TCPEchoClient{
        public static void main(String args[]){
               try{
                       Socket s = new Socket(args[0],7);
                       InputStream is = s.getInputStream();
                       OutputStream os = s.getOutputStream();
                       for(int i='0';i<='9';i++){
                              os.write(i);
                              int ch = is.read();
                              System.out.print((char)ch);
                       }                      
               }
               catch(IOException ie){
                       System.out.print("Error: " +ie);
               }
        }
} 
        Chương trình STCPEchoServer cài  đặt một Echo Server phục vụ tuần tự  ở chế  độ có nối kết. Server lắng nghe trên cổng mặc định số 7.

2. Lớp STCPEchoServer.java  (Server phục vụ tuần tự)
import java.net.*;
import java.io.*;
public class STCPEchoServer{
        public final static int defaultPort = 7;
        public static void main(String[] args){
        try{
               ServerSocket ss = new ServerSocket(defaultPort);
                while (true) {
                    try { 
                        Socket s = ss.accept(); 
                        OutputStream os = s.getOutputStream();
                        InputStream is = s.getInputStream();
                        int ch=0;
                        while(true) { 
                            ch = is.read();
                            if(ch == -1) break;
                            os.write(ch);
                      } 
                        s.close(); 
                    } 
                    catch (IOException ie) {
                        System.err.println("Connection Error: "+ie);
                    } 
                } 
         }
         catch (IOException ie) {
               System.err.println("Server Creation Error:"+ie);
         }
        }
}   
        Hai chương trình này có thể nằm trên hai máy khác nhau. Trong trường hợp đó khi thực hiện chương trình TCPEchoClient phải chú ý nhập đúng địa chỉ IP của máy tính đang chạy chương trình STCPEchoServer. Xem địa chỉ IP của một máy tính Windows bằng lệnh ipconfig.
3. Lớp PTCPEchoServer.java (Server phục vụ song song)
import java.net.*;
import java.io.*;
public class PTCPEchoServer {
    public final static int defaultPort = 7; // Cong mac dinh
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(defaultPort); //Tao socket cho server
            while (true) {
                try {
                    Socket s = ss.accept(); // Lang nghe cac yeu cau ket noi
                    RequestProcessing rp = new RequestProcessing(s); // Tao phan xu ly 
                    rp.start(); // Khoi dong phan xu ly cho Client hien tai
                } 
                catch (IOException e) {
                    System.out.println("Connection Error: "+e);
                } 
            }
        }
        catch (IOException e) {
            System.err.println("Create Socket Error: "+e);
        } 
    } 
}
class RequestProcessing extends Thread {
    Socket channel; //Socket cua kenh ao noi voi Client hien tai
    public RequestProcessing(Socket s){
        channel = s; // Nhan Socket cua kenh ao noi voi Client
    }
    public void run() {
        try {
            OutputStream os = channel.getOutputStream();
            InputStream is = channel.getInputStream();
            while (true) {
                int n = is.read();        // Nhan ky tu tu Client
                if (n == -1) break;    // Thoat neu kenh ao bi xoa
                os.write(n);              //  Gui ky tu nhan duoc ve Client
            }
        }
        catch (IOException e) {
            System.err.println("Request Processing Error: "+e);
        }
    }
}
Biên dịch và thực thi chương trình. Sau đó mở thêm 2 của sổ DOS khác để thực thi chương trình TCPEchoClient nối kết tới PTCPEchoServer. Ta sẽ nhận thấy rằng PTCPEchoServer có khả năng phục vụ đồng thời nhiều Client. 
More about