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: , , ,