Wednesday, July 13, 2011

StudyNote -- [R] Use R to calculate the ROC area

#Suppose I have a file name pred200 in the path "/Users/Sha/" and inside this file there are two columns, one is 'prediction' the other is 'label'.
data <- read.table("/Users/Sha/pred200",sep=" ",header=TRUE)
#Read data from file, inside the file each row is separated by a 'space' and there is a header in the file. A header is the name of the column.
pred <- prediction(data$predictions, data$labels)
# transform the metric to variable pred
perf <- performance(pred, "tpr", "fpr")
perf.auc <- performance(pred, "auc")
perf.auc.areas <- slot(perf.auc, "y.values")

Labels: ,

Tuesday, April 26, 2011

StudyNote--X--JAVA--I

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trans;
import java.io.*;
import java.util.regex.*;
import java.util.LinkedList;
import java.lang.Thread.*;
import java.util.concurrent.locks.ReentrantLock;
/**
 *
 * @author sc
 */
//this is a stack which length is only 2
 class ProductTable {
//define a LinkedList and then will be used as the stac
    public LinkedList <String>products = new LinkedList<String>();
//this is the function to add data into LinkedList,synchronized is the key word used with lock
    public synchronized void addProduct(String context){
      //if the stack is full,the producer should wait until there is a space
        while(this.products.size()>=2){
            try {
                wait();
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.products.addLast(context);
       //tell other producer thread they can use this stack now
        this.notifyAll();
    }
//this function is to get data from the stack
    public synchronized String getProduct() {
     //if this stack is empty,consumer should wait until some producer filled it
        while(this.products.size()<= 0){
            try {
                wait();
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        String context =this.products.removeFirst();
        this.notifyAll();//tell other consumer thread they can use this stack now
        return context;
    }
}
//this is producer function that implement Runnable function
 class Producer implements Runnable {
    private ProductTable productTable;
    private String context;
    private File file;
    private BufferedReader input;
    //initialize this producer thread 
    public Producer(ProductTable productTable,String filename) {
        this.productTable = productTable;
        this.file=new File(filename);//bind the file with filename
        if(this.file.exists()){
            try{
                this.input = new BufferedReader(new FileReader(this.file));
            }
           //this is required to catch IOException
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
        else{
            System.err.println("Does not exist!");
        }
    }
    @Override//override the Runnable run() function
    public void run(){
        try{
        //each time read one line from the file
             while((this.context = this.input.readLine())!=null){
                this.productTable.addProduct(context);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                this.input.close();//when all data is read,close the file
               //send a signal to consumer to tell it the producer is terminated 
                this.productTable.addProduct("OVER");
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
}
//this is the consumer thread class
class consumerDoc implements Runnable{
    private ProductTable productTable;
    public StringBuffer[] buffer;
    private String str;
    private String regex;
    private Pattern p;
    private Matcher m;
    public int count=0;
    public consumerDoc(ProductTable productTable){
        this.productTable = productTable;
        this.str=null;
       //this is the pattern match,regression
        this.regex="(.*?)(, size)\\ (.+?)\\ [(^](.*?)\\ words(.*?)\\:\\ (.*)";
        this.p= Pattern.compile(this.regex);
    }
    @Override
    public void run(){
        try{
            while(true){
                try{
                    Thread.sleep(1);//thread sleep
                    this.str=productTable.getProduct();//get a data line from the stack
                   //if meets "OVER" means producer is terminated and this is the end of the stack,consumer can terminated itself
                    if(this.str.equals("OVER")){
                        productTable.addProduct("OVER");//put back to end other threads
                       return;
                    }
                    this.m=this.p.matcher(this.str);
                    while(m.find()){
                         //invoke another method and add the filtered information into output data structure 
                        setValue(m.group(1),m.group(4),m.group(6));
                    }
              //must catch InterruptedException in Runnable run() function
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void setValue(String A,String B,String C){
    //this is Main static variable to be invoked here
    // not use append twice because of the multi-threads issue
        Main.docBuffer[0].append(m.group(1)+"\n");//size
        Main.docBuffer[1].append(m.group(4)+"\n");//words
        Main.docBuffer[2].append(m.group(6)+"\n");//name
    }
}
//this is main class
public class Main {
   //three static variables to be invoked, as Runnable has no return method,use this way to get Runnable results
    public static LinkedList<String> list = new LinkedList<String>();
    public static StringBuffer[] docBuffer=new StringBuffer[3];
    public static StringBuffer[] featureBuffer=new StringBuffer[2];
    /**
     * @param args the command line arguments
     */
     public static void main(String[] args) throws Exception{
        // TODO code application logic here
        //Use currentTimeMillis() to read current time to measure program proformance
        long s=System.currentTimeMillis();
        for(int i=0;i<3;i++){
            docBuffer[i]=new StringBuffer();
        }
        featureBuffer[0]=new StringBuffer();
        featureBuffer[1]=new StringBuffer();
        ProductTable queueA=new ProductTable();
        Producer producerA=new Producer(queueA, "C:\\DocInfo.txt");
       //start 20 consumer threads to handle the data 
       consumerDoc[] consumerA=new consumerDoc[20];
       for(int i=0;i<20;i++){
            consumerA[i]=new consumerDoc(queueA);//initialize the threads
        }
        Thread threadRQA1=new Thread(producerA);
        Thread[] threadRQA2=new Thread[20];
        for(int i=0;i<20;i++){
            threadRQA2[i]=new Thread(consumerA[i]);
        }
        threadRQA1.start();//start the thread
        for(int i=0;i<20;i++){
            threadRQA2[i].start();
        }
        threadRQA1.join();//only threadRQA1 complete can the rest runs
       for(int i=0;i<20;i++){
            threadRQA2[i].join();
        }//wait for all threads ends
        long f=System.currentTimeMillis();
        System.out.println("Running time is :"+(f-s));
    }
}
**Note to end producer and consumer thread,one should have signal transferred and end according to the signal.Sometimes,multi-threads performance not much better than single thread as frequently access IO would possibly reduce the speed and when use multi-threads, the data order is a big issue that should be considered.

Labels: ,

Wednesday, April 06, 2011

StudyNote--IX--LaTex--III

% THIS IS SIGPROC-SP.TEX - VERSION 3.1
% WORKS WITH V3.2SP OF ACM_PROC_ARTICLE-SP.CLS
% APRIL 2009
%
% It is an example file showing how to use the 'acm_proc_article-sp.cls' V3.2SP
% LaTeX2e document class file for Conference Proceedings submissions.
% ----------------------------------------------------------------------------------------------------------------
% This .tex file (and associated .cls V3.2SP) *DOES NOT* produce:
%       1) The Permission Statement
%       2) The Conference (location) Info information
%       3) The Copyright Line with ACM data
%       4) Page numbering
% ---------------------------------------------------------------------------------------------------------------
% It is an example which *does* use the .bib file (from which the .bbl file
% is produced).
% REMEMBER HOWEVER: After having produced the .bbl file,
% and prior to final submission,
% you need to 'insert'  your .bbl file into your source .tex file so as to provide
% ONE 'self-contained' source file.
%
% Questions regarding SIGS should be sent to
% Adrienne Griscti ---> griscti@acm.org
%
% Questions/suggestions regarding the guidelines, .tex and .cls files, etc. to
% Gerald Murray ---> murray@hq.acm.org
%
% For tracking purposes - this is V3.1SP - APRIL 2009

\documentclass{acm_proc_article-sp}
#use acm_proc_article-sp template
\usepackage[timestamp,first]{draftcopy}
#this package enable a draft watermark on the background of the first page.Also we can use [timestamp,all]
\usepackage{hyperref}
#enable url used as a reference 
\usepackage{natbib}
#enable reference label marked in an order
\draftcopyVersion{Draft}
# use the draft watermark
\begin{document}
\bibliographystyle{unsrt}
#Entries are not ordered alphabetically, but in the order they are first referenced
\title{Active learning for biased training data\titlenote{ This is an honours thesis.}}
#titlenote
\numberofauthors{1}
#The number of authors share the affiliation
\author{
\alignauthor
SKSC\
\affaddr{School}\\
\affaddr{Australia}\\
\email{somewhere@somewhere.com}\\
}
\date{6 April 2011}
\maketitle
\begin{abstract}
This is the abstract
\end{abstract}

\terms{Honours thesis,Algorithms,Machine Learning}
# This is how to use the terms
\keywords{Active Learning,Similarity}
# How to generate the keyword section
\section{Introduction}
A training set is a set of data used in various areas of information science to discover potentially predictive relationships. Training sets are used in artificial intelligence, machine learning, genetic programming, intelligent systems, and statistics.\cite{wikiTraingSet}\\
\begin{itemize}
  \item 
       First Item
  \item
      Second Item
  \item
      Three Item
\end{itemize}
\newpage
#generate a new page manually
\section{background}
\subsection{Active Learning Scenarios}
\subsubsection{Membership query synthesis\cite{angluin1988queries}}
\subsubsection{stream-based selective sampling}
#several subsections and subsubsections inside.
\section{My Work}
   \subsection{Description}
      This is my description.
   \subsection{Evaluation}
      This is my evalution section
   \section{Conclusions}
      This is my conclusion part

\bibliography{reference}
# This should be .bib file name, no extension required
\balancecolumns
# ensure balanced column heights on the last page
\end{document}

Labels: ,

Tuesday, April 05, 2011

StudyNote-VIII--LaTex II

\documentclass[a4paper,12pt]{article}
\usepackage[top=1in, bottom=1in, left=1.25in, right=1.25in]{geometry}
\usepackage{graphicx}
\usepackage{multicol}

\begin{document}
\title{the title}
\date{}
\author{SKSC}
\maketitle

\begin{abstract}
\small{}
This is the abstract of this article.
\end{abstract}
\section{CAFFEINE}
This is the general structure of a CAFFEINE canonical form basis function. 
\begin{figure}[htp]
  \centering #put the image in the center
  \includegraphics[width=0.45\textwidth]{test.eps}
\end{figure}
#This is the way to present picture in LaTex. Latex can receive jpg,png and some other extension files.However the best is always the eps.To convert from jpg/png or other image file into eps, we can use bmeps command. bmeps file.jpg file.eps
\begin{figure}[h]
\begin{minipage}[t]{0.45\linewidth}
\centering
\includegraphics[width=\textwidth]{SRG.eps}
\caption{SR system used context-free grammar}
\end{minipage}
\hfill
\begin{minipage}[t]{0.45\linewidth}
\centering
\includegraphics[width=\textwidth]{gr.eps}
\caption{CAFFEINE used grammar}
\end{minipage}
\end{figure}
# this is a way to insert reference
\begin{thebibliography}{Reference}
\bibitem 
JJ Page and William B. Langdon and Riccardo Poli,Smooth Uniform Crossover with Smooth Point Mutation in Genetic Programming: A Preliminary Study,1999,Proceedings of the Second European Workshop on Genetic Programming
\end{thebibliography}
\end{document}

Labels: ,

Sunday, March 27, 2011

StudyNote-VII LaTex I

\documentclass[a4paper,12pt]{article}
#Every LaTex script should be started with the syntax.[] is an option, here I say I want to use A4 paper and 12pt font, actually however it is default. Inside{}is a required value, we can choose from article, resume, book,report and so on. #
\setlength{\topmargin}{-1.5 in}
\setlength{\textheight}{11 in} 
\setlength{\headsep}{0.2in}
\setlength{\headheight}{12pt}
\setlength{\footskip}{1pt}
#All above are to set LaTex page layout, more information can refer to wikipedia http://en.wikibooks.org/wiki/LaTeX/Page_Layout

\usepackage{threeparttable}
#It is the support package for threeparttable, threeparttable package like its name suggests, can be divided into three parts, the caption, the tabular and the tablenotes

\begin{document}
\title{First Assignment of Data Mining} # For article document,this is the way to establish the title.
\date{}#Nothing in {} means not show date, also we can say data{\today} which shows today's date
\author{SKSC}
\maketitle# This is the must required script which set up the title, date and author and other information if there is

\begin{table}[!htbp]
# this is to start a table block, h=here, t=top,b=bottom,p=page-of-its-own
\begin{threeparttable}
 \caption{Comparision of ZeroR,OneR, J48 and IBK}
#Set table caption
\begin{tabular}{|c|c|c|c|c|}
#This is to draw a table, | means whether there is a vertical line , we have three options to including c
c--central-justified column
l--left-justified column
r--right-justified column
\hline # draw a line
                                         &ZeroR       & OneR         & J48            & IBK  \\
# Here we have five columns,& is used to separate cells in a row
\hline
Training Error                    &138/214    & 82/214       & 8/214        & 0\\
\hline
Training Error Percentage  & 64.486\% & 38.3178\% & 3.7383\%  & 0 \\
# should add \ before % is we want to input percentage
\hline
Cross-valiadation Error     &138/214     & 92/214       & 71/214     & 63/214\\
# double \ has the same use like \newline
\hline
Cross-validation Error Percentage &64.486\%& 42.9907\% &33.1776\%&29.4393\%\\
\hline
\end{tabular}
\begin{tablenotes} # Begin a table note
  \item[]  
\vspace{0 in}\tiny{}#The space between note and table is 0 in and the word tiny, here tiny{} we have several choices
\tiny
\scriptsize
\footnotesize
\small
\normalsize (default)
\large
\Large (capital "L")
\LARGE (all caps)
\huge
\Huge (capital "H")
Overall, training error is not greater than cross-validation error among these four classifiers and the accuracy order from high to low is IBK$>$J48$>$OneR$>$ZeroR,the overfitting order from less to more is IBK$<$J48$<$OneR$<$ZeroR.ZeroR is not overfiiting but very unaccuracy,J48 and IBK are overfitting so no matter how accuracy they are, they can not be used.Although the accuracy of OneR is not that high,it is not overfitting,so it can be used in some critical ways.
# To input < or >, $<$ or $>$ is one of the way
\end{tablenotes}
\end{threeparttable}
\end{table}

\end{document}# end document

Labels: ,

Sunday, May 30, 2010

StudyNote--VI Python II

#<Copyright by sksc.me>
#<No one can copy and paste these codes without permission by sksc.me before 1st June 2010> 
import sys
import enrol
import os
def stats(argv):
    """
    This function reads command-line and display statistics about current enrolments If run with on arguments,stats will display a list of subjects,
    and the total number of students and classes for each subjects.If run with –student and a student ID, it should print a list of all the classes
    the specified student is enrolled in, including subject code and name, location and time  .
    """
    e=0
    if os.getenv('ENROLDIR'):
        Path=os.getenv('ENROLDIR')
        TempX=len(Path)
        while Path[:TempX].lower().rfind('data')!= -1 :
        #This while loop is case of path with data directory nesting.For instance: C://Pathon//data//XXX//Data//
            TempX=Path[:TempX].lower().rfind('data')
            if os.path.isfile(Path[:TempX]+'data//SUBJECTS'):
                if os.path.isfile(Path[:TempX]+'data//CLASSES'):
                    if os.path.isfile(Path[:TempX]+'data//VENUES'):
                        e=enrol.Enrol(Path[:TempX]+'data')
                        break    
    if os.path.isfile(os.getcwd()+'//data//SUBJECTS')and e==0:
        # If no useful path in ENROLDIR, search current directory
        e=enrol.Enrol(os.getcwd()+'//data')
    elif e==0:
        #If both fail,exit
        print 'No Data Files Can be Found Status'
        sys.exit(0)
    if len(argv)==1:
        #This is for command-line with no arguments
        SubjectID=e.subjects()
        for itemX in SubjectID :
            SubjectName=e.subjectName(itemX)
            ClassAmount=e.classes(itemX)
            StudentAmount=0
            for itemY in ClassAmount:
                StudentInfo=e.classInfo(itemY)
                StudentAmount=len(StudentInfo[4])+StudentAmount
            print itemX, SubjectName, '  classes: '+str(len(ClassAmount)),'  students:'+str(StudentAmount)
    elif argv[1]=='--student' and len(argv)==3:
        #This is for command-line with 2 arguments
        ClassID=e.checkStudent(argv[2])
        for itemX in ClassID:
            ClassInfo=e.classInfo(itemX)
            SubjectName=e.subjectName(ClassInfo[0])
            print itemX,'('+SubjectName+')',ClassInfo[1],'in '+ClassInfo[2]      
    else:
        print "WRONG INPUT"

stats(sys.argv)

Labels: ,

StudyNote--V Python I

#<Copyright by sksc.me>
#<No one can copy and paste these codes without permission by sksc.me before 1st June 2010>
import os
import sys
def readlines(filename):
    """
    This function returns a list of all lines in a file and ignore those
    lines that begin with #
    """
    path=open(filename)
    p=[]
    for item in path :
        if not item.startswith('#'):#This is to ignore the line which starts with '#'
            p.append(item.strip())
#This is the ignore the whilespace at the beginning and the end of the string
    path.close()
    return p
def readtable(filename):
    """
    Reads a file of colon-delimited lines and returns a list of lists,with
    each lines being represented as a list of string,split on colons
    """
    path=open(filename)
    BigP=[]
    for item in path :
        if not item.startswith('#'):
            BigP.append(item.split(':'))# split on colons
    for itemX in range(len(BigP)):
 # This loop is to ignore the whitespace in each element
        for itemY in range(len(BigP[itemX])):
            BigP[itemX][itemY]=BigP[itemX][itemY].strip()
    path.close()
    return BigP
def writelines (filename,lines):
    """
    This function writes a list of string sately to the file filename,replacing
    any content already there.In this function a temp file is used in case of
    unsafely action.
    """
    try:
        path=open('temp.SHA','w')
        for x in lines :
            path.write(x+'\n')
        path.close()
        if os.path.isfile(filename):
            os.rename(filename,'InCase.SHA')
            os.rename('temp.SHA',filename)
            os.remove('InCase.SHA')
            return 1
        else :
            os.rename('temp.SHA',filename)
            return 1
    except:
        os.remove('temp.SHA')
        os.rename('InCase.SHA',filename)
        return 0
class Enrol:
    def __init__(self,Directory):
        """
        This is the constructor.Accepts the name of the directory where the
        enrolment data is kept.And it reads data from the directory
        """
        self.__dir=Directory
        self.__readFiles()
    def __readFiles(self):
        """
        This is the function for reading data when object is constructed,it is
        invoked by __init__.And it will throw Exception when some error happens.
        It reads all data including three main files and all .roll files,if .roll
        does not exsit, it will create a new one and read it.
        """
        self.__dict={}
        try:
            self.__SubjectData=readtable(self.__dir+'//SUBJECTS')
            self.__ClassData=readtable(self.__dir+'//CLASSES')
            self.__VenuesData=readtable(self.__dir+'//VENUES')
            for readFilesX in self.__ClassData :
                if not os.path.isfile(self.__dir+'//'+readFilesX[0]+'.roll'):
                                      ClassFile=open(self.__dir+'//'+readFilesX[0]+'.roll','w')
                                      ClassFile.close()# If the file does not exist, create one
                self.__dict[readFilesX[0]]=readlines(self.__dir+'//'+readFilesX[0]+'.roll')
            return 1
        except:
            print 'No Data Files Found'
            os._exit(1)# If any error happens during this step, exit the program
    def subjects(self):
        """
        This functio returns a list of subject codes handled by the enrolment
        system and accept no argument.
        """
        p=[]
        for subjectsX in self.__SubjectData :
            p.append(subjectsX[0])
        return p
    def subjectName(self,SubjectCode):
        """
        Accept a subject code and return the name of the subject with that code,
        and None will be returned if no subject name found
        """
        for subjectNameX in self.__SubjectData :
            if subjectNameX[0]==SubjectCode :
                return subjectNameX[1]
        return None
    def classes(self,SubjectCode):
        """
        Return a list of classIDs for a particular subject.Accept one argument:
        the subject code of a subject.And it will raise KeyError if the subject
        does not exist and return 0.
        """
        try:
            p=[]
            for classesX in self.__ClassData :
                if classesX[1]==SubjectCode :
                    p.append(classesX[0])
            if len(p):
                return p
            else :
                raise KeyError  #raise KeyError if the file is not there
        except KeyError:
            return 0  #catch the KeyError and return 0
    def classInfo(self,ClassID):
        """
        Accept a string of ClassID and return information about a certain class.
        And it will Raise KeyError if the class does not the exist and return 0.
        """
        try:
            P=[]
            Status=False
            for classInfoX in self.__ClassData :
                if classInfoX[0]==ClassID :
                    Status=True
                    break
            if not Status :
                raise KeyError
            return classInfoX[1],classInfoX[2],classInfoX[3],classInfoX[4],self.__dict[ClassID]
        except KeyError :
            return 0
    def checkStudent(self,StudentID,SubjectCode='a'):
        """
        Check which classes a student is enrolled in.Accept one or two arguments.
        The first one is StudentID and the second one is SubjectCode which is an
        option.If ano subjectCode is specified,it will return a list of class codes
        the student is enrolled in.Otherwise,it return class code of the class in
        which the student in enrolled for that subject.
        """
        p=[]
        try:
            if SubjectCode=='a' :
  # set SubjectCode a default value to help check whether how many arguments are given
                for checkStudentKey in self.__dict.keys():
                    for checkStudentX in self.__dict[checkStudentKey]:
                        if checkStudentX==StudentID:
                            p.append(checkStudentKey)
                            break
                return p
            else :
                ClassID=self.classes(SubjectCode)
                for checkStudentKey in ClassID :
                    for checkStudentX in self.__dict[checkStudentKey]:
                        if checkStudentX == StudentID:
                            p.append(checkStudentKey)
                            break
                return p
        except:
            return 0
    def enrol(self,StudentID,ClassID):
        """
        Attempt to enrol a student in a class.Accept StudentID and ClassCode.
        It will return 1 if success and 0 if fails.Before attempting to enrol
        a student in a class,it attempt to check whether there is still enough
        room to accept a student.If not, it fails.If yes,it proceeds.If the
        student is enrolled in any othrt classes in the same subject as the class,
        the old enrollment will be removed and replaced by a new one.
        """
        try:
            if self.classInfo(ClassID)==0:# invoke a def to check whether the ClassID is a right one
                return 0
            else:
                for enrolX in self.__dict[ClassID]:
                    if enrolX == StudentID :
                        return 1
                for enrolY in self.__ClassData:
                    if enrolY[0] ==ClassID :
                        for enrolZ in self.__VenuesData:
                            if enrolZ[0]==enrolY[3] and str(len(self.__dict[ClassID]))==str(enrolZ[1]):
                                print 'The Class is full'
                                return 0
                self.__dict[ClassID].append(StudentID)
                self.__dict[ClassID].sort()
                for enrolX in self.__ClassData :
                    if enrolX[0] ==ClassID :
                        for enrolY in self.__ClassData :
                            if enrolY[1]==enrolX[1] and enrolY[0]!=ClassID :
                                self.__dict[enrolY[0]]=filter(lambda x: x!=StudentID,self.__dict[enrolY[0]])
                                #Delete the StudentID in any other class under same subject
                                self.__dict[enrolY[0]].sort()# sort them
                                FileNameX=self.__dir+'//'+ClassID+'.roll'
                                FileNameY=self.__dir+'//'+enrolY[0]+'.roll'
                                writelines(FileNameX,self.__dict[ClassID])
                                writelines(FileNameY,self.__dict[enrolY[0]])
                                return 1
        except:
            return 0

Labels: ,

Tuesday, May 04, 2010

StudyNote--III DML--JAVA DOM XML

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.lang.*;
import javax.xml.xpath.*;

public class DOMSearch{
public static void main(String[] arg) throws NullPointerException{
String SeriesName=null;
  if (arg.length >= 1) {
     SeriesName = arg[0];
//In Java whether input has double quotation marks or not,the outputs are the same
}else if(arg.length==0){
         System.out.println("No Series name input");
}
try{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
//Specifies that the parser produced by this code will provide support for XML namespaces,never forget this
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("TVGuide.xml");
doc.normalize();
/*可以去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象。否则你得到的DOM树可能并不如你所想象的那样。特别是在输出的时候,这个normalize()更为有用*/
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
NodeList list1=doc.getElementsByTagName("Program");
  String Name="TVGuide/Channel/Program[Series='"+SeriesName+"']/../Name/text()";
/*To combine some string for the coming XPath Search,also we can use other ways to combine strings,like StringBuilder and StringBuffer
Examples: String Name=new StringBuffer().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This example use toString() to convert StringBuffer to String in case Name can be used in the next xpath.evalute which needs String value
String Name=new StringBuilder().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This is the same as the StringBuffer example
StringBuffer is thread-safe and better to be used in multi-threads while StringBuilder is not thread-safe and it has better to be used in single-thread as it is fast.
*/
      NodeList nodelist=(NodeList)xpath.evaluate(Name,doc,XPathConstants.NODESET);
      if(nodelist.getLength()==0){
      System.out.println("Series '"+SeriesName+"' Not Found");
      }else{
      for(int i=0;i<nodelist.getLength();i++){
      System.out.println(nodelist.item(i).getNodeValue());
      String StartTime="TVGuide/Channel[Name='"+nodelist.item(i).getNodeValue()+"']/Program[Series='"+SeriesName+"']/Start/text()";
      NodeList nodelist1=(NodeList)xpath.evaluate(StartTime,doc,XPathConstants.NODESET);
      for(int j=0;j<nodelist1.getLength();j++){
  System.out.println(nodelist1.item(j).getNodeValue());
       }
      }
     }
}catch(Exception e){
e.printStackTrace();
}
}
}

Labels: , ,

StudyNote--IV DML--JAVA SAX XML

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
import java.util.regex.*;
<copyright(c) by sksc.me>
<No one can just copy and paste these codes without permission by sksc.me before 1st June 2010>
public class SAXPrint extends DefaultHandler{
   private int indent=0;
   private int CountStart=0;
   private int CountEnd=0;
   public void PrintIndent(){
  for(int i=0;i<indent;i++){
  System.out.print("|");
  }
   }
   public void startDocument() throws SAXException{
/*Here comes to a basic question.Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.* /
  System.out.println("Orders.xml");
   }
   public void startElement(String NameSpaceURI,String LocalName,String QName,Attributes attrs)throws SAXException{
          CountStart++;
  CountEnd=0;
  if(CountStart>=2){
  System.out.print("\n");
  }
   PrintIndent();
System.out.print("+-"+QName);
  if(attrs.getValue(0)!=null){
  System.out.print("  (");
  for(int i=0;i<attrs.getLength();i++){
  System.out.print(" "+attrs.getQName(i)+"="+attrs.getValue(i));
  if(i!=attrs.getLength()-1){System.out.print(",");}
  }
  System.out.print(" )");
  }
  indent++;
   }
   public void characters(char ch[], int start, int length) throws SAXException{
String data=new String(ch,start,length);
Pattern  p= Pattern.compile("\\S+?\\s");
/*This is to use java pattern match to find the long string where there is at least a whitespace inside, and only extract the first word.\\S means all kind of characters while ? means non-greedy,and \\s is representing whitespace*/
    Matcher match = p.matcher(data);
    if(match.find(0)) {
/*match.find(0) is the first word that matches the pattern,that is all what we need,enough.*/
        String MatchWord = match.group().trim();
        System.out.print(":"+MatchWord+"...");
    }else  if(!data.trim().equals(""))
       System.out.print(":"+data.trim());
/*This function returns a string with leading and trailing whitespace omitted*/
      }
   }
   public void endElement(String NameSpaceURI,String LocalName,String QName) throws SAXException{
indent--; CountStart=0; CountEnd++; if(CountEnd>=2){ System.out.print(""); }else{System.out.println();} }
   public void endDocument() throws SAXException{
   }
    public static String FileCheck(String arg) throws IOException{
  Pattern  pattern= Pattern.compile("\\S+?\\.xml");
  Matcher matcher = pattern.matcher(arg);
  if(!matcher.find()){
  System.out.println("Wrong FileExtension");
  System.exit(0);
  }
  else if(!(new File(arg)).exists()){
  System.out.println("The File Does Not Exist");
  System.exit(0);
  }
return arg;
   }
   public static void main(String arg[]) throws SAXException, IOException, ParserConfigurationException{
          if(arg.length==0){
  System.out.println("No FileName Input");
  System.exit(0);
  }
  String FileName=FileCheck(arg[0]);
  XMLReader xmlReader=XMLReaderFactory.createXMLReader();
  xmlReader.setContentHandler(new SAXPrint());
  xmlReader.parse(new InputSource(FileName));
/*This is one of  the way to read  XML file to memory.There are three ways to set up a SAX  Parser
(1)XMLReader reader=XMLReaderFactory.createXMLReader();//This is what I am using
(2)XMLReader reader=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
To code in this way,one should have had a certain class org.apache.xerces.parsers.SAXParser in class path and imported it.Otherwise it will throw a java.lang.ClassNotFoundException;
(3)DefaultHandler handler = new SAXPrint(); // Use the default (non-validating) parser
  SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidting(true);
/*Non-validating can be used if the file is well-formed,it works without regard to the actual content.On the other hand,a validating parser reads the DOCTYPE declaration and retrieves a file of definitions called DTD for the data.File can also be described with XML schema,but the syntax is different*/
try {
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(new File("orders.xml"), handler ); 
  } catch (Throwable t) {
    t.printStackTrace();
  }
*/
}
}

Labels: , , ,