Archive for May, 2009

XML transformation with extension

Wednesday, May 27th, 2009

<%–
Code Revised from
       
Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback)
by Thiru Thangarathinam 

# Publisher: Wrox (January 18, 2006)
# Language: English
# ISBN: 0764596772
–%>       
       
       
       
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<%@ Import Namespace="System.Xml.XPath" %>

<script runat="server"> 
public class Discount
{
  public Discount()
  {
  }

    public string ReturnDiscount(string price)
    {
        decimal priceValue = Convert.ToDecimal(price);
        return (priceValue * 15 / 100).ToString();
    }

}
               
    void Page_Load(object sender, System.EventArgs e)
  {
        string xmlPath = MapPath("BooksWithStyle.xml");
        string xslPath = MapPath("Books_with_extensions.xsl");      
      XPathDocument xpathDoc = new XPathDocument(xmlPath);      
        XslCompiledTransform transform = new XslCompiledTransform();
        XsltArgumentList argsList = new XsltArgumentList();
        Discount obj = new Discount();
        argsList.AddExtensionObject("urn:myDiscount", obj);
        //Load the XSL stylsheet into the XslCompiledTransform object
        transform.Load(xslPath);                
        transform.Transform(xpathDoc, argsList, Response.Output);            
    }        
</script>

<%–
<?xml version=‘1.0‘?>
<bookstore>
  <book genre="A">
    <title>title 1</title>
    <author>
      <first-name>A</first-name>
      <last-name>B</last-name>
    </author>
    <price>99.99</price>
  </book>
  <book genre="B">
    <title>title 2</title>
    <author>
      <first-name>B</first-name>
      <last-name>C</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

–%>

<%–
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myDiscount="urn:myDiscount">
  <xsl:output method="html" />  
  <xsl:template match="/">
    <html>
      <title>XSL Transformation</title>
      <body>
        <h2>My Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th align="left">Title</th>
            <th align="left">Price</th>
            <th align="left">Calculated Discount</th>
          </tr>
          <xsl:for-each select="bookstore/book">
            <tr>
              <td>
                <xsl:value-of select="title"/>
              </td>
              <td>
                <xsl:value-of select="price"/>
              </td>
              <td>
                <xsl:value-of select="myDiscount:ReturnDiscount(price)" />                
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
–%>
           
       

Demonstrate toString() without an override

Wednesday, May 27th, 2009

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS “AS IS”
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun’s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun’s, and James Gosling’s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/* Demonstrate toString() without an override */
public class ToStringWithout {
  int x, y;

  /** Simple constructor */
  public ToStringWithout(int anX, int aY) {
    x = anX; y = aY;
  }

  /** Main just creates and prints an object */
  public static void main(String[] args) { 
    System.out.println(new ToStringWithout(42, 86));
  }
}

           
       

The use of message header fields

Wednesday, May 27th, 2009

 

/*
 * @(#)MessageHeadersTopic.java  1.3 02/05/02
 * 
 * Copyright (c) 2000-2002 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */
import java.sql.*;
import java.util.*;
import javax.jms.*;

/**
 * The MessageHeadersTopic class demonstrates the use of message header fields.
 * <p>
 * The program contains a HeaderProducer class, a HeaderConsumer class, a
 * display_headers() method that is called by both classes, a main method, and 
 * a method that runs the consumer and producer threads.
 * <p>
 * The producing class sends three messages, and the consuming class
 * receives them.  The program displays the message headers just before the 
 * send call and just after the receive so that you can see which ones are
 * set by the send method.
 * <p>
 * Specify a topic name on the command line when you run the program.  The 
 * program also uses a queue named "controlQueue", which should be created  
 * before you run the program.
 *
 * @author Kim Haase
 * @version 1.8, 08/18/00
 */
public class MessageHeadersTopic {
    final String  CONTROL_QUEUE = "controlQueue";
    String        topicName = null;
    int           exitResult = 0;

    /**
     * The HeaderProducer class sends three messages, setting the JMSType  
     * message header field, one of three header fields that are not set by 
     * the send method.  (The others, JMSCorrelationID and JMSReplyTo, are 
     * demonstrated in the RequestReplyQueue example.)  It also sets a 
     * client property, "messageNumber". 
     *
     * The displayHeaders method is called just before the send method.
     *
     * @author Kim Haase
     * @version 1.8, 08/18/00
     */
    public class HeaderProducer extends Thread {

        /**
         * Runs the thread.
         */
        public void run() {
            ConnectionFactory       connectionFactory = null;
            javax.jms.Connection    connection = null;
            Session                 session = null;
            Topic                   topic = null;
            MessageProducer         msgProducer = null;
            TextMessage             message = null;
            final String            MSG_TEXT = new String("Read My Headers");

            try {
                connectionFactory = 
                    SampleUtilities.getConnectionFactory();
                connection = 
                    connectionFactory.createConnection();
                session = connection.createSession(false, 
                    Session.AUTO_ACKNOWLEDGE);
                topic = SampleUtilities.getTopic(topicName, session);
            } catch (Exception e) {
                System.out.println("Connection problem: " + e.toString());
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (JMSException ee) {}
                }
              System.exit(1);
            } 
            
            try {
                /*
                 * Synchronize with consumer.  Wait for message indicating 
                 * that consumer is ready to receive messages.
                 */
                try {
                    SampleUtilities.receiveSynchronizeMessages("PRODUCER THREAD: ",
                                                              CONTROL_QUEUE, 1);
                } catch (Exception e) {
                    System.out.println("Queue probably missing: " + e.toString());
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (JMSException ee) {}
                    }
                  System.exit(1);
              }

                // Create producer.
                msgProducer = session.createProducer(topic);
                
                // First message: no-argument form of send method
                message = session.createTextMessage();
                message.setJMSType("Simple");
                System.out.println("PRODUCER THREAD: Setting JMSType to " 
                    + message.getJMSType());
                message.setIntProperty("messageNumber", 1);
                System.out.println("PRODUCER THREAD: Setting client property messageNumber to " 
                    + message.getIntProperty("messageNumber"));
                message.setText(MSG_TEXT);
                System.out.println("PRODUCER THREAD: Setting message text to: " 
                    + message.getText());
                System.out.println("PRODUCER THREAD: Headers before message is sent:");
                displayHeaders(message, "PRODUCER THREAD: ");
                msgProducer.send(message);

                /* 
                 * Second message: 3-argument form of send method;
                 * explicit setting of delivery mode, priority, and
                 * expiration
                 */
                message = session.createTextMessage();
                message.setJMSType("Less Simple");
                System.out.println("\nPRODUCER THREAD: Setting JMSType to " 
                    + message.getJMSType());
                message.setIntProperty("messageNumber", 2);
                System.out.println("PRODUCER THREAD: Setting client property messageNumber to " 
                    + message.getIntProperty("messageNumber"));
                message.setText(MSG_TEXT + " Again");
                System.out.println("PRODUCER THREAD: Setting message text to: " 
                    + message.getText());
                displayHeaders(message, "PRODUCER THREAD: ");
                msgProducer.send(message, DeliveryMode.NON_PERSISTENT,
                    3, 10000);
                
                /* 
                 * Third message: no-argument form of send method,
                 * MessageID and Timestamp disabled
                 */
                message = session.createTextMessage();
                message.setJMSType("Disable Test");
                System.out.println("\nPRODUCER THREAD: Setting JMSType to " 
                    + message.getJMSType());
                message.setIntProperty("messageNumber", 3);
                System.out.println("PRODUCER THREAD: Setting client property messageNumber to " 
                    + message.getIntProperty("messageNumber"));
                message.setText(MSG_TEXT
                    + " with MessageID and Timestamp disabled");
                System.out.println("PRODUCER THREAD: Setting message text to: " 
                    + message.getText());
                msgProducer.setDisableMessageID(true);
                msgProducer.setDisableMessageTimestamp(true);
                System.out.println("PRODUCER THREAD: Disabling Message ID and Timestamp");
                displayHeaders(message, "PRODUCER THREAD: ");
                msgProducer.send(message);
            } catch (JMSException e) {
                System.out.println("Exception occurred: " + e.toString());
                exitResult = 1;
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (JMSException e) {
                        exitResult = 1;
                    }
                }
            }
        }
    }
    
    /**
     * The HeaderConsumer class receives the three messages and calls the
     * displayHeaders method to show how the send method changed the
     * header values.
     * <p>
     * The first message, in which no fields were set explicitly by the send 
     * method, shows the default values of these fields.
     * <p>
     * The second message shows the values set explicitly by the send method.
     * <p>
     * The third message shows whether disabling the MessageID and Timestamp 
     * has any effect in the current JMS implementation.
     *
     * @author Kim Haase
     * @version 1.8, 08/18/00
     */
    public class HeaderConsumer extends Thread {
 
        /**
         * Runs the thread.
         */
        public void run() {
            ConnectionFactory       connectionFactory = null;
            javax.jms.Connection    connection = null;
            Session                 session = null;
            Topic                   topic = null;
            MessageConsumer         msgConsumer = null;
            final boolean           NOLOCAL = true;
            TextMessage             message = null;

            try {
                connectionFactory =  
                    SampleUtilities.getConnectionFactory();
                connection = 
                    connectionFactory.createConnection();
                session = connection.createSession(false, 
                    Session.AUTO_ACKNOWLEDGE);
                topic = SampleUtilities.getTopic(topicName, session);
            } catch (Exception e) {
                System.out.println("Connection problem: " + e.toString());
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (JMSException ee) {}
                }
              System.exit(1);
            } 
            
            /*
             * Create consumer and start message delivery.
             * Send synchronize message to producer.
             * Receive the three messages.
             * Call the displayHeaders method to display the message headers.
             */
            try {
                msgConsumer = 
                    session.createConsumer(topic, null, NOLOCAL);
                connection.start();

                // Let producer know that consumer is ready.
                try {
                    SampleUtilities.sendSynchronizeMessage("CONSUMER THREAD: ",
                                                            CONTROL_QUEUE);
                } catch (Exception e) {
                    System.out.println("Queue probably missing: " + e.toString());
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (JMSException ee) {}
                    }
                  System.exit(1);
              }

                for (int i = 0; i < 3; i++) {
                    message = (TextMessage) msgConsumer.receive();
                    System.out.println("\nCONSUMER THREAD: Message received: " 
                        + message.getText());
                    System.out.println("CONSUMER THREAD: Headers after message is received:");
                    displayHeaders(message, "CONSUMER THREAD: ");
                }
            } catch (JMSException e) {
                System.out.println("Exception occurred: " + e.toString());
                exitResult = 1;
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (JMSException e) {
                        exitResult = 1;
                    }
                }
            }         
        }
    }
    
    /**
     * Displays all message headers.  Each display is in a try/catch block in
     * case the header is not set before the message is sent.
     *
     * @param message  the message whose headers are to be displayed
     * @param prefix  the prefix (producer or consumer) to be displayed
     */
    public void displayHeaders (Message message, String prefix) {
        Destination  dest = null;      
        int          delMode = 0;
        long         expiration = 0;
        Time         expTime = null;
        int          priority = 0;
        String       msgID = null;
        long         timestamp = 0;
        Time         timestampTime = null;
        String       correlID = null;
        Destination  replyTo = null;
        boolean      redelivered = false;
        String       type = null;
        String       propertyName = null;
        
        try {
            System.out.println(prefix + "Headers set by send method: ");
            
            // Display the destination (topic, in this case).
            try {
                dest = message.getJMSDestination();
                System.out.println(prefix + " JMSDestination: " + dest);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the delivery mode.
            try {
                delMode = message.getJMSDeliveryMode();
                System.out.print(prefix);
                if (delMode == DeliveryMode.NON_PERSISTENT) {
                    System.out.println(" JMSDeliveryMode: non-persistent");
                } else if (delMode == DeliveryMode.PERSISTENT) {
                    System.out.println(" JMSDeliveryMode: persistent");
                } else {
                    System.out.println(" JMSDeliveryMode: neither persistent nor non-persistent; error");
                }
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            /*
             * Display the expiration time.  If value is 0 (the default),
             * the message never expires.  Otherwise, cast the value
             * to a Time object for display.
             */
            try {
                expiration = message.getJMSExpiration();
                System.out.print(prefix);
                if (expiration != 0) {
                    expTime = new Time(expiration);
                    System.out.println(" JMSExpiration: " + expTime);
                } else {
                    System.out.println(" JMSExpiration: " + expiration);
                }
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the priority.
            try {
                priority = message.getJMSPriority();
                System.out.println(prefix + " JMSPriority: " + priority);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the message ID.
            try {
                msgID = message.getJMSMessageID();
                System.out.println(prefix + " JMSMessageID: " + msgID);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            /*
             * Display the timestamp.
             * If value is not 0, cast it to a Time object for display.
             */
            try {
                timestamp = message.getJMSTimestamp();
                System.out.print(prefix);
                if (timestamp != 0) {
                    timestampTime = new Time(timestamp);
                    System.out.println(" JMSTimestamp: " + timestampTime);
                } else {
                    System.out.println(" JMSTimestamp: " + timestamp);
                }
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the correlation ID.
            try {
                correlID = message.getJMSCorrelationID();
                System.out.println(prefix + " JMSCorrelationID: " + correlID);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
           // Display the ReplyTo destination.
           try {
                replyTo = message.getJMSReplyTo();
                System.out.println(prefix + " JMSReplyTo: " + replyTo);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the Redelivered value (usually false).
            System.out.println(prefix + "Header set by JMS provider:");
            try {
                redelivered = message.getJMSRedelivered();
                System.out.println(prefix + " JMSRedelivered: " + redelivered);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display the JMSType.
            System.out.println(prefix + "Headers set by client program:");
            try {
                type = message.getJMSType();
                System.out.println(prefix + " JMSType: " + type);
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
            
            // Display any client properties.
            try {
                for (Enumeration e = message.getPropertyNames(); e.hasMoreElements() ;) {
                    propertyName = new String((String) e.nextElement());
                    System.out.println(prefix + " Client property " 
                        + propertyName + ": " 
                        + message.getObjectProperty(propertyName)); 
                }
            } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
                exitResult = 1;
            }
        } catch (Exception e) {
                System.out.println(prefix + "Exception occurred: " 
                    + e.toString());
            exitResult = 1;
        }
    }

    /**
     * Instantiates the consumer and producer classes and starts their
     * threads.
     * Calls the join method to wait for the threads to die.
     * <p>
     * It is essential to start the consumer before starting the producer.
     * In the send/subscribe model, a consumer can ordinarily receive only 
     * messages sent while it is active.
     */
    public void run_threads() {
        HeaderConsumer   headerConsumer = new HeaderConsumer();
        HeaderProducer   headerProducer = new HeaderProducer();

        headerConsumer.start();
        headerProducer.start();
        try {
            headerConsumer.join();
            headerProducer.join();
        } catch (InterruptedException e) {}
    }
    
    /**
     * Reads the topic name from the command line, then calls the
     * run_threads method to execute the program threads.
     *
     * @param args  the topic used by the example
     */
    public static void main(String[] args) {
        MessageHeadersTopic  mht = new MessageHeadersTopic();

        if (args.length != 1) {
          System.out.println("Usage: java MessageHeadersTopic <topic_name>");
          System.exit(1);
      }
        mht.topicName = new String(args[0]);
        System.out.println("Topic name is " + mht.topicName);

      mht.run_threads();
      SampleUtilities.exit(mht.exitResult); 
    }
}

        

Select Records Using PreparedStatement

Monday, May 25th, 2009

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectRecordsUsingPreparedStatement {
  public static Connection getConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
    String username = "name";
    String password = "password";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String[] args) {
    ResultSet rs = null;
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = getConnection();
      String query = "select deptno, deptname, deptloc from dept where deptno > ?";

      pstmt = conn.prepareStatement(query); // create a statement
      pstmt.setInt(1, 1001); // set input parameter
      rs = pstmt.executeQuery();
      // extract data from the ResultSet
      while (rs.next()) {
        int dbDeptNumber = rs.getInt(1);
        String dbDeptName = rs.getString(2);
        String dbDeptLocation = rs.getString(3);
        System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        rs.close();
        pstmt.close();
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

           
       

A JavaScript Calculator

Monday, May 25th, 2009

/*
Mastering JavaScript, Premium Edition
by James Jaworski 

ISBN:078212819X
Publisher Sybex CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Doing Math</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!–
r = new Array(2)
function setStartState(){
 state="start"
 r[0] = "0"
 r[1] = "0"
 operator=""
 ix=0
}
function addDigit(n){
 if(state=="gettingInteger" || state=="gettingFloat")
  r[ix]=appendDigit(r[ix],n)
 else{
  r[ix]=""+n
  state="gettingInteger"
 }
 display(r[ix])
}
function appendDigit(n1,n2){
 if(n1=="0") return ""+n2
 var s=""
 s+=n1
 s+=n2
 return s
}
function display(s){
 document.calculator.total.value=s
}
function addDecimalPoint(){
 if(state!="gettingFloat"){
  decimal=true
  r[ix]+="."
  if(state=="haveOperand" || state=="getOperand2") r[ix]="0."
  state="gettingFloat"
  display(r[ix])
 }
}
function clearDisplay(){
 setStartState()
 display(r[0])
}
function changeSign(){
 if(r[ix].charAt(0)=="-") r[ix]=r[ix].substring(1,r[ix].length)
 else if(parseFloat(r[ix])!=0) r[ix]="-"+r[ix]
 display(r[ix])
}
function setTo(n){
 r[ix]=""+n
 state="haveOperand"
 decimal=false
 display(r[ix])
}
function calc(){
 if(state=="gettingInteger" || state=="gettingFloat" ||
  state=="haveOperand"){
  if(ix==1){
   r[0]=calculateOperation(operator,r[0],r[1])
   ix=0
  }
 }else if(state=="getOperand2"){
  r[0]=calculateOperation(operator,r[0],r[0])
  ix=0
 }
 state="haveOperand"
 decimal=false
 display(r[ix])
}
function calculateOperation(op,x,y){
 var result=""
 if(op=="+"){
  result=""+(parseFloat(x)+parseFloat(y))
 }else if(op=="-"){
  result=""+(parseFloat(x)-parseFloat(y))
 }else if(op=="*"){
  result=""+(parseFloat(x)*parseFloat(y))
 }else if(op=="/"){
  if(parseFloat(y)==0){
   alert("Division by 0 not allowed.")
   result=0
  }else result=""+(parseFloat(x)/parseFloat(y))
 }
 return result
}
function performOp(op){
 if(state=="start"){
  ++ix
  operator=op
 }else if(state=="gettingInteger" || state=="gettingFloat" ||
  state=="haveOperand"){
  if(ix==0){
   ++ix
   operator=op
  }else{
   r[0]=calculateOperation(operator,r[0],r[1])
   display(r[0])
   operator=op
  }
 }
 state="getOperand2"
 decimal=false
}
function applyFunction(){
 var selectionList=document.calculator.functions
 var selIX=selectionList.selectedIndex
 var sel=selectionList.options[selIX].value
 if(sel=="abs") r[ix]=Math.abs(r[ix])
 else if(sel=="acos") r[ix]=Math.acos(r[ix])
 else if(sel=="asin") r[ix]=Math.asin(r[ix])
 else if(sel=="atan") r[ix]=Math.atan(r[ix])
 else if(sel=="ceil") r[ix]=Math.ceil(r[ix])
 else if(sel=="cos") r[ix]=Math.cos(r[ix])
 else if(sel=="exp") r[ix]=Math.exp(r[ix])
 else if(sel=="floor") r[ix]=Math.floor(r[ix])
 else if(sel=="log") r[ix]=Math.log(r[ix])
 else if(sel=="sin") r[ix]=Math.sin(r[ix])
 else if(sel=="sqrt") r[ix]=Math.sqrt(r[ix])
 else r[ix]=Math.tan(r[ix])
 decimal=false
 display(r[ix])
}
// –></SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript"><!–
setStartState()
// –></SCRIPT>
<H1>Doing Math</H1>
<FORM NAME="calculator">
<TABLE BORDER="BORDER" ALIGN="CENTER">
<TR>
<TD COLSPAN="6"><INPUT TYPE="TEXT" NAME="total" VALUE="0"
 SIZE="44"></TD></TR>
<TR>
<TD><INPUT TYPE="BUTTON" NAME="n0" VALUE="   0   " ONCLICK="addDigit(0)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n1" VALUE="   1   " ONCLICK="addDigit(1)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n2" VALUE="   2   " ONCLICK="addDigit(2)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="equals" VALUE="  =   " ONCLICK="calc()"></TD>
<TD ROWSPAN="1"><INPUT TYPE="BUTTON" NAME="clearField" VALUE="    Clear   " ONCLICK="clearDisplay()"></TD>
<TD COLSPAN="1"><INPUT TYPE="BUTTON" NAME="ln2" VALUE="      ln2       " ONCLICK="setTo(Math.LN2)"></TD></TR>
<TR><TD><INPUT TYPE="BUTTON" NAME="n3" VALUE="   3   " ONCLICK="addDigit(3)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n4" VALUE="   4   " ONCLICK="addDigit(4)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n5" VALUE="   5   " ONCLICK="addDigit(5)"></TD>
<TD COLSPAN="1" ROWSPAN="1"><INPUT TYPE="BUTTON" NAME="sign" VALUE=" +/- " ONCLICK="changeSign()"></TD>
<TD ROWSPAN="1">
<INPUT TYPE="BUTTON" NAME="sqrt2" VALUE="  sqrt(2)   " ONCLICK="setTo(Math.SQRT2)"></TD>
<TD COLSPAN="1" ROWSPAN="1">
<INPUT TYPE="BUTTON" NAME="ln10" VALUE="     ln10     " ONCLICK="setTo(Math.LN10)"></TD></TR>
<TR>
<TD><INPUT TYPE="BUTTON" NAME="n6" VALUE="   6   " ONCLICK="addDigit(6)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n7" VALUE="   7   " ONCLICK="addDigit(7)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="n8" VALUE="   8   " ONCLICK="addDigit(8)"></TD>
<TD COLSPAN="1" ROWSPAN="1">
<INPUT TYPE="BUTTON" NAME="pi" VALUE=" pi  " ONCLICK="setTo(Math.PI)"></TD>
<TD COLSPAN="1" ROWSPAN="1">
<INPUT TYPE="BUTTON" NAME="sqrt12" VALUE="sqrt(1/2) " ONCLICK="setTo(Math.SQRT1_2)"></TD>
<TD COLSPAN="1" ROWSPAN="1">
<INPUT TYPE="BUTTON" NAME="log2e" VALUE="  log2(e)  " ONCLICK="setTo(Math.LOG2E)"></TD></TR>
<TR>
<TD><INPUT TYPE="BUTTON" NAME="n9" VALUE="   9   " ONCLICK="addDigit(9)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="decimal" VALUE="   .    " ONCLICK="addDecimalPoint()"></TD>
<TD><INPUT TYPE="BUTTON" NAME="plus" VALUE="   +   " ONCLICK="performOp(’+’)"></TD>
<TD COLSPAN="1" ROWSPAN="1"><INPUT TYPE="BUTTON" NAME="e" VALUE=" e   " ONCLICK="setTo(Math.E)"></TD>
<TD COLSPAN="1" ROWSPAN="1"><INPUT TYPE="BUTTON" NAME="random" VALUE="Random"
 ONCLICK="setTo(Math.random())"></TD>
<TD COLSPAN="1" ROWSPAN="1"><INPUT TYPE="BUTTON" NAME="log10e" VALUE="log10(e)  " ONCLICK="setTo(Math.LOG10E)"></TD></TR>
<TR>
<TD><INPUT TYPE="BUTTON" NAME="minus" VALUE="   -    " ONCLICK="performOp(’-’)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="multiply" VALUE="    X  " ONCLICK="performOp(’*’)"></TD>
<TD><INPUT TYPE="BUTTON" NAME="divide" VALUE="    /   " ONCLICK="performOp(’/’)"></TD>
<TD COLSPAN="3" ROWSPAN="1"><B>Functions: </B>
<SELECT NAME="functions" SIZE="1">
<OPTION VALUE="abs" SELECTED="SELECTED">abs(x)</OPTION>
<OPTION VALUE="acos">acos(x)</OPTION>
<OPTION VALUE="asin">asin(x)</OPTION>
<OPTION VALUE="atan">atan(x)</OPTION>
<OPTION VALUE="ceil">ceil(x)</OPTION>
<OPTION VALUE="cos">cos(x)</OPTION>
<OPTION VALUE="exp">exp(x)</OPTION>
<OPTION VALUE="floor">floor(x)</OPTION>
<OPTION VALUE="log">log(x)</OPTION>
<OPTION VALUE="sin">sin(x)</OPTION>
<OPTION VALUE="sqrt">sqrt(x)</OPTION>
<OPTION VALUE="tan">tan(x)</OPTION>
</SELECT>
<INPUT TYPE="BUTTON" NAME="apply" VALUE="Apply"
 onClick="applyFunction()"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>