Thursday, December 24, 2015

com.izforge.izpack.api.exception.CompilerException: the file version is different from the compiler version

This exception occurs when the installation version in the installation xml file is different from the IzPack version you have installed.

<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
          <installation version="5.0">

To fix it, make the version the same as the IaPack version you are using.



                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, December 18, 2015

java.sql.SQLException: Could not commit with auto-commit set on - Resolved

The "Could not commit with auto-commit set on" exception happens when the connection is automatically set auto commit to true.

To fix this, do one of the followings.

A. Set connection to auto commit false.


           Class.forName(<dbDriver>);

           Connection connection = DriverManager.getConnection(<dbURL>, <dbUser>, <dbPassword>);

             connection.setAutoCommit(false);     


B. Set the -Doracle.jdbc.autoCommitSpecCompliant=false JVM option.


             In NetBeans, right click the project, select Properties. In the pop up window, select Run on the left and enter -Doracle.jdbc.autoCommitSpecCompliant=false in the VM Options on the right.

--------------------------------------------------------------------------------
                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, December 16, 2015

java.sql.SQLException: ORA-28000: the account is locked

The account is locked when an user has tried to log into the database with wrong userID/password for times more than the number defined by the FAILED_LOGIN_ATTEMPTS parameter in the profile.

To fix this problem, log into the oracle database as dba and execute the following commands.

SQL> ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED;

SQL> ALTER USER <username> ACCOUNT UNLOCK;



                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, November 18, 2015

Java: Heap Size, Stack Size and Perm Gen / Metaspace Size

A. What are heap, stack and perm gen?


Heap is the place in the memory stores the objects created by your application. This is where garbage collection starts.

Stack is the place in the memory stores the threads generated by your application.

Permanent Generation, also known as Perm Gen or Perm, is the place in memory stores class definitions and static fields. Stuffs stored here are generally not garbage collected.

 Insufficient memory in any of the three places will cause java.lang.OutOfMemoryError. However, in java 8, the Perm Gen is replaced by Metaspace which eliminates the corresponding OutOfMemoryError unless the Metaspace is limited on purpose.

B. Set the size of heap, stack and perm gen


Heap:  use the following parameters to set the heap sizes
 
           -Xms<minSize>  for the initial heap size
          - Xmx<maxSize> for the maximum heap size

          for example: java -Xms512m -Xms2048m MyMagicPerformer.class

          For setting them in NetBeans, right click on your executable project, open the properties window, click run in the left Categories list, on the right side of the window, enter -Xms<minSize> -Xmx<maxSize> in the VM Options.

Stack: use the following parameter to set the stack sizes

          -Xss<size>

           for example: java -Xss1024k MyMagicPerformer.class

Perm Gen: use the following parameters to set the perm sizes

           -XX:PermSize=<size>  for the initial perm size
          -XX:MaxPermSize=<size>  for the maximum perm size

          for examplejava -XX:PermSize=64m -XX:MaxPermSize=128m MyMagicPerformer.class

          In java 8, the Perm Gen is replace by Metadata. By default the Metadata allocation is limited by the amount of available native memory. A new flag MaxMetaspaceSize can be used to limit the amount of native memory used for class metadata. If you don’t specify this flag, the Metaspace will dynamically re-size depending of the application demand at runtime

           -XX:MaxMetaspaceSize=<size>
          java -XX:MaxMetaspaceSize=128m MyMagicPerformer.class

C. Find out the sizes


            On Linux/Unix and Mac OSX: 
            java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

            If you would like to find out the memory sizes of a particular java program, replace the "-version" argument with the name of your java program. For example: java -XX:+PrintFlagsFinal MyMagicPerformer | grep -iE 'HeapSize|PermSize|ThreadStackSize'

           On Windows:
           java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
-----------------------------------------------------------------------------------------------
                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
    

Friday, November 6, 2015

java.net.UnknownHostException

If you are able to ping the IP address, but not able to ping the domain name, for example,

> ping 216.58.219.228
PING 216.58.219.228 (216.58.219.228) 56(84) bytes of data.
64 bytes from 216.58.219.228: icmp_seq=1 ttl=53 time=33.0 ms
64 bytes from 216.58.219.228: icmp_seq=2 ttl=53 time=32.9 ms

> ping www.google.com
ping: unknown host www.google.com

you need to update your domain name server (DNS) to add the entry for www.google.com, then update the /etc/resolv.conf file by adding the following line.

nameserver       <DNS IP address>

Or you can directly add the following line to your /etc/resolv.conf file.

www.google.com     216.58.219.228


If you cannot reach the host by pinging either the domain name or the IP address, you need to establish the connection between the host and your machine first.

-------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one?Read the book free here.

Wednesday, September 2, 2015

SQL: Order by customized sequence of values

Lets say that you have the following SQL statement.

SELECT DEPARTMENT, STATUS, NAME FROM EVENT ORDER BY DEPARTMENT, STATUS;

AND the STATUS column has such values: Initial, data collected, processing, completed. If you would like the records returned by your SQL statement to be ordered by the DEPARTMENT in alphabetic order and with each department, the events are ordered by status as listed above. You cannot use ORDER BY STATUS to achieve it for the order you want is not alphabetic.

You can achieve it by using the following SQLs.

1. SELECT DEPARTMENT, STATUS, NAME
     FROM EVENT
     ORDER BY DEPARTMENT,
              CASE STATUS WHEN 'Initial' THEN 1
                                     WHEN 'data collected' THEN 2
                                     WHEN 'processing' THEN 3
                                     WHEN 'completed' THEN 4
              ELSE 5
              END  ASC;


2. For ORACLE

     SELECT DEPARTMENT, STATUS, NAME
     FROM EVENT
     ORDER BY DEPARTMENT,
                          instr('Initial, data collected, processing, completed', STATUS);


     For MySQL

     SELECT DEPARTMENT, STATUS, NAME
     FROM EVENT
     ORDER BY DEPARTMENT,
                          FIELD (STATUS, 'Initial, data collected, processing, completed');



                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Wednesday, August 26, 2015

Java: Run a non jar execution entrance class in a jar file

If you would like to run a class containing a main method other than the default execution entrance of the jar file, you may use the following command. Use forward slash in Linux/Unix system and use backward slash in Windows system.

java -cp <path to your jar>/<jar file name>.jar  <package path of the class>.<class name>

Otherwise, if you just want ot execute the jar through its default execution entrance, the command would be the following.

java -jar <path to your jar>/<jar file name>.jar



                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, August 20, 2015

Socket getPort vs getLocalPort

The getLocalPort() method returns the port to which the socket binds to. Whereas the getPort() method returns the remote port to which the socket connects to.

For example

ServerSocket serverSocket = new ServerSocket(6045, 50, <InetAddress>);

You create a Socket using the serverSocket's InetAddress and port number to connect to it. You may use this socket to read and write or you can also use the socket returned by serverSocket.accept() to read and write. However, they have different local and remote ports.

A. Using the created socket

Socket socket = new Socket(<InetAddress>, 6045);
socket.getPort() will return the port number used in the above line which is 6045. socket.getLocalPort will return something else, lets say 53222.

To this socket, the server is remote.

B. Using the accepted socket

Socket socket2 = serverSocket.accept();
socket2.getPort() will return 53222 and socket2.getLocalPort() will return 6045.

To this socket2, the server is local.

------------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Wednesday, August 19, 2015

SQL: Find and remove / delete all the locks / deadlocks / blockers in an Oracle or PostgreSQL database

If your executing program which updates records in the database hangs, a good chance is that the record it is trying to update is locked by another program.

To prevent concurrent modification of a record, Oracle locks a record when it is being modified. However, if a program, after it has locked some records for modification, hangs due to some reason, it will cause failure or hang of other programs that need to access the records. To find out the locked records in the database, you can get the sid, serial#, status, username, osuser, machine, terminal from the session view, and the owner, object_name and object_type from the dba_objects table, and use them in conjunction with the locked_object view.

Here is the SQL:

A. Oracle


SELECT a.sid, a.serial#, a.username, a.status, a.osuser, a.machine, a.terminal,
          b.owner, b.object_id, b.object_name, b.object_type,
          c. os_user_name
From v$session a, dba_objects b, v$locked_object c
WHERE a.sid = c.session_id and b.object_id = c.object_id;

Or use the one below to get what is holding a lock on an object for which another process is waiting.

SELECT sid, serial# From v$session where sid in (select HOLDING_SESSION from DBA_BLOCKERS);

Or find only the locks that have blocked another session for at least 30 seconds

select v1.sid, v1.serial# from v$session v1 where v1.sid in (select blocking_session from v$session v2 where v2.WAIT_TIME = 0 and v2.seconds_in_wait >= 30);

To remove a lock:
ALTER SYSTEM KILL SESSION 'SID, SERIAL#';

(If not enough privilege, login as sysdba and execute the command below.

               SQL> grant alter system to userid;

                        Grant succeeded.
)

B. PostgreSQL


SELECT t.relname, l.locktype, page, virtualtransaction, pid, mode, granted
FROM pg_locks l, pg_stat_all_tables t
WHERE l.relation=t.relid order by relation asc;

SELECT p.pid, p.usename, p.datname, l.relation::regclass,
l.granted, p.query, p.query_start
FROM pg_stat_activity AS p
JOIN pg_locks AS l ON l.pid = p.pid
WHERE l.relation IN (SELECT relation FROM pg_locks WHERE granted IS FALSE)
ORDER BY l.relation;

SELECT pid, (now() - query_start) AS duration, query, state
FROM pg_stat_activity
WHERE (now() - query_start) > interval '30 seconds';

To remove the lock:
select pg_terminate_backend(<blocking_pid>);


----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, August 3, 2015

Pentaho report: displaying pentaho 0, pentaho 1, pentaho 2 ......

If a pop up appears when you open a report saying, "Missing column <column name>, do you want to remove the column from the report?"  If you choose "No", the report will display two rows with columns displaying values pentaho 0, pentaho 1, pentaho 2 .........

The way to fix it is to remove the column from the report, which does not exist in your meta data, or add such a field to your meta data.

-------------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Pentaho: Locations of pentaho log files

By default the pentaho log files are located at the following locations on your computer.

Pentaho/server/biserver-ee/logs/pentaho.log

Pentaho/server/biserver-ee/tomcat/logs/catalina.<date>.log

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Pentaho: org.pentaho.pms.core.exception.PentahoMetadataException: QueryXmlHelper.ERROR_0009 - Domain Instance returned null

The following exceptions are caused by that the meta data domain used in the Meta Data Editor and the meta data domain used in the Pentaho User Console are different.

Caused by: org.pentaho.reporting.engine.classic.core.ReportProcessingException: InteractiveAdhocReportUtils.ERROR_0002 - Unable to load report query.
at com.pentaho.iadhoc.service.b.b.a(SourceFile:113)
at com.pentaho.iadhoc.service.b.b.a(SourceFile:80)
at com.pentaho.iadhoc.service.b.k.a(SourceFile:501)
at com.pentaho.iadhoc.service.b.k.a(SourceFile:117)
at com.pentaho.iadhoc.service.InteractiveAdhocService.getThinSpec(SourceFile:157)
at com.pentaho.iadhoc.service.InteractiveAdhocService.getReportSpecificationJson(SourceFile:99)
... 88 more
Caused by: org.pentaho.pms.core.exception.PentahoMetadataException: QueryXmlHelper.ERROR_0009 - Domain Instance <Domain Name> returned null
at org.pentaho.metadata.query.model.util.QueryXmlHelper.fromXML(QueryXmlHelper.java:349)
at org.pentaho.metadata.query.model.util.QueryXmlHelper.fromXML(QueryXmlHelper.java:339)
at com.pentaho.iadhoc.service.h.a(SourceFile:64)
at com.pentaho.iadhoc.service.b.b.a(SourceFile:110)

To fix this problem: 

1. From your Pentaho Metadata Editor, click File in the top menu bar and choose Publish to Server.

2. In the pop up window, make sure that the Domain Name matches the domain name in the exception. Click OK.

Or do the following.

1. From your Pentaho Metadata Editor, click File in the top menu bar and choose Publish to Server.

2. Look for the Domain Name in the pop up window,.

3. Go to Pentaho User Console, click the Create New button, and choose Data Source

4. In the pop up window, make sure to use  the Domain Name you saw in step 2 as the Data Source Name. Continue and finish creating the data source.

5. Create your reports using the new data source.

------------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, July 16, 2015

Socket: java.net.BindException: Address already in use

java.net.BindException: Address already in use
        at java.net.PlainSocketImpl.socketBind(Native Method)
        at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
        at java.net.ServerSocket.bind(ServerSocket.java:376)

When you disconnect a socket connection and immediately use the same IP address and port number for a new socket, this exception may throw. This is because when a TCP connection is closed, the connection may remain in a timeout state for a period of time after the connection is closed, also known as the TIME_WAIT state or 2MSL wait state. It may not be possible to bind a socket to the requred socket address if there is a connection in the timeout state involving the socket address or port. However, setting the reuse address of the socket to true before binding allows the socket to be bound even though a previous connection is in a timeout state.

For example, the following code throws the exception.

      ServerSocket serverSocket = new ServerSocket(<port>);

The following code will not throw the exception.

      ServerSocket serverSocket = new ServerSocket();
      serverSocket.setReuseAddress(true);
      serverSocket.bind(new InetSocketAddress(<port>));

------------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, July 14, 2015

Java: Overridable method call in constructor

In NetBeans, the following code will give a warning: Overridable method call in constructor.

public class Reward {
      protected int baseReward = 1000;

      public Reward() {
            int reward = calculateReward(); //this line generates the warning
            System.out.println("The reward is " + reward);
      }

      protected int calculateReward() {return baseReward;}
}

This is because the calculateReward method can be override in subclasses and calling such a method in superclass constructor before the proper initiation of properties in subclasses may result in errors. Here is an example.

public class CreativeReward extends Reward {
      private int rewardAdjust = 100;

     public CreativeReward() {
           super();
     }

      public CreativeReward(int rewardAdjust) {
            this.rewardAdjust = rewardAdjust;
      }

      protected int calculateReward() {
          return baseReward + rewardAdjust;
      }

      public static void main(String[] args) {
            new CreativeReward(); //Prints 1000 instead of 1100
            new CreativeReward(50); //Prints 1000 instead of 1050
      }
}

This is because the constructor in superclass is called first, after which the constructor in subclass is called and the instance variables are initiated. Therefore, an overriden method called in superclass constructor will ignore the values assigned to the used instance variables in subclasses. Thus, in the above example the rewardAdjust used in the superclass constructor is 0 instead of 100 or 50.

-----------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Tuesday, July 7, 2015

SQL: How to replace values of a field in the select result with some other values?

Let say that you have a student table, which has a column called GroundExam to indicate if the status of the student on the ground exam required by the education board. The column is a numeric field. The following is the meaning of the values.

0 : have not taken
1 : Passed
2 : Failed

Now, you would like to query the Student table to see the status of the students on the ground exam, but you would like the result to display the string which is more understandable than the numbers.

You may use the following query.

SELECT NAME, ID,
          CASE  GroundExam WHEN 0 THEN 'Have not Taken'
                    WHEN 1 THEN 'Passed'
                     WHEN 2 THEN 'Failed'
                    END AS GroundExam
FROM Students;

----------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, June 3, 2015

NetBeans Java scroll bar (JScrollBar) does not scroll

To view a large size of data by scrolling it using the JScrollBar, one usually would put the data in a data container such as a JTextArea or a JTable, create a JScrollPane object and call the setViewportView method to set the data container to be viewed in the JScrollPane, and then set the scroll policy to be either as needed or always.

However, when you keep adding data to your data container and the newly added data goes out of the view, you try to drag the scroll bar or press the arrow at the end of  the side where the scroll bar locates, sometimes the scroll bar only moves a little bit, then stopped moving. This is because the preferred size of the data container (the JTextArea or the JTable) is set too small. The preferred size is the actual area that can be viewed in the JScrollPane. When data goes beyond this area, it is not visible and not accessible to scrolling.

If you use the GUI design of the NetBeans to build your components, the preferred size is automatically assigned, you need to make sure that it is big enough to contain all the possible data so that all the data are visible by scrolling. Or you can right click on the data container and choose the customize code to comment out the size setting code.
       
------------------------------------------------------------------------------------------------------------------------
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
--------------------------------------------------------------------------------------------------------------------------

Reference:

1. setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

Tuesday, May 19, 2015

SQL: Handle / dealing single quote / apostrophe in string

String values in a SQL is surrounded by a pair of single quotes. A single quote either starts or ends a string value. If your string has single quote in it , you need to handle it appropriately for it to work.

1.  Replace single quote contained in a string by a pair of single quotes. For example,

      SELECT * FROM FRUIT WHERE note = 'Product of Smith''s farm';
      Product of Smith's farm is replaced with Product of Smith''s farm.

      SELECT * FROM FRUIT WHERE note = '''Honey'' sweet type';
      'Honey' sweet type is replaced with ''Honey'' sweet type.

      SELECT * FROM FRUIT WHERE note = 'Product of Thomsons''';
      Product of Thomsons' is replaced with Product of Thomsonss''.


2. Single quote in string concatenation.

     SELECT 'Fruit''s name: ' || '''' || NAME || '''', PRICE FROM FRUIT;

     will return something like: Fruit's name: 'Apple'       $3.99
                                                Fruit's name: 'Orange'     $1.99


3. Replace single quote contained in a string with chr(39). For example,

     SELECT * FROM FRUIT WHERE note = 'Product of Smith' || chr(39) || 's farm';

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, May 8, 2015

SQL: select a unique/distinct subset of columns and also show the other columns - partial distinct / unique columns

For example, you have this FRUIT table in your database. (This is just an example, it contains repeating data that need to be normalized :-)).

Name          Price         Date                   Place
Apple          3.28          1/10/2015          Darloo
Apple          3.28           1/22/2015         Jumbo
Orange        2.50           1/15/2015         Darloo
Orange        2.50           1/19/2015         Jumbo

Lets say that you want to get unique Name and Price only but the result also show Date and Place. Some thing looks like this.

Apple          3.28          1/10/2015          Darloo
Orange        2.50           1/19/2015         Jumbo

If you use the SQL: SELECT unique Name, Price, Date, Place FROM FRUIT to query the table, you will get all the rows with repeating Name and Price.

You may use the following SQL to get the result you want.

SELECT Name, Price, Date, Place
FROM (
       SELECT FRUIT.*, row_number() over (partition by Name, Price order by Name)  as rn
       FROM FRUIT) FRUIT
WHERE rn = 1;

----------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, April 13, 2015

JTable: How to make a column automatically update its values when the values in the corresponding rows are changed?

If in your JTable, one column stores the value that is the result of certain calculation of the values in other columns, you can let the value of the column to be automatically updated when values in other columns are modified. This can be achieved by using the TableModelListener to monitor changes in the other columns. The following code is an example of how it is done.

import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableCalculationTest extends JFrame {
    JTable table = null;
    DefaultTableModel model = null;
    TableModelListener listener = null;

    public TableCalculationTest() {
        table = new JTable();
        model = new TableModel();
        model.addRow(new Object[] {"Apple", new Float(3.99), new Float(80), new Float(2.00), new Float(100), new Float(519.20)});
        model.addRow(new Object[] {"Apple", new Float(3.99), new Float(65.5), new Float(2.50), new Float(300), new Float(1011.35)});
        model.addRow(new Object[] {"Avacado", new Float(4.99), new Float(15), new Float(3.50), new Float(200), new Float(774.85)});
        table.setModel(model);
        table.getTableHeader().setReorderingAllowed(false);
     
        table.setDefaultRenderer(Float.class, new FloatRenderer());
        table.setDefaultEditor(Float.class, new FloatCellEditor(new JTextField()));
     
        listener = new TableChangeListener();
        model.addTableModelListener(listener);
       
        JScrollPane jsp = new JScrollPane(table);
        getContentPane().add(jsp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
 
    private class TableChangeListener implements TableModelListener {
        @Override
        public void tableChanged(TableModelEvent e){
            int row = e.getFirstRow();
            int col = e.getColumn();
            //remove the TableModelListener to avoid infinite looping
            model.removeTableModelListener(listener);
            if (col != 0){
                //do the calculation
                Float rowTotal = (Float)model.getValueAt(row, 1) * (Float)model.getValueAt(row, 2) +
                        (Float)model.getValueAt(row, 3) * (Float)model.getValueAt(row, 4);
             
                //set the corresponding field with the calculated value
                model.setValueAt(rowTotal, row, 5);
            }
            //add back the TableModelListener
            model.addTableModelListener(listener);
        }
    }
 
    private class TableModel extends DefaultTableModel{
        public TableModel() {
            setColumnIdentifiers(new Object[] {"Name", "Detail Price", "Detail Order", "WholeSale Price", "Wholesale Order", "Total Charges"});
        }
        public Object getColumnCalss(int col){
            Object type = Float.class;
            if (col == 0){
                type = String.class;
            }
            return type;
        }
     
        @Override
        public void setValueAt(Object v, int row, int col) {
            if (col != 0) {
                if (v instanceof String) {
                    super.setValueAt(Float.parseFloat((String) v), row, col);
                } else {
                    super.setValueAt((Float) v, row, col);
                }
            }
        }
    }
 
    private class FloatRenderer extends DefaultTableCellRenderer {
        JTextField field = new JTextField();
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
            if (value instanceof Float){
                field.setText(String.valueOf((Float)value));
            }
            return field;
        }
    }
 
    private class FloatCellEditor extends DefaultCellEditor{
        private JTextField field = new JTextField();
     
        public FloatCellEditor(JTextField f) {
            super(f);
            field = f;
        }
     
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column){
            if (value instanceof Float){
                JTextField field = new JTextField();
                field.setText(String.valueOf((Float)value));
            }
            return field;
        }
    }
 
    public static void main(String[] args){
        new TableCalculationTest();
    }
}
       
-------------------------------------------------------------------------------------------------------------------
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, April 2, 2015

NetBeans, SVN command returned with the following error, Can not load remote file for


When right click on the project, choose Subversion, Diff, Diff to Repository, the following error pops up.


This problem can be fixed by following the steps below.


  • Check in all your changes in the directory containing the error causing file.
  • Close NetBeans
  • Open your file explorer, make copy of the directory containing the error causing file to somewhere else, then delete the directory.
  • Open NetBeans, right on the project, select Subversion, then Update, and Update to Head.
---------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, March 31, 2015

Cursor automatically moves / jumps around when typing

When a wireless mouse is used, the cursor sometimes automatically moves to unpredictable places when typing. To fix this problem in a Windows 8 DELL computer, follow the steps below.

1. Adjust the mouse settings.

  • Open the control panel, click on "Hardware and Sound", then under "Devices and Printers" click the "Mouse" hyperlink. 
  • In the pop-up Mouse Properties window, click the link "Click to change the Dell Touchpad settings". 
  • In the pop-up window, click the mouse icon and check the "Disable Touchpad when USB Mouse present" check box. Close the window
  • Click the "Apply" button and the "OK" button.
      If step 1 does not completely fix the problem, continue to do step 2.

2. Adjust the keyboard  setting.

  • Open the control panel, click on the "Easy of Access", then under the "Easy of Access Center" click the "Change how your keyboard works" link.
  • At the bottom of the pop-up window, click the "Keyboard Settings" link.
  • In the pop-up Keyboard Properties window, select the "Speed" tab, increase the repeat delay and decrease the repeat rate by sliding the indicators to the left.
  • Click the "Apply" button and the "OK" button.
      If after step 2, the problem still exists, continue to do step 3.

3. Install the TouchFreeze. TouchFreeze can be downloaded at TouchFreeze.

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, March 10, 2015

com.jcraft.jsch.JSchException: Packet corrupt

This exception occurs when the Session is reused repeatedly in a loop where the session is disconnected intentionally or due to time out and needs to reconnect again.

For example, the following code will throw such an exception at session.connect() in the while loop.

Public class SftpTest extends Thread {
       private String username = "";
       private String password = "";
       private boolean running = true;

      public SftpTest(String user, String pass) {
            username = user;
            password = pass;
      }

      public void run() {
             try {
                    JSch jsch = new JSch();
                     Session session = jsch.getSession(username, "<your host>");
                    session.setPassword(password);
                    session.setConfig("StrictHostKeyChecking", "no");
                   session.connect();

                   Channel channel = session.openChannel("sftp");
                   channel.connect();
                    ChannelSftp sftp = (ChannelSftp) channel;

                    while (running) {
                           if (!session.isConnected()) {
                                   session.connect();
                                   channel = session.openChannel("sftp");
                             }
                            if (!channel.isConnected()) {
                                   channel.connect();
                                  sftp = (ChannelSftp) channel;
                           }

                           Vector<LsEntry> entries = sftp.ls("*.pdf");
                           for (LsEntry entry : entries) {
                                   String fileName = entry.getFilename();
                                   sftp.get(fileName, ".");
                                   sftp.rm(fileName);
                            }
                            Thread.sleep(60 * 60 * 1000);//sleep for 1 hr                        
                      }
                       sftp.exit();
                       sftp.disconnect();
                       session.disconnect();
              } catch (InterruptedException ie) {
                     ie.printStackTrace();
              } catch (SftpException fe) {
                     fe.printStackTrace();
              } catch (JSchException e) {
                    e.printStackTrace();
              }
       }

       public static void main (String[] args) {
               SftpTest test = new SftpTest("<your username>", "<your password>");
               test.start()
       }
}

The reason that such an exception is thrown is that the first time the Session is connected to the remote site, a random number called Packet is generated for the session. When the thread is having its 1 hour sleep, the session gets automatically disconnected due to no activity for a certain period of time. When the Session is disconnected, the Packet is lost. When the Session is trying to reconnect, it could not find the Packet, thus the exception is thrown.

One way to solve this problem is to not reuse the same Session. If the thread is going to sleep for awhile, disconnect the Session before going to sleep and create a new Session after sleep. The above code can be rearranged as below to avoid this exception.

Public class SftpTest extends Thread {
       private String username = "";
       private String password = "";
       private boolean running = true;

      public SftpTest(String user, String pass) {
            username = user;
            password = pass;
      }

      public void run() {
             try {
                   while (running) {
                         JSch jsch = new JSch();
                         Session session = jsch.getSession(username, "<your host>");
                         session.setPassword(password);
                         session.setConfig("StrictHostKeyChecking", "no");
                         session.connect();

                        Channel channel = session.openChannel("sftp");
                        channel.connect();
                        ChannelSftp sftp = (ChannelSftp) channel;

                        Vector<LsEntry> entries = sftp.ls("*.pdf");
                        for (LsEntry entry : entries) {
                                   String fileName = entry.getFilename();
                                   sftp.get(fileName, ".");
                                   sftp.rm(fileName);
                         }
                       sftp.exit();
                       sftp.disconnect();
                       session.disconnect();
                      Thread.sleep(60 * 60 * 1000);//sleep for 1 hr
                   } //end of while loop
             } catch (InterruptedException ie) {
                     ie.printStackTrace();
              } catch (SftpException fe) {
                     fe.printStackTrace();
              } catch (JSchException e) {
                    e.printStackTrace();
              }
       }

       public static void main (String[] args) {
               SftpTest test = new SftpTest("<your username>", "<your password>");
               test.start()
       }
}
       
----------------------------------------------------------------------------------------------------------------
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.