12/29/2009

比對並Update的SQL - MS SQL version

系統上線一陣子後因為資料日漸增多,我們會把資料切成online, offline的部分,有時會想將online更新到offline,這時我們把兩個Table的資料做比對,找出相同的資料後,更新offline。

使用下面的SQL可以更新offline資料。使用cursor。
DECLARE c Cursor FOR
  select pd.tankid, pd.bodid, pd.sampletstamp
  from newbod.dbo.tblQCThickMeasurements bod, ProcessData.dbo.tblQCThickMeasurements pd
  where bod.tankid = pd.tankid
  and bod.bodid = pd.bodid
  and bod.sampletstamp = pd.sampletstamp
  and pd.qualcopied = 0;
Open c;
IF (@@CURSOR_ROWS<>0) ---判斷cursor開啟狀況
 BEGIN  
  DECLARE @tankId VARCHAR(50), @BodId VARCHAR(50), @sampleTS Datetime;  
  Fetch NEXT FROM c INTO @tankId, @BodId, @sampleTS;

  While (@@FETCH_STATUS <> -1)--當陳述式失敗,或資料列超出結果集時停止迴圈
   BEGIN
    update ProcessData.dbo.tblQCThickMeasurements set
      qualcopied=1 
    where tankid = @tankId
    and bodid = @BodId
    and sampletstamp = @sampleTS;
    Fetch NEXT FROM c INTO @tankId, @BodId, @sampleTS;
   END;
 END;
CLOSE c;
DEALLOCATE c;
GO

比對並Update的SQL - Oracle version

系統上線一陣子後因為資料日漸增多,我們會把資料切成online, offline的部分,有時會想將online更新到offline,這時我們把兩個Table的資料做比對,找出相同的資料後,更新offline。

使用下面的SQL可以更新offline資料。
update 
    (select ol.tank_id, ol.bod_id, ol.sampletstamp, ol.qualcopied
    from hisadm.qc_cord_summ su, hisadm.qc_cord_summ_ol ol
    where su.tank_id = ol.tank_id
    and su.bod_id = ol.bod_id
    and su.sampletstamp = ol.sampletstamp
    and ol.qualcopied = 'F'
    and ol.sampletstamp <> to_date('2009/7/26 11:32:00','yyyy/MM/dd HH24:MI:SS')
    and ol.sampletstamp <> to_date('2009/12/8 19:17:00','yyyy/MM/dd HH24:MI:SS')) a set 
a.qualcopied = 'T';

當條件上出現重覆資料時,Oracle就不允許update了,需要自已將重覆測試的資料過濾,自行update不重覆的資料,會使用到cursor如同下方SQL
declare cursor c is select ol.tank_id, ol.bod_id, ol.sampletstamp, ol.qualcopied
                    from hisadm.qc_cord_summ su, hisadm.qc_cord_summ_ol ol
                    where su.tank_id = ol.tank_id
                    and su.bod_id = ol.bod_id
                    and su.sampletstamp = ol.sampletstamp
                    and ol.qualcopied = 'F'
                    and ol.sampletstamp <> to_date('2009/7/26 11:32:00','yyyy/MM/dd HH24:MI:SS')
                    and ol.sampletstamp <> to_date('2009/12/8 19:17:00','yyyy/MM/dd HH24:MI:SS');
begin
  for r_c in c loop  
      update hisadm.qc_cord_summ_ol a set
      a.qualcopied = 'T'
      where a.tank_id = r_c.tank_id
      and a.bod_id = r_c.bod_id
      and a.sampletstamp = r_c.sampletstamp;
  end loop;
end;

12/28/2009

MS SQL 2000以下版本如何做出row_num的效果?

MS SQL 2005含以上的版本有個 row_number() 可以讓使用者容易的做查詢出的資料加上序號,可是MS SQL 2000就不支援了。
由於這樣的需求簡單寫了下方的code,可以做出序號效果,前題是id欄位是唯一。
select (select count(1) from table1 c
  where c.id <= table1.id) as row_number, 
  table1.*     
from table1

11/27/2009

Oracle 找出loss的數字序列

日遇到個問題。
在table: pt_dltgls裡有location 1 ~ 500(符合條件的max location),其中有些location在輸入時漏掉了。所以要找出這裡漏掉的location,讓使用者來補回。

SQL做法:
1.Oracle語法列出1 ~ max location。
2.再minus現有的location,剩下的就是漏掉的location啦!~


Oracle SQL
Select level location
from dual 
connect by level <= (select nvl(max(location), 0) from pt_dltgls where dp_lot_id='C9J04031' and gls_status='S')
minus 
select distinct location from pt_dltgls t where dp_lot_id='C9J04031' and gls_status='S'

ps:感謝同仁Aming大力幫忙,沒有Aming還真寫不出來呢~哈~

11/25/2009

Wonder girls sing nobody in NY

How to code a class in VB.net 2005

近幾年物件導向愈來愈熱門,每個語言的概念差不多但寫法都不一樣,那要怎麼寫一個VB.net的Class呢?

Imports Microsoft.VisualBasic
Imports System.Data.OleDb
Imports System.Data

Public Class Table
    Private _name As String
    Private _delSql As ArrayList
    Private _dtDel As DataTable
    Private _dsQry As DataSet

    Public Sub New(ByVal name As String)
        'constructor
        Me._name = name
        Me._delSql = New ArrayList()

    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return _name
        End Get
    End Property

    Public Property DataTable() As DataTable
        Get
            Return _dtDel
        End Get
        Set(ByVal value As DataTable)
            _dtDel = value
        End Set
    End Property

    Public Sub putDelSql(ByVal sSql As String)
        If Not sSql Is Nothing Then
            _delSql.Add(sSql)
        End If
    End Sub

    Public Function getDelSql() As ArrayList
        Return _delSql
    End Function

    Public Function getDelSql(ByVal i As Integer) As String
        If i <= _delSql.Count - 1 Then
            Return _delSql(i)
        End If
        Return Nothing
    End Function

    Public Property DataSetQry() As DataSet
        Get
            Return _dsQry
        End Get
        Set(ByVal value As DataSet)
            _dsQry = value
        End Set
    End Property

End Class

11/17/2009

jQuery玩Ajax 後端服務由jsp提供

jQuery強大的支援Ajax呼叫與使用,可要怎麼做呢?

下面的例子要求使用者輸入姓名,使用者按下「Click Me」後,透過ajax機制傳送姓名給jsp程式,而jsp只是單純顯示出使用者所輸入的姓名而已。


Step by Step
1.import js檔。


2.body裡加上下方的tag





3.head裡加入下方的javascript


4.提供Ajax呼叫查詢後端資料的jsp
<%@ page language="java" contentType="text/html; charset=BIG5"
    pageEncoding="BIG5" import="java.util.*;"%>
<%

String gender = request.getParameter("gender");
String name = request.getParameter("name");
out.println((gender.equalsIgnoreCase("male")?"Mr.":"Mrs.") + " " + name);
out.println("Hello world! This message is posted by Server.");
%>

用jQuery操作html Dom object

jQuery怎樣操作html dom呢?下面有個也是學著網上先進做的範例。
效果請參考


Step by Step
1.import js檔。


2.body裡加上下方的tag
jQuery DOM Operation


original



3.head裡加入下方的javascript

First touch jQuery

jQuery是個javascript Library,讓程式人員寫較少的code完成所需功能。
官網:http://jquery.com/
官網說明:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

下面是個簡單的例子,學著網上其它先進做出來的範例。




上方效果若看不到請參考



Step by Step
1.使用jQuery要先Download jQuery API,它是個javascript檔。有幾個版本。以jQuery 1.3.2為例
  • jQuery Minified - 是去掉空白,註解的精簡版本,適用在上線的系統。
  • jQuery Regular - 是標準版本,適用在開發時較容易觀看它原始的code。

2.import js檔到html上。


3.在html的body裡加上下方的tag

4.html的head裡加入下方的javascript

Object to XML by DOM API in Java

有時侯我們想要把java object轉成XML時會使用到的code,轉出來的xml約像下面的格式。

   A12345
   1
   B12345
   2
   Iden123
   李昭慶
   
    d1
    c1
    1
    1
    1
   
   
    d2
    c2
    2
    2
    2
   
   
    d3
    c3
    3
    3
    3
   
  
DOMtoXML.java
/**
 * Object output XML format by DOM.
 */
package com.iden.Dom;

import java.io.*;
import java.util.ArrayList;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMtoXML {
   
 DOMtoXML(){}
 
 public static void main(String[] args) {  
  DOMtoXML jt = new DOMtoXML();
    
  Lot lot = new Lot("A12345", "1", "B12345", "2", "Iden123", "李昭慶");
  lot.putGlass("d1", "c1", "1", "1", "1");
  lot.putGlass("d2", "c2", "2", "2", "2");
  lot.putGlass("d3", "c3", "3", "3", "3");  
  String xml = lot.genObjectToXML();  
  System.out.println(xml); //print the xml string
 }
  
 private String encoding(String s){     
     try {      
   return new String(s.getBytes(), "UTF-8"); //"ISO-8859-1"
  } catch (UnsupportedEncodingException e) {   
   e.printStackTrace();
  }
  return null;
    }  
}

class Lot {
 DocumentBuilderFactory f;
 DocumentBuilder b;
 Document doc;
 private String lotId1;
 private String glsQty1;
 private String lotId2;
 private String glsQty2;
 private String userId;
 private String userName;
 private ArrayList glasses;
 
 Lot(String lotId1, String glsQty1, String lotId2, String glsQty2, String userId, String userName) { 
  this.glasses = new ArrayList();
  this.lotId1 = lotId1;
  this.glsQty1 = glsQty1;
  this.lotId2 = lotId2;
  this.glsQty2 = glsQty2;
  this.userId = userId;
  this.userName = userName;
    
  f = DocumentBuilderFactory.newInstance();
  try {
   b = f.newDocumentBuilder();
  } catch (ParserConfigurationException e) {   
   e.printStackTrace();
  }
  doc = b.newDocument();
  
 }

 public String genObjectToXML(){  
  try {   
   /*
    * XML output format:    
    */   
   Element root = doc.createElement(this.getClass().getSimpleName()); 
   doc.appendChild(root);
         Element e;
         e = doc.createElement("lotId1");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.lotId1));
         e = doc.createElement("glsQty1");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.glsQty1));
         e = doc.createElement("lotId2");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.lotId2));
         e = doc.createElement("glsQty2");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.glsQty2));
         e = doc.createElement("userId");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.userId));
         e = doc.createElement("userName");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.userName)); 
         
         Element g, dpLot, cutLot, gId, location, orgLocation;
         for(int i=0;i<glasses.size();i++){
          Glass objG = (Glass)glasses.get(i);
          g = doc.createElement("glass");
          root.appendChild(g);
          
          dpLot = doc.createElement("dpLotId");
          g.appendChild(dpLot);
          dpLot.appendChild(doc.createTextNode(objG.getDpLotId()));
          cutLot = doc.createElement("cutLotId");
          g.appendChild(cutLot);
          cutLot.appendChild(doc.createTextNode(objG.getCutLotId()));
          gId = doc.createElement("glsId");
          g.appendChild(gId);
          gId.appendChild(doc.createTextNode(objG.getGlsId()));
          location = doc.createElement("location");
          g.appendChild(location);
          location.appendChild(doc.createTextNode(objG.getLocation()));
          orgLocation = doc.createElement("orgLocation");
          g.appendChild(orgLocation);
          orgLocation.appendChild(doc.createTextNode(objG.getOrgLocation()));
         }
                
         
         TransformerFactory tf = TransformerFactory.newInstance();
   Transformer m = tf.newTransformer();
   DOMSource source = new DOMSource(doc);
   ByteArrayOutputStream byte1 = new ByteArrayOutputStream();
   StreamResult result = new StreamResult(byte1);
   System.out.println("Encoding: " + m.getOutputProperty(OutputKeys.ENCODING));
   m.setOutputProperty(OutputKeys.ENCODING, "BIG5");
   m.transform(source, result);
   return byte1.toString();
   
  } catch (TransformerConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerException e) {   
   e.printStackTrace();  
  }
  return null;
 }
 
 public void putGlass(String dpLotId, String cutLotId, String glsId, String location, String orgLocation) {
  if (dpLotId != null && cutLotId != null && glsId != null && location != null && orgLocation != null) {
   Glass g = new Glass();
   g.setDpLotId(dpLotId);
   g.setCutLotId(cutLotId);   
   g.setGlsId(glsId);
   g.setLocation(location);
   g.setOrgLocation(orgLocation);
   glasses.add(g);
  }
 }

 class Glass {
  private String dpLotId;
  private String cutLotId;
  private String glsId;
  private String location;
  private String orgLocation;

  public String getGlsId() {
   return glsId;
  }
  public void setGlsId(String glsId) {
   this.glsId = glsId;
  }
  public String getLocation() {
   return location;
  }
  public void setLocation(String location) {
   this.location = location;
  }
  public String getDpLotId() {
   return dpLotId;
  }
  public void setDpLotId(String dpLotId) {
   this.dpLotId = dpLotId;
  }
  public String getCutLotId() {
   return cutLotId;
  }
  public void setCutLotId(String cutLotId) {
   this.cutLotId = cutLotId;
  }
  public String getOrgLocation() {
   return orgLocation;
  }
  public void setOrgLocation(String orgLocation) {
   this.orgLocation = orgLocation;
  }
 } 
}

神眼三代與呼叫器無法同步解決法

說媽媽的VIOS被偷兒光顧後,我們家裡就出現三隻神眼三代傳訊鎖了。有用過這隻的朋友都知道這隻鎖最重要的就是鎖體上鎖後會同步呼叫器,當有人打開車門或進入車內時,鎖體會大叫,呼叫器也會第一時間通知車主。

最近有一隻鎖體沒電了,我就依照著說明手冊步驟更換電池,測試時,鎖體打開到open再扣上C型扣,居然有兩個呼叫器都B一聲,同步開機了,糟了! 我再測試另一隻原來鎖體,打開再扣上C型扣,哇~都沒辦法同步配對的呼叫器了。(變成A鎖同步A呼叫器與B呼叫器,而B鎖沒有呼叫器能與它同步)

為了重新同步,打了通電話給神眼的經銷商,居然要我郵寄給他們重設,電話那頭說:「重設定呼叫器就可以了,跟你說你也不會做,寄回來我們重設就好。」

「哇咧~~我們家有三隻鎖耶! 那每次出問題時都寄回去,鎖體很重,郵寄費不低耶~~,重設呼叫器誰不會呀; 步驟說清楚我不就知道了嗎。」心裡OS。

不死心,再打一通給鎖的製造商-超安精密,電話是位聲音很好聽的小姐接聽,說明過鎖的狀況與問題後,她很熱心的解說重設步驟,是這樣低。
  • 1.將無法同步的鎖體與呼叫器拿遠一點,離另外2隻鎖與呼叫器遠一點。
  • 2.鎖體用key打開到open,C型扣扣回,B一聲,閃燈熄滅後,馬上再打開到open。
  • 3.馬上按下呼叫器左鍵(解除鍵),按一下放開。
  • 4.等一下,若成功鎖會BBB之後閃爍呼叫器也會B並且液晶上會有訊號格顯示。

    再一次謝謝超安,客服做的不錯哦~有你們的貼心,真好。

    11/10/2009

    Java 自已動手寫log

    不用log4j自已寫個簡單的log程式。
    分檔規則是將log分年,月記錄,每天一個log檔,日子一久想查某一天的log也比較方便。
    例如:2009年10月11月有log時,log分檔會像這樣。
    • /2009/10/
      • 1.log
      • 2.log
      • 3.log
      • 5.log
      • ......
    • /2009/11/
      • 1.log
      • 2.log
      • 3.log
      • .....

    Log class
    /*
     * Log.java with encode
     * for logging
     *
     * Created on 2009年10月16日
     *
     * @author  Iden
     *
     ****<< Modification Note >>
     *     Date       PTS/PBR/PCR      Label       Editor         Description
     *  ==========  ===============  ==========  ==========  ============================================================
     *  2009/10/16                      0.0.0.1      Iden         create
     */
    package com.iden.util;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetEncoder;
    import java.text.SimpleDateFormat;
    
    public class Log {
     
     private String filePath = ""; //directory path of Log 
     private String filePrefix = ""; //prefix name of log file
     private String fileSubName = ""; //subname of log file
     String curWorkingDir = System.getProperty("user.dir"); //User working directory
     private String breakLine="\n";  
     private Object encoding;   
     private String encodingStr;   
    
     public Log(String path) {
      this(path, "log", "UTF-8");
     }
     
     public Log(String path, String subname, Object encoding) {
      this(path, "Log", subname, encoding);
     }
     
     public Log(String path, String prefix, String subname, Object encoding) {
      if(encoding ==null)
       new Exception("encoding is empth");
      
      filePath = path;
      filePrefix = prefix;
      fileSubName = subname;
      this.encoding = encoding;  
     }
     
     
     /**
      * Output the log file
      * @param str
      */
     public void write(String str) {  
      OutputStream stream = null;
            Writer writer = null;
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
      try {
       String folder = generateDirectory();
          
       File file = new File(folder + filePrefix + "_" + getCurrYYYYMMDD() + "." + fileSubName);
       
       StringBuffer sb = new StringBuffer("");
       sb.append("[" + formatter.format(new java.util.Date()) + "] [start]" + breakLine)
        .append(str)
        .append(breakLine + "[end]" + breakLine);
          
             stream = new FileOutputStream(file, true);
             
                if (encoding instanceof Charset) {
                    writer = new OutputStreamWriter(stream, (Charset)encoding);
                } else if (encoding instanceof CharsetEncoder) {
                    writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding);
                } else {
                    writer = new OutputStreamWriter(stream, (String)encoding);
                }
                OutputStreamWriter osw =(OutputStreamWriter)writer;
          encodingStr =  osw.getEncoding();      
          osw = null;
                
                writer.write(sb.toString());
                writer.flush();
                writer.close();
                
      } catch (java.io.FileNotFoundException efnf) {
       writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
      } catch (java.io.IOException exio) {
       writeException("IOException at write log file: " + exio.getMessage());   
      } catch (java.lang.Exception e) {
       writeException("Exception at write log file: " + e.getMessage());   
      } finally {
       writer = null;
      }
     }
     
     /**
      * Output the log file with default encoding
      * @param str
      */
     public void writeDefaultEncode(String str) {
      java.io.FileWriter fw = null;  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
      try {
       String folder = generateDirectory();
    
       fw = new java.io.FileWriter(folder + filePrefix + "_"
         + getCurrYYYYMMDD() + "." + fileSubName, true);
       
       fw.write("[" + formatter.format(new java.util.Date()) + "] " + breakLine + "[start]" + breakLine);
       fw.write(str);
       fw.write(breakLine + "[end]" + breakLine);
       fw.flush();
       fw.close();     
                   
      } catch (java.io.FileNotFoundException efnf) {
       writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
      } catch (java.io.IOException exio) {
       writeException("IOException at write log file: " + exio.getMessage());   
      } catch (java.lang.Exception e) {
       writeException("Exception at write log file: " + e.getMessage());   
      } finally {
       fw = null;
      }
     } 
     
     /**
      * Get the encoding string
      */
     public String getEncoding(){
      if(encodingStr != null)
       return encodingStr;
      return null;
     } 
    
     /**
      * Generate directory path
      * @return
      */
     private String generateDirectory() {
      String folder = defineDirectoryName(filePath);
      java.io.File file = new java.io.File(folder);
      file.mkdirs();
      return folder;
     }
    
     /**
      * Define the directory path of Log. format is path\YYYY\MM
      * @param path
      * @return current directory path
      */
     private String defineDirectoryName(String path) {
      java.util.Calendar cal = java.util.Calendar.getInstance(java.util.Locale.TAIWAN);
      String folder = path;  
      
      folder = folder + "\\" + String.valueOf(cal.get(java.util.Calendar.YEAR));
      if (String.valueOf((cal.get(java.util.Calendar.MONTH) + 1)).length() == 1) {
       folder = folder + "\\0" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
      } else {
       folder = folder + "\\" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
      } 
      folder = folder + "\\";
      return folder;
     }
     
     /**
      * Get the current date. format is YYYYMMDD
      * @return String of YYYYMMDD
      */
     private String getCurrYYYYMMDD() {  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); //yyyy/MM/dd HH:mm:ss
      return formatter.format(new java.util.Date());
     } 
     
     /**
      * Output Exception message from this object
      * @param msg
      */
     private void writeException(String msg){
      new Log(this.curWorkingDir).write(msg);
     }
     
    }
    
    

    Java中像 printStackTrace() 拋出 Stack String

    有時侯需要將stack中的例外訊息拋出來給使用者查詢或寫成log,這時侯就需要下面的程式了。
    package com.iden.util;
    
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.io.Writer;
    
    public class HandleException {
     
     /**
      * Return StackTrace information
      * @param throwObj
      * @return
      */
     private static String getStackTrace(Throwable throwObj) {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      throwObj.printStackTrace(printWriter);
      return result.toString();
     }
     
     /**
      * Return custom StackTrace information
      * @param throwObj
      * @return
      */
     private static String getCuctomStackTrace(Throwable throwObj) {  
      final StringBuilder result = new StringBuilder("HandleException.getCuctomStackTrace(): ");
      result.append(throwObj.toString());
      final String NEW_LINE = System.getProperty("line.separator");
      result.append(NEW_LINE);
      
      for (StackTraceElement element : throwObj.getStackTrace()) {
       result.append(element);
       result.append(NEW_LINE);
      }
      return result.toString();
     }
     
     public static void main(String[] args){
      try{
       throw new NullPointerException("Iden test");
       //throw new AlreadyBoundException("Iden test");
      }catch(Exception e){
       if(e instanceof java.lang.NullPointerException){ 
        System.out.println(getStackTrace(e));
        System.out.println(getCuctomStackTrace(e));
       } 
      }  
     }
     
    }
    

    Java load properties file

    如何用Java去讀取外部resource檔,要怎麼做呢?
    EIF.properties是個文件檔,放在class可以讀到的路徑下,在這裡是放在/bin。

    PropertyLoader class
    package com.iden.resource;
    
    import java.util.Properties;
    
    public class PropertyLoader {
    
     private Properties prop = null;
     private Boolean isSet;
    
     PropertyLoader() {
      prop = new Properties();
      try {
       prop.load(getClass().getResourceAsStream("/EIF.properties"));
      } catch (Exception e) {
       e.printStackTrace();
      }
      if (new String(
        prop.getProperty("PropertyLoaderTest.isSet") != null ? prop
          .getProperty("PropertyLoaderTest.isSet") : "").trim()
        .equalsIgnoreCase("1"))
       isSet = true;
      else
       isSet = false;
     }
     
     public static void main(String[] args){
      PropertyLoader loader = new PropertyLoader();
      System.out.println("PropertyLoaderTest.isSet=" + loader.isSet);
      
     }
    }
    

    EIF.properties
    # 1 or 0  / 1:short data model: update data when start time, end time, shift time  0:every data update model
    PropertyLoaderTest.isSet=1
    

    11/04/2009

    VB Window Form 限制輸入字數 code

    VB.net限制只能輸入多少字並大寫,以下是練習。
    'TextBox limit character digits user input
        Public Sub limitTextBoxDigits(ByRef obj As System.Windows.Forms.TextBox, ByVal digits As Integer)
            obj.CharacterCasing = Windows.Forms.CharacterCasing.Upper
            If obj.SelectedText <> "" Then 
                Dim selIdx As Integer = obj.SelectionStart
                obj.Text = obj.Text.Remove(obj.SelectionStart, obj.SelectionLength)
                obj.Select(selIdx, 1)
            End If
            If obj.Text.Length >= digits Then obj.Text = obj.Text.Remove(digits - 1, 1) : obj.Select(digits - 1, 1)
        End Sub
    

    10/29/2009

    Java Reflection 動態調用物件的方法

    近來接觸Java Reflection,參考良葛格的例子做了些練習,下面是實作的code。

    Student Class:
    package com.iden.reflection;
    
    public class Student {
     private String name;
        private int score; 
    
        public Student() { 
            name = "N/A"; 
        } 
    
        public Student(String name, int score) { 
            this.name = name; 
            this.score = score; 
        } 
    
        public void setName(String name) {
            this.name = name;
        }
        
        public void setScore(int score) {
            this.score = score;
        }
    
        public String getName() { 
            return name; 
        } 
    
        public int getScore() { 
            return score; 
        } 
    
        public void showData() { 
            System.out.println("name: " + name); 
            System.out.println("score: " + score); 
        }
    }
    


    InvokeMethodDemo Class 調用Student object實作方法:
    package com.iden.reflection;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class InvokeMethodDemo {
     
     private static String className;
     
        public static void main(String[] args) {
         //動態載入與呼叫方法
            try {
              
             if(args.length == 0)
              className = "com.iden.reflection.Student";
             else
              className = args[0];
              
                Class c = Class.forName(className);//呼叫Class
                Object targetObj = c.newInstance();//動態實作物件
                
                Class[] param1 = {String.class};
                Method setName = c.getMethod("setName", param1);//指定物件的方法            
                Object[] paramObjs1 = {"caterpillar"};
                setName.invoke(targetObj, paramObjs1);//將參數帶入方法
                
                
                Class[] param2 = {Integer.TYPE};
                Method setScore = c.getMethod("setScore", param2);            
                Object[] paramObjs2 = {new Integer(90)};
                setScore.invoke(targetObj, paramObjs2);
                
                
                Method showData = c.getMethod("showData", new Class[0]);
                showData.invoke(targetObj, new Object[0]);// call showData method to show name and score.
                
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    } 
    


    感謝良葛格做了這麼棒的教學。
    良葛格範例

    10/28/2009

    Oracle 系統 object 相關

    --查出所有的objects:
    select * from all_objects
    

    --找Column名稱是ID的所有table
    select * from all_tab_columns
    where column_name = 'ID';
    

    updated: Nov 12, 2009
    --Oracle show Year, Month and Date
    select TO_CHAR(sysdate,'Y') as YY ,TO_CHAR(sysdate,'MM') as MM,TO_CHAR(sysdate,'DD') as DD from dual
    

    updated:Dec 17, 2009
    --查詢自建Table: PT_LTDFT 有沒有欄位 DF_TYPE
    SELECT COLUMN_NAME from USER_TAB_COLUMNS p WHERE p.table_name = 'PT_LTDFT' and p.column_name = 'DF_TYPE'
    

    10/26/2009

    VirtualBox中 GuestOS:Ubuntu 自動掛載 shared folder

    Ubuntu開機後要自動掛載磁碟需設定fstab,做法約如下:

    1.進入command console,etc裡用sudo vi打開fstab檔(權限不足會不能修改fstab)
    cd /
    cd etc
    sudo vi fstab

    2.在最下面加入以下資訊
    Download /media/Download vboxsf defaults 0 0

    其中Download是VirtualBox中設定的shared folder名稱
    /media/Download是要掛載的folder

    3.reboot,完成。

    VirtualBox裡掛載Shared Folder在GuestOS Ubuntu 9.10

    Host OS: windows
    Guest OS: Ubuntu 9.10

    前提:
    在VirtualBox設定裡先設定好HostOS的shared folder

    1. 安裝VirtualBox Additions:
    cd /media/cdrom
    sudo ./VBoxLinuxAdditions-x86.run

    2. vboxvfs module載入核心:
    sudo modprobe vboxvfs

    3.建立要掛載的folder
    mkdir /media/Download

    4.掛載Shared Folder
    sudo mount -t vboxsf [SharedFolderName] /media/Download

    5.完成

    9/29/2009

    Java code加入proxy

    加上下面的code就可以了。這是設在系統的方式。
        System.setProperty("http.proxySet", "true");
        System.setProperty("http.proxyHost", "10.180.0.53");
        System.setProperty("http.proxyPort", "8080");
    

    6/03/2009

    Windows中 Java都會自動使用的lib folder

    只要將jar放到 C:\Windows\Sun\Java\Deployment\Lib\Trusted 裡,jre會自行取用而且只會load一次

    Java Applet 需 Sign才能在client使用IO等安全性功能

    這陣子在做Applet的東西才發現,Applet在client執行時,需要client簽核才可以使用IO等等資源,所以Applet寫好後打包成jar,這jar必須做成signed jar才行。

    1.用jdk command產生憑証檔到keystore
    keytool -genkey -alias [myKeyName]

    2.用jdk command將打包好的jar 做成sign jar
    jarsigner myJar.jar [myKeyName]


    參造了原文文章:

    Sign All Applet JAR files

    Applets are back! And now applets can do more than ever before thanks to signed JAR files. By signing your JARs, you can get access to the filesystem and other resources that were previously off-limits, provided the user grants your applet those privileges. And signing JAR files is now very easy thanks to tools bundled with the JDK.

    However, be certain to sign all JAR files used by your Java applet. If you sign the JAR file with your main applet class, your applet will launch. If it later uses classes from another JAR file, though, you can run into trouble. If the newly-loaded class tries a restricted operation and its JAR file isn't signed, your applet will fail at that point with a security exception. Rather than waiting for this and debugging it when it occurs, save yourself the trouble and sign all of your JAR files up front.

    You can create your own certificate using tools provided by the JDK. keytool -genkey -alias mykey lets you create your own certificate. Be sure to specify an expiration date far in the future with -validity 1000. The default is only 6 months.

    Sign your JAR files with jarsigner my.jar mykey (where my.jar is the name of the jar file to sign).

    Deploy all of your JAR files to a folder on your web server, add an HTML page with the applet tag, and let the world enjoy your new applet with powerful permissions.

    來自:http://frequal.com/java/SignAllAppletJars.html

    5/18/2009

    解決Yam.com上看技術線圖出現亂碼

    源由:
    安裝過英文版的MS Windows或ubuntu linux後,想要看yam.com股市的技術線圖時,中文字都是「囗囗囗囗囗囗」的亂碼,看不到本來的中文字而感到困擾。


    解決:
    經過一番google搜尋與思考發現這問題是jvm在執行applet時encode問題,需要強制成big5。

    for ubuntu
    1. 當然自已要先把 jre6 安裝完成
    2. 選擇 System -> Preferences -> Sun Java 6 plugin control panel
    3. 切換到 "Java" 的tab,點選 Java Applet Runtime Settings的 View按鈕
    4. 在正在使用的jre裡加上parameters : 「-Dfile.encoding=big5」
    5. 按下OK就完成了。

    for Windows Vista
    1. 控制台 -> Java
    2. 一樣有個 "Java" 的tab,如上設定強制的編碼即可。

    成功,都看到正常的中文字了。

    3/10/2009

    愛車協尋 2873-PQ 白色VIOS

    2009年3月9日(星期一)清早,「媽媽的車不見了」在睡夢中的我突然聽到,馬上跳離床,下樓查看,真的…不見了。 地上只留下被打破的客座車窗玻璃與一些鎖頭的零件。


    牌照號碼 2873-PQ 一輛母親每週洗車、細心維護的白色 Toyota VIOS,就在住家樓下路旁消失了。


    當天母親很是難過,心裡很不捨,嘴裡只說「有人比我們還需要它」,就這樣完成了警局報案,拿了張聯單,收拾心情一陣子後,離家去阿姨那幫忙…


    說到這輛車是有故事的。


    母親已在阿姨家幫忙多年,阿姨家很遠在南投北山(我們家在台中市東區),所以每天都開著高齡15年又失而復得的March(被偷兒光顧過一次)來回南投北山與台中,每日車程加起來有140公里之遠,就這樣一天又一天…


    兩年多前,三個兒子早已知道母親辛苦,一方面也擔心母親車途上安全,另一方面服役已15年的March數月來大小問題不斷發生,努力存了多年的一筆錢終於付得起頭款,當下即決定「讓媽媽換一輛車」。


    不久家樓下就停了輛VIOS,還記得那時母親看到了車時,高興又眼泛淚水的表情,我知道母親即高興又驕傲。



    後記

    =========================================================

    我想請廣大的網民,幫忙一同協尋,對我們而言,這是一輛有意義的小VIOS。

    失蹤的地點台中市東英路上,時間大約是3月8日22:30 ~ 3月9日08:00


    若能協同找到我們將奉上新台幣6萬以答謝您的幫忙。

    若您有任何線索,請留下Commont,或是mail給我 iden1109@gmail.com


    拜托大家。



    3/05/2009

    解決Eclipse out of memory problem

    在 eclipse.ini 最後加上這一行即可

    -XX:MaxPermSize=160m

    引用來源 blog:
    公爵的 Ubuntu 城堡

    1/10/2009

    VirtualBox 2 change uuid

    how to change uuid in VirtualBox 2.1
    try this:
    command> VBoxManage internalcommands setvdiuuid disk2.vdi