2016年12月24日 星期六

永久修改 Ipython Nortebook 或 Jupter Notebook 的默認目錄

參考:
http://xuanchao1980.com/2016/05/12/jupyterDirectory/

步驟:
Ipython Notebook

1.打開命令行(初始化配置文件):
  1. ipython profile create

這個命令,會初始化一份配置文件ipython_notebook_config.py,輸入後找到下面這行

# c.NotebookManager.notebook_dir = u'D:\\love\\cat'

如果没有,請找這行:

# c.NotebookApp.notebook_dir = u'Z:\\luv\\cat'

2.去掉註解&空格,修改路徑路徑為自己想要的

Jupyter Notebook

1.打開命令行(初始化配置文件):
  1. jupyter notebook --generate-config
這個命令,會初始化一份配置文件.jupyter\jupyter_notebook_config.py
輸入後找到下面這行

# c.NotebookApp.notebook_dir = u'D:\\love\\you'


2.去掉註解&空格,修改路徑路徑為自己想要的

2016年12月20日 星期二

Word Cloud 文字雲 - jQCloud & WordCloud2

Sample Step:

1.Download word cloud jquery:
http://mistic100.github.io/jQCloud/#usage



2.Include package & jQuery CDN
- jqcloud.min.js- jqcloud.min.css
- jqcloud.min.js- jqcloud.min.js
- https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

- 程式碼
  1. <head>
  2. <meta charset="utf-8">
  3. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
  4. <script src="jqcloud.min.js"></script>
  5. <link rel="stylesheet" href="jqcloud.min.css">
  6. <title>test</title>
  7. </head>

3.設定『資料』 & 啟用文字雲
- 要記得給文字雲『範圍大小』,否則畫面上看不到
  1. $('#keywords').jQCloud(words, {
  2. width: 500,
  3. height: 350
  4. });

- 設定假資料
  1. <script>
  2. $(function(){
  3. var words = [
  4. {text: "Lorem", weight: 13},
  5. {text: "Ipsum", weight: 10.5},
  6. {text: "Dolor", weight: 9.4},
  7. {text: "Sit", weight: 8},
  8. {text: "Amet", weight: 6.2},
  9. {text: "Consectetur", weight: 5},
  10. {text: "Adipiscing", weight: 5},
  11. ];
  12.  
  13. <!-- $('#demo').jQCloud(words); -->
  14. $('#demo').jQCloud(words, {
  15. width: 600,
  16. height: 600
  17. });
  18. });
  19. </script>

4.Result



5.Sample code
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
  6. <script src="jqcloud.min.js"></script>
  7. <link rel="stylesheet" href="jqcloud.min.css">
  8. <title>test</title>
  9. </head>
  10. <script>
  11. $(function(){
  12. var words = [
  13. {text: "Lorem", weight: 13},
  14. {text: "Ipsum", weight: 10.5},
  15. {text: "Dolor", weight: 9.4},
  16. {text: "Sit", weight: 8},
  17. {text: "Amet", weight: 6.2},
  18. {text: "Consectetur", weight: 5},
  19. {text: "Adipiscing", weight: 5},
  20. ];
  21.  
  22. <!-- $('#demo').jQCloud(words); -->
  23. $('#demo').jQCloud(words, {
  24. width: 600,
  25. height: 600
  26. });
  27. });
  28.  
  29. </script>
  30. <body>
  31. <div id="demo" style="border:thin solid black">
  32. </div>
  33. </body>
  34.  
  35. </html>

6.Advance Skill 
[自訂設定]
- delay: 50 (字體顯示的速度)
- steps : Number of "steps" to map the words on, depending on their weight (大約會有幾種字體大小,會與自設的color進行比對)
- colors: 自訂顏色
-from-to: 字體最大-最小(根據container的大小)
  1. $('#wordCloud').jQCloud(words, {
  2. delay: 50,
  3. width: 500,
  4. height: 500,
  5. autoResize: true,
  6. steps : 50,
  7. //最凸顯
  8. colors: ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
  9. "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
  10. "#555555", "#555555", "#555555", "#555555", "#555555", "#444444", "#444444", "#444444", "#444444","#444444",
  11. "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
  12. "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
  13. ],
  14. fontSize: {
  15. from: 0.08,
  16. to: 0.02
  17. }
  18. });

[文字雲特殊效果(字體隨滑鼠移出移入改變)]
  1. //文字雲特殊效果
  2. $(document).on('mouseenter','.jqcloud-word',function(){
  3. var font_size = parseFloat($(this).css("font-size"));
  4. var newSize = font_size + 10;
  5. $(this).css("font-size",newSize + 'px');
  6. }).on('mouseout','.jqcloud-word',function(){
  7. var font_size = parseFloat($(this).css("font-size"));
  8. var newSize = font_size - 10;
  9. $(this).css("font-size",newSize + 'px');
  10. });

[使用者可調整"字體顏色"、文字雲型狀]

1.按下"更新"
2.刪掉文字雲
3.重建文字雲
  1. //delete
  2. wordCloud.jQCloud('destroy');
  3. //update word cloud
  4. wordCloud.jQCloud(words, {
  5. delay: 40,
  6. width: width,
  7. height: height,
  8. autoResize: true,
  9. steps : 50,
  10. colors: colorStyle,
  11. shape: shape,
  12. fontSize: {
  13. from: 0.08,
  14. to: 0.02
  15. }
  16. });

4.sample code
  1. //文字雲update
  2. $('#updateButton').on('click', function() {
  3. var wordCloud = $('#wordCloud');
  4. var selectColorStyle = $('#colorStyle').val();
  5. var selectShape = $('#shape').val();
  6. var colorStyle;
  7. //custom color style
  8. if (selectColorStyle == '1') {
  9. colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
  10. "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
  11. "#555555", "#555555", "#555555", "#555555", "#555555", "#444444", "#444444", "#444444", "#444444","#444444",
  12. "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
  13. "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
  14. ];
  15. } else if (selectColorStyle == '2') {
  16. colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
  17. "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
  18. "#3399CC", "#3399CC", "#CC6600", "#CC6600", "#999999", "#444444", "#444444", "#444444", "#444444","#444444",
  19. "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
  20. "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
  21. ];
  22. } else if (selectColorStyle == '3') {
  23. colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
  24. "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
  25. "#3399CC", "#3399CC", "#CC6600", "#CC6600", "#999999", "#999999", "#CCCC33", "#CCCC33", "#CCCC33","#CCCC33",
  26. "#FF9933", "#FF9933", "#CC9999", "#CC9999", "#666699", "#666699", "#FF9900", "#FF9900", "#0099CC","#0099CC",
  27. "#CCCC99", "#CCCC99", "#FF6666", "#FF6666", "#FFCC99", "#FFCC99", "#CC3399", "#CC3399", "#99CC33","#99CC33"
  28. ];
  29. }
  30. //custom shape
  31. var width;
  32. var height;
  33. var shape;
  34. if (selectShape == '1') {
  35. width = 550;
  36. height = 400;
  37. shape = 'elliptic';
  38. } else if (selectShape == '2') {
  39. width = 500;
  40. height = 500;
  41. shape = 'elliptic';
  42. } else {
  43. width = 550;
  44. height = 400;
  45. shape = 'rectangular';
  46. }
  47. //delete
  48. wordCloud.jQCloud('destroy');
  49. //update word cloud
  50. wordCloud.jQCloud(words, {
  51. delay: 40,
  52. width: width,
  53. height: height,
  54. autoResize: true,
  55. steps : 50,
  56. colors: colorStyle,
  57. shape: shape,
  58. fontSize: {
  59. from: 0.08,
  60. to: 0.02
  61. }
  62. });
  63. });

Word Cloud 2

1.下載:
https://timdream.org/wordcloud2.js/#red-chamber

2.Sample Code:
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
  6. <script src="wordcloud2.js"></script>
  7. <title>test</title>
  8. </head>
  9. <script>
  10. $(function(){
  11. var words = [
  12. ["哈哈哈哈",60],
  13. ["Ipsum",19],
  14. ["Dolor",18],
  15. ["Sit",17],
  16. ["Amet",16],
  17. ["Consectetur",15],
  18. ["Adipiscing",14],
  19. ["dsfsf",13],
  20. ["Ipsdfsum",12],
  21. ["Dosdfsdflor",11],
  22. ["台灣",10],
  23. ["Ipsum",9],
  24. ["Dolor",8],
  25. ["Sit",7],
  26. ["Amet",6],
  27. ["Consectetur",5],
  28. ["Adipiscing",4],
  29. ["dsfsf",3],
  30. ["Ipsdfsum",2],
  31. ["Dosdfsdflor",1],
  32. ["台灣",25],
  33. ["Ipsum",24],
  34. ["Dolor",23],
  35. ["Sit",22],
  36. ["Amet",21],
  37. ];
  38.  
  39. WordCloud($('#wordCloud')[0], {
  40. list: words,
  41. classes: 'wordCloud',
  42. wait: 30,
  43. gridSize: 10,
  44. weightFactor: 1.6,
  45. fontFamily: 'Hiragino Mincho Pro, serif',
  46. color: 'random-dark',
  47. backgroundColor: '#FFFFFF',
  48. rotateRatio: 0
  49. });
  50. //文字雲update
  51. $('#updateButton').on('click', function() {
  52. //custom shape
  53. var selectShape = $('#shape').val();
  54. var shape;
  55. if (selectShape == '1') {
  56. shape = 'circle';
  57. } else if (selectShape == '2') {
  58. shape = 'star';
  59. } else if (selectShape == '3') {
  60. shape = 'pentagon';
  61. } else if (selectShape == '4'){
  62. shape = 'diamond';
  63. } else if (selectShape == '5') {
  64. shape = 'triangle';
  65. }
  66. WordCloud($('#wordCloud')[0], {
  67. list: words,
  68. classes: 'wordCloud',
  69. wait: 30,
  70. shape: shape,
  71. gridSize: 10,
  72. weightFactor: 1.6,
  73. fontFamily: 'Hiragino Mincho Pro, serif',
  74. color: 'random-dark',
  75. backgroundColor: '#FFFFFF',
  76. rotateRatio: 0
  77. });
  78. });
  79. //文字雲特殊效果
  80. $(document).on('mouseenter','.wordCloud',function(){
  81. var font_size = parseFloat($(this).css("font-size"));
  82. var newSize = font_size + 10;
  83. $(this).css("font-size",newSize + 'px');
  84. }).on('mouseout','.wordCloud',function(){
  85. var font_size = parseFloat($(this).css("font-size"));
  86. var newSize = font_size - 10;
  87. $(this).css("font-size",newSize + 'px');
  88. });
  89. });
  90. </script>
  91. <body>
  92. <div style="border:thin solid red;align:center">
  93. <div id="wordCloud" style="width:500px;height:500px;border:thin solid black;margin:0 auto">
  94. </div>
  95. </div>
  96. <select id="shape" class="pull-right" style="height: 27px;width: 100px;margin: 3px" type="select">
  97. <option value='1' selected="selected">雲朵</option>
  98. <option value='2' >星星</option>
  99. <option value='3'>五角大廈</option>
  100. <option value='4'>鑽石</option>
  101. <option value='5'>金字塔</option>
  102. </select>
  103. </body>
  104. <button class="" id="updateButton">Update</button>
  105.  
  106. </html>

2016年12月19日 星期一

Hibernate Criteria - DQL

Hibernate - Criteria

參考:
http://openhome.cc/Gossip/HibernateGossip/CriteriaBasic.html

範例:
1.add()
- org.hibernate.criterion.Criteria 實例代表著一個條件,您要使用org.hibernate.Criteria的add()方法加入這些條件實例,例如查詢” age”大於20且小於40的資料

- 使用add()時,預設是使用and來組合條件

- gt()大於 lt小於
  1. Criteria criteria = session.createCriteria(User.class);
  2. criteria.add(Restrictions.gt("age", new Integer(20)));
  3. criteria.add(Restrictions.lt("age", new Integer(40)));
  4. List users = criteria.list();

2.or()
- age等於(eq)20或(or)age為空(isNull)的條件
  1. Criteria criteria = session.createCriteria(User.class);
  2. criteria.add(Restrictions.or(
  3. Restrictions.eq("age", new Integer(20)),
  4. Restrictions.isNull("age")
  5. ));
  6. List users = criteria.list();

3.like()
- 查詢"name"中名稱為"just"開頭的資料:
  1. Criteria criteria = session.createCriteria(User.class);
  2. criteria.add(Restrictions.like("name", "just%"));
  3. List users = criteria.list();

4.in()
- 條件要放 『陣列 []
  1. String[] queryArray = {"John", "Ian"}
  2.  
  3. criteria.add(Restrictions.in(columnName, queryArray)); // 使用criteria columnName要放『物件的名稱』not 欄位名稱

5.between()
- 要注意型態問題(ex. timestamp)
  1. Criteria criteria = session.createCriteria(AuditTrail.class);
  2. criteria.add(Restrictions.between("auditDate", sDate, eDate));

6.Restrictions的幾個常用限定查詢方法如下表所示:
方 法說 明
Restrictions.eq等於
Restrictions.allEq使用Map,使用key/value進行多個等於的比對
Restrictions.gt大於 >
Restrictions.ge大於等於 >=
Restrictions.lt小於 <
Restrictions.le小於等於 <=
Restrictions.between對應SQL的BETWEEN子句
Restrictions.like對應SQL的LIKE子句
Restrictions.in對應SQL的in子句
Restrictions.andand關係
Restrictions.oror關係
Restrictions.sqlRestrictionSQL限定查詢

2016年12月16日 星期五

Hibernate SQL - DML、DQL、JOIN 範例

SQL
參考:http://blog.csdn.net/vacblog/article/details/7769976

-Select
1.addEntity()
透過『addEntity()』將"table"與"實體類"關聯在一起
這樣可以融合SQL簡潔的語法與Hibernate的方便性

使用addEntity()的大前提
-查詢返回的是某個table的全部數據  
-該table有對應的映射實體

這時候才能透過addEntity()方法將查詢結果轉換成實體
  1. Query query = session.createSQLQuery(
  2. "SELECT * FROM user_account ua WHERE ua.account=:account AND ua.user_email=:emailAddress ")
  3. .addEntity(UserAccountEntity.class) //結合entity的方式把資料傳回來,但使用時有前提
  4. .setParameter("account", account)
  5. .setParameter("emailAddress", emailAddress);
  6. resultList = query.list();

2.使用別名的addEntity()
  1. String sql = "select {myUser.*} from user_information myUser ORDER BY myUser.id";
  2. SQLQuery query = session.createSQLQuery(sql);
  3. query.addEntity("myUser", UserInformationEntity.class);

3.addScalar()
最基本的SQL查询就是取得一個物件的列表:
  1. session.createSQLQuery("select * from person_inf").list();
  2. session.createSQLQuery("select id,name,age from person_inf").list();

此時會返回一個Object陣列组成的List,陣列每個元素都是person_inf表的一個欄位值。Hibernate會使用ResultSetMetadata來判定返回的值的實際順序跟類型。
但是在JDBC中過多的使用ResultSetMetadata會降低程序的性能。為避免過多使用ResultSetMetadata或者指定更加明確的返回值類型,我們可以使用addScalar()方法提高效能
  1. session.createSQLQuery("select * from person_inf")
  2. .addScalar("name",StandardBasicTypes.STRING)
  3. .addScalar("age",StandardBasicTypes.INT)
  4. .list();

上述查询指定了:
-SQL查询欄位。
-要返回的欄位值和類型。
但是他仍然會返回Object陣列,但是此時不再使用ResultSetMetdata,而是明確的將\name和age按照String和int類型從resultset中取出。同時,也指明了就算query是使用*来查询的,可能獲得超過列出的這3個欄位,也僅僅會返回這3個欄位的值。

4. Join tables & 只傳回特定欄位值
  1. Query query = session.createSQLQuery(
  2. "SELECT ua.f_service FROM user_account ua INNER JOIN service_account sa ON ua.f_service=sa.id
  3. WHERE sa.account=:serviceAccount AND ua.account=:account AND ua.user_email=:emailAddress ")
  4. .addScalar("f_service",StandardBasicTypes.INTEGER)
  5. .setParameter("serviceAccount", serviceAccount)
  6. .setParameter("account", account)
  7. .setParameter("emailAddress", emailAddress);
  8.  
  9. resultList = query.list();
  10.  
  11. //get serviceId (createSQLQuery return Object[], but we only select f_service so only return an Object)
  12.  
  13. if (resultList.size() > 0) {
  14. Object aResult = resultList.get(0); //因為只有一個欄位值,所以傳回的並不是陣列,只是一個object
  15. serviceId = Integer.valueOf(String.valueOf(aResult));
  16. }
下列語法也通用
  1. Query query = session.createSQLQuery(
  2. "SELECT ua.f_service FROM user_account ua, service_account sa
  3. WHERE ua.f_service=sa.id and sa.account=:serviceAccount AND ua.account=:account AND ua.user_email=:emailAddress ")
要是有『多個查詢值 select a,b,c......』會返回object[],使用下列方法接取
  1. Object[] aResult = (Object[]) resultList.get(0);

5.透過addEntity、addScalar做join
http://blog.maxkit.com.tw/2014/03/hibernate-addentity-addscalar.html

2016年12月15日 星期四

Hibernate HQL - DML、DQL、JOIN 範例

HQL
-Select 
1.利用 ? 設定 sql 中的參數,搭配 query.setParameter("第幾個問號",變數);
  1. Session session = BackendHibernateUtil.getSession();
  2. List resultList = new LinkedList<>();
  3. try {
  4. Query query = session.createQuery("FROM CtrlSourceAreaEntity WHERE source_type = ?");
  5. query.setParameter(0,sourceType);
  6. resultList = query.list();
  7. } catch (HibernateException e) {
  8. log.error("XMLParserDAO @querySourceAreaId Fail:", e);
  9. } finally {
  10. session.close();
  11. }
  12. return resultList;
2.利用 :Name 設定參數
  1. "FROM CtrlSourceAreaEntity WHERE source_type = :sourceType"
  2. query.setParameter("sourceType",sourceType);

3.SQL Query In 設定參數
  1. Query query = session.createQuery("FROM ScheduleDownloadEntity WHERE status in (:statusNames) ORDER BY create_time ");
  2. query.setParameterList("statusNames", statusList);
  3. resultList = query.list();

-Update
1.executeUpdate()是執行DML的意思
  1. Query query = session.createQuery("UPDATE UserAccountEntity SET password = ? where f_service = ? AND account = ? AND user_email = ?");
  2. query.setParameter(0, userPasswordMD5);
  3. query.setParameter(1, serviceId);
  4. query.setParameter(2, account);
  5. query.setParameter(3, emailAddress);
  6. query.executeUpdate(); //這句是commit的意思

-Delete
1.executeUpdate() 是執行DML的意思

2.executeUpdate() 會傳回 int 影響的資料筆數
  1. Query query = session.createQuery("DELETE EdititemEntity WHERE kind = ? AND post_time BETWEEN ? AND ? ");
  2. query.setParameter(0, taskNumber);
  3. query.setParameter(1, startDate);
  4. query.setParameter(2, endDate);
  5. int resultCount = query.executeUpdate(); //可以取得DML影響的資料筆數

-Insert
1.將傳進來的 entity 實體 透過 session.save() 的方式把資料存進DB
  1. public void insertData(EdititemEntity edititemEntity) {
  2. Session session = Opv_lyHibernateUtil.getSession(); //Hibernate Session Connect
  3. Transaction tx = session.beginTransaction(); //一組交易
  4. try {
  5. session.save(edititemEntity); //將傳進來的Entity存進DB(透過Hibernate專屬方法)
  6. tx.commit(); //交易確認
  7. } catch (HibernateException e) {
  8. tx.rollback(); //交易取消
  9. log.error("CategoryDAO @insertData Fail,newsId={},error={}", edititemEntity.getId(), e);
  10. } finally {
  11. session.close();
  12. }
  13. }

HQL-Join

參考:
http://openhome.cc/Gossip/HibernateGossip/ManyToOne.html

多對一:
一個簡單的實體與實體間之關係為『多對一』的關係,例如『使用者』與『房間』的關係就是多對一的關係,多個使用者使用同一房間。

範例目標:

A:每個 user 有特定的 serviceId(f_service) ,多個user會對上同一個serviceId,希望透過HQL的方式,取得user時,順便取得service_account




1.實體設定(UserAccountEntity)

-在多對一的情況下,『多』的實體才需要特別設定,『一』的部份不用調整,因此我們只調整UserAccount
-UserAccountEntity.class
UserAccountEntity類別中有一serviceAccountEntity屬性,將參考至serviceAccountEntity實例,多個User實例可共同參考一個service實例











2.設定檔(UserAccountEntity.hbm.xml)
- class="絕對路徑""
- column="f_service" → userAccount的f_service(FK)會去參考到serviceAccount的id(PK),兩張table才會連結在一起
- cascade表示主控方(User)進行save-pdate、delete等 相關操作時,被控 方(Room)是否也一併進行相關操作,簡單的說,也就是您儲存或更新User實例時,被參考到的Room實例是否一併對資料庫發生儲存或操作,設定為 all,表示主控方任何操作,被控方也進行對應操作。

-把原先的fService先註解掉



-設定mana-to-one的參數















3.查詢結果
- 重要:INNER JOIN 是 userAccount實體中的serviceAccount屬性




- 結果
每個傳回的結果都帶有UserAccountEntity & ServiceAccountEntity

2016年11月16日 星期三

當 sublimetext 使用 Django碰上 Non-ASCII 編碼問題

1.問題:
- Non-ASCII














2.解決方式
- 在檔案上方加入
#-*- coding: UTF-8 -*-








-將檔案重新編碼儲存




2016年11月7日 星期一

建構子Construct 對 靜態變數 static & 實體變數 instance 操作

1.實作


  1. public class TestClass {
  2. public String instancePath ; //實例變數 (需要new出物件才能使用)
  3. public static String staticPath ; //靜態變數 (類別名稱.變數名稱 即可使用)
  4.  
  5. /**
  6. * Construct
  7. * @param path 路徑
  8. */
  9. public TestClass (String path) {
  10. this.instancePath = path;
  11. this.staticPath = path;
  12. }
  13.  
  14. public String getInstancePath () {
  15. instancePath = "i am instancePath"; //實體被改掉,後面再取會不一樣
  16. return instancePath;
  17. }
  18.  
  19. public String getStaticPath () {
  20. staticPath = "i am staticPath";
  21. return staticPath;
  22. }
  23. }
  1. public class MainClass {
  2. public static void main(String[] args) {
  3. TestClass testClass = new TestClass("c://");
  4.  
  5. System.out.println(testClass.instancePath); //一開始取到『建構子』給的值
  6. System.out.println(testClass.getInstancePath()); //後面方法裡值被修改掉
  7.  
  8. System.out.println(TestClass.staticPath); //透過類別方法.變數方法即可取用
  9. System.out.println(testClass.getStaticPath()); //
  10. }
  11. }

2.Console

2016年10月20日 星期四

FileZella Server 架設 FileZella Client 連線 (本機連本機)

參考:https://steachs.com/archives/1690
FileZilla Server小檔案:
官方網站:http://filezilla-project.org
軟體版本:0.9.36
軟體語系:英文
支援系統:Windows XP/Vista/7
軟體下載:官方下載

步驟說明:
1.安裝FileZella Server (本機當作Server )
2.指定某資料夾做為分享資源
3.安裝FileZella Client 
4.進行連線,看是否能抓取到『Server分享的資料夾資源』

1.安裝:
1.在安裝時會有一個選單是選擇開機啟動
2.開機不啟動(手動)
3.不安裝服務自動啟動伺服(不建議)
而下方是設定FTP使用的port要佔用哪一個(預設14147)



啟動設定,建議不用變更,依預設即可。



2.第一次啟動時
1.『設定IP位址』(範例設為本機)
2.『port』
3.『管理者密碼』



3.設定使用者群組(可先忽略)
在設定使用者之前,我們可以先設定群組,這樣可以統一分類,點擊二個人頭的圖示,開啟視窗後點擊「Add」輸入群組名確定即可。



4.設定要分享的資料夾
切換到「Shared folders」,設定client登入後的預設資料夾在哪,一樣點擊「Add」再選擇要讓使用者登入的資料夾即可。



5.分享資料夾權限設定
分為Files(檔案)及Directories(資料夾),預設是可以看到清單及讀取,如果你是要讓人可以寫入及建立資料夾等權限,可以依個人需求勾選。



6.建立使用者至群組(重要步驟,可直接新增跳過群組)
建立好群組後,點擊一顆頭的圖示,點擊「Add」,輸入使用者名稱,再選擇群組,這樣就將使用者加入群組完成。



再來就可以勾選擇使用者的「Password」再輸入要幫使用者設定的密碼,確認後就可以試看看用剛建立的帳密登入試試。



7.其他設定-各別帳號設定資料夾權限
像設定群組一樣,切換到Shared folders再新增資料夾並設定權限即可。



Speed Limits可設定限速,連線規則等等,可各別設定上傳及下載。





8.FileZella Client 登入測試
登入IP:127.0.0.1  (Server IP 因為server開在本機所以是127.0.0.1)
user:scorpio
pw:*******
Port:21 (預設)



連線畫面

2016年10月18日 星期二

Log4j Java 使用xml設定檔

環境
-Intelj13
-log4j1.2.17

範例實作
1.匯入lo4j jar檔







2.建立log4j.xml 設定檔
- 設定檔名稱『一定要叫log4j』,否則系統會抓取不到
- 開頭前2行做為log4j設定檔的宣告
- 所有設定放在log4j:configuration中
- 放在專案src下方









  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <!--宣告log4j.xml的文件型別定義(Document Type Definition, DTD)-->
  3.  
  4. <!--所有log4j的設定都必須放在 <log4j:configuration>...</log4j:configuration>之內 -->
  5. <log4j:configuration>
  6. </log4j:configuration>

3.Log要輸出到哪裡??要長甚麼樣子??,appender設定
(放在
log4j:configuration中)

- Append 定義 log message 『輸出的裝置』及 『log 內容格式』
- log4j.xml 可以設定多個append
  1. <appender name="Console" class="org.apache.log4j.ConsoleAppender">
  2. <layout class="org.apache.log4j.PatternLayout"> <!-- 設定appender的layout為PatternLayout -->
  3. <!-- 設定layout的pattern,參數名為conversionPattern,value為想要的輸出格式 -->
  4. <param name="conversionPattern"
  5. value="%-d{yyyy-MM-dd HH:mm:ss} [%C{5}]-[%p] %m%n"/>
  6. </layout>
  7. </appender>
  1. <!-- DailyRollingFileAppender的第一個log檔並不會加上DatePattern的樣式,
  2. 必須在下一次週期產生的log檔才會加上DatePattern的樣式。
  3. 所以基本上當天產生的log檔算是第一次的log檔,並不會加上Pattern樣式-->
  4.  
  5. <appender name="File" class="org.apache.log4j.DailyRollingFileAppender">
  6. <param name="File" value="D:\system_notice.txt" /> <!--檔案路徑-->
  7. <!--DatePattern是DailyRollingFileAppender的一個重要參數,用來設定檔案輸出的週期-->
  8. <param name="DatePattern" value="'.'yyyy-MM-dd-HH'.log'" />
  9. <layout class="org.apache.log4j.PatternLayout">
  10. <param name="ConversionPattern"
  11. value="%-d{yyyy-MM-dd HH:mm:ss,SSS} [%C{5}]-[%p] %m%n" />
  12. </layout>
  13. </appender>
4.檔案與Log設定的配對(本範例有三種) logger設定(放在log4j:configuration中)
- 補充-概念等於希望把log印出至console也要同時輸出至檔案
  1. <appender-ref ref="Console"/>
  2. <appender-ref ref="File"/>
- 全專案套用
- 某個資料夾全部套用
- 指定要使用哪個Logger
  1. <!--RootLogger(全專案套用)-->
  2. <!--rootLogger的LEVEL設定為DEBUG,DEBUG以上等級的資訊也都會寫出-->
  3. <!--主要class搭配:public static Logger logger = Logger.getLogger(MyPractice.class);-->
  4. <root>
  5. <priority value="DEBUG"/> <!--印出INFO以上的資訊-->
  6. <appender-ref ref="Console"/> <!--將rootLogger的appender參考至剛設定好的Console appender-->
  7. <appender-ref ref="File"/> <!--將rootLogger的appender參考至剛設定好的File appender-->
  8. </root>
  1. <!--整個資料夾套用-->
  2. <!--main class搭配:public static Logger logger = Logger.getLogger("MyPractice.class");-->
  3. <logger name="MyTest"> <!--指定的資料夾-->
  4. <level value="ERROR"/> <!--印出ERROR以上的資訊-->
  5. <appender-ref ref="Console"/> <!--將rootLogger的appender參考至剛設定好的Console appender-->
  6. <appender-ref ref="File"/> <!--將rootLogger的appender參考至剛設定好的File appender-->
  7. </logger>
  1. <!--指定要哪個Logger設定-->
  2. <!--class搭配:public static Logger logger = Logger.getLogger("aa");-->
  3. <logger name="aa"> //替logger取名稱
  4. <level value="INFO"/> <!--印出INFO以上的資訊-->
  5. <appender-ref ref="Console"/> <!--將rootLogger的appender參考至剛設定好的Console appender-->
  6. <appender-ref ref="File"/> <!--將rootLogger的appender參考至剛設定好的File appender-->
  7. </logger>
5.Java檔實際執行記錄
  1. public class MyPractice{
  2. public static Logger logger = Logger.getLogger(MyPractice.class);
  3. public static Logger logger2 = Logger.getLogger("aa");
  4. public static void main(String[] args) {
  5. int num = 0;
  6. try {
  7. System.out.println(num/0);
  8. } catch (Exception e) {
  9. System.out.println(e);
  10. logger.debug("Here is some DEBUG");
  11. logger.info("Here is some INFO");
  12. logger.warn("Here is some WARN");
  13. logger.error("Here is some ERROR");
  14. logger.fatal("Here is some FATAL");
  15. logger2.debug("Here is some aa logger");
  16. logger2.info("Here is some aa logger");
  17. }
  18. }
  19. }

2016年10月10日 星期一

String VS. StringBuffer VS. StringBuilder

1.參考來源:
- http://blog.xuite.net/jane17512001/PenguinDesign/116288109-%E5%AD%97%E4%B8%B2%E8%99%95%E7%90%86(String%E3%80%81StringBuilder%E3%80%81StringBuffer)

- http://puremonkey2010.blogspot.tw/2011/11/java-string-stringbuffer-stringbuilder.html

2.特性介紹:
- String
每次對 String 類型進行改變的時候其實都等同於生成了一個新的 String 對象,然後將指針指向新的 String 對象,所以經常改變內容的字符串最好不要用 String ,因為每次生成對像都會對系統性能產生影響

- StringBuffer
每次結果都會對 StringBuffer 對象本身進行操作,而不是生成新的對象,再改變對象引用。所以在一般情況下我們推薦使用 StringBuffer 
(Java.lang.StringBuffer 可將字符串緩衝區安全地用於多個線程。可以在必要時對這些方法進行同步)

-StringBuilder
從 JDK 5.0 開始,為該類增添了一個單個線程使用的等價類,即 StringBuilder 。與 StringBuffer 相比,通常應該優先使用 StringBuilder 類,因為它支持所有相同的操作,但由於它不執行同步,所以速度更快!

3.結論(效率)
1.在大部分情況下 StringBuffer > String 
例外情況:
- String 較快
  1. String S1 = "This is only a" + "simple" + "test";
- String 較慢
  1. String S2 = "This is only a";
  2. String S3 = "simple";
  3. String S4 = "test";
  4. String S1 = S2 +S3 + S4;

2.在不考慮多執行緒的情況下 StringBuilder > StringBuffer ,因為它支持所有相同的操作,但由於它不執行同步,所以速度更快!

2016年9月30日 星期五

利用 bat (批次檔) 執行java程式 (待補充..)

參考:
http://oldwuwu.blogspot.tw/2013/05/batjava.html

1.一隻簡單的JAVA程式








2.一隻.bat檔(用記事本寫即可)

SET PATH=C:\Program Files\Java\jdk1.6.0_27\bin  (JDK的位置)
javac xxxxx.java   (要進行編譯的xxxx.java檔)
java xxxxx  (同上編譯過後的class檔)
pause  (執行完後,讓命令提示字元畫面停留在螢幕上)




















3.將兩隻檔案放在同一個資料夾










4.點擊『testBat.bat』批次檔,即可看到成果










2016年9月22日 星期四

Build Spring MVC

內容說明
- 建立Spring MVC
- 含有2種做法(1.一般 2. RequestMapping)

範例環境
- Intellj 13
- Spring 3.2.0
- Tomcat 7.0

前置作業
- 參考下列網址提供之 jar 檔下載
- 參考網址:
http://openhome.cc/Gossip/SpringGossip/FirstSpringMVC.html
http://blog.kenyang.net/2010/10/14/spring-mvcspringjar-spring-webmvc

範例實作
目標:
在index.jsp頁面輸入"字串",透過Spring MVC 將"字串"導到hello.jsp


0.檔案目錄結構












1.Tomcat 運行

2.Spring jar 檔匯入

3.web.xml設定

- 注意事項
a.設定『Tomcat』一啟動要進入的url(可自行決定是否加入)
  1. <welcome-file-list>
  2. <welcome-file>/index.jsp</welcome-file>
  3. </welcome-file-list>
b.只要任何url後面為.do(例如:http://localhost:8080/hello.do),就會被『導入』到名稱為mvc-dispatcher的servlet

c.該servlet會在進入/WEB-INF/mvc-config.xml 該設定檔讀取設定(servlet-mapping會去找相同名稱的servlet此範例為name=mvc-dispatcher)

d.
如果今天想要強迫Web Container啟動時
1.就要載入特定的Servlet
2.並且指定載入的順序
那麼就需要<load-on-startup>標籤了
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  6. version="2.5">
  7. <servlet>
  8. <servlet-name>mvc-dispatcher</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <init-param>
  11. <param-name>contextConfigLocation</param-name>
  12. <param-value>/WEB-INF/mvc-config.xml</param-value>
  13. </init-param>
  14. <load-on-startup>1</load-on-startup>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>mvc-dispatcher</servlet-name>
  18. <url-pattern>*.do</url-pattern>
  19. </servlet-mapping>
  20. </web-app>
4.mvc-config.xml 設定

注意:請直接參考code的內容註釋
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--要使用RequestMapping要有下面這句,url進來,到指定的資料夾中找,有設定RequestMapping的Controller-->
  7. <context:component-scan base-package="main"/>
  8. <!--RequestMapping結束-->
  9. <bean id="viewResolver"
  10. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  11. <!--InternalResourceViewResolver的"prefix"、"suffix"屬性會與ModelAndView返回的路徑資訊結合-->
  12. <!--在servlet requestMapping都會把路徑寫好,所以 打 / 就好)-->
  13. <property name="prefix">
  14. <value>/</value>
  15. </property>
  16. <!--讀取"副檔名".jsp開頭的檔案-->
  17. <property name="suffix">
  18. <value>.jsp</value>
  19. </property>
  20. </bean>
  21. <!--第一種MyController沒有用RequestMapping,要特別指定,哪個url進來,要進到哪個controller-->
  22. <!--若有使用RequestMapping,則不需下面這段-->
  23. <!--網址為/hello.do進來的request,要進到哪一個controller-->
  24. <bean name="/hello.do" class="main.MyController">
  25. </bean>
  26. </beans>
InternalResourceViewResolver 的設定不是必要的,如果沒設,處理請求的元件就必須字串告知 spring-webmvc接下來由哪個 URL 組織畫面進行回應,也就是你必須傳回如 "hello.jsp" 這樣的字串,這樣會比較沒有彈性,如上設定 InternalResourceViewResolver 的話,你只要傳回 "hello" 字串,InternalResourceViewResolver 會自動根據 prefix 與 suffix 設定,得知目前實際上要以 "/hello.jsp" 來進行『畫面回應』,將來若想要改為其他回應技術,就只需要修改 XML 檔案。

重點:
所以最後是return『response』回應給傳進來的request

而這個『response』是透過ModeAndView進行組織的,
而『Model 參數』用來攜帶『回應頁面』要用到的資料

5.index.jsp設定
  1. <html>
  2. <head>
  3. <title></title>
  4. </head>
  5. <body>
  6. <form action="/hello.do">
  7. 請輸入名子:<input type="text" name="nameInput">
  8. <input type="submit" value="傳送到一般的Spring">
  9. </form>
  10. <form action="/hello2.do">
  11. 請輸入名子:<input type="text" name="nameInput2">
  12. <input type="submit" value="傳送到requestMapping">
  13. </form>
  14. </body>
  15. </html>
6.hello.jsp設定
  1. <html>
  2. <head>
  3. <title></title>
  4. </head>
  5. <body>
  6. <h1>This is Form Normal Spring:Hello ${nameInput}</h1><br>
  7. <h1>This is From RequestMapping:Hello ${nameInput2}</h1>
  8. </body>
  9. </html>
7.使用基本Spring MVC 的Controller
  1. package main;
  2. import org.springframework.web.servlet.ModelAndView;
  3. import org.springframework.web.servlet.mvc.Controller;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. /**
  7. * Created by ytchen on 2016/9/22.
  8. */
  9. public class MyController implements Controller{
  10. public ModelAndView handleRequest(HttpServletRequest req,
  11. HttpServletResponse res)
  12. throws Exception {
  13. //取得index.jsp輸入的名子
  14. String name = req.getParameter("nameInput");
  15. //參數1:要傳到哪個jsp;參數2:該物件的屬性名稱(前台取值用)參數3:要傳遞的物件或值
  16. return new ModelAndView("hello", "nameInput", name);
  17. }
  18. }
8.使用@RequestMapping Spring 的Controller

- 注意事項
- @RequestMapping 有2種標註方式,一種是標在class,一種是標在method。
- Class類別使用@Controller 標記為Controller
- 請參考:
http://www.blogjava.net/fancydeepin/archive/2014/08/15/springmvc-tutorial-02.html
http://www.cnblogs.com/zhangshitong/p/5195746.html
  1. package main;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.servlet.ModelAndView;
  6. import javax.servlet.http.HttpServletRequest;
  7. /**
  8. * Created by ytchen on 2016/9/22.
  9. */
  10. @Controller
  11. public class MyController2 {
  12. @RequestMapping(value = "/hello2.do", method = {RequestMethod.POST, RequestMethod.GET})
  13. public ModelAndView hello(HttpServletRequest request) {
  14. //取得index.jsp輸入的名子
  15. String name = request.getParameter("nameInput2");
  16. //將request傳到指定jsp
  17. ModelAndView mav = new ModelAndView("hello");
  18. mav.addObject("nameInput2", name);
  19. return mav;
  20. }
  21. }
9.運行畫面
a.index.jsp





b.按下傳送到一般的Spring





c.按下傳送到requestMapping

2016年9月10日 星期六

How To Generate Hibernate Entity With Intellj

說明
- 利用Intellj 連接SQLServer DataBase ,並自動產生Hibernate Entity
- Hibernate 設定檔設置

環境
- Intellj 13
- SQLServer 2012

1.Intellj 連接資料庫

a.建立連線
- 點擊最右側Database長條圖示
- 點擊 + 號新增Database資源連線
- 選擇Driver (此範例使用jTds)
SQL Server有2種不同Driver,以下範例使用jTds(不同Driver後面的設定會有些許不同)















b.帳密設定
- Database:"輸入資料庫名稱"
- User:"輸入帳號"
- Password:"輸入密碼"
- 按下 Test Connection 測試連線,若成功連線,會有下列的圖示的跳出視窗
















c.確認Table
選擇scheme & Table
檢查是否與該資料庫內容一樣













d.替 Intellj 加入 Hibernate Mapping功能
- 成功開啟後,最左邊的欄位,會出現Persistence的長條功能鍵














e.Mapping  Hibernate 與 Database(建立兩者關係)
- 點擊Persistence長條
- 選擇poc(此專案叫poc)並點擊右鍵
- Genetate Persistence Mapping → By DatabaseScheme






















2.Generate Hibernate Entity
- Choose Data Source:選擇上面設定的連線資源
- Package:選擇產出後,要放至哪個路徑
- 需要一些時間來跑
- 找到目標Table (範例Table為:user_information),並點擊勾選

設定檔相關勾選:
1. Add to Scheme Factory:將該xml連線加入指定的xxxx.cfg.xml

2. Generate Column Properties:是某將DB欄位的相關屬性
(流水號identity、資料長度、not null...顯示在hbm.xml上面)


3.Generate SeparateXML per Entity:是否要產生XML檔(本範例不勾選)


若沒有出現任何Table:對著空白處按下『右鍵』,RefreshTable

















3.成功產出畫面














4.額外補充 - SQLServer Driver設定不同處

- 在xxxx.hcfg.xml設定檔中

a.Microsoft







b.jTds





c.Mapping至對映的entity檔案(有無產xml檔,會有不同寫法)

2016年9月8日 星期四

jQuery 動態加載內容(Ajax or append) 事件綁定無效解決辦法:.on()

參考:
http://www.polarxiong.com/archives/jQuery-Ajax%E5%8A%A8%E6%80%81%E5%8A%A0%E8%BD%BD%E5%86%85%E5%AE%B9on-%E7%BB%91%E5%AE%9A%E4%BA%8B%E4%BB%B6%E6%97%A0%E6%95%88%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95.html

1.Problem:
- 新增的『元素』讀取不到『事件』

2.Example:
- new botton 綁定『click』事件 → 出現 alert()
- 但只有寫死的有效動態加載的卻失效
- 舉例:
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="cssName.css">
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  7. <title>aaa</title>
  8. <script>
  9. $(function(){
  10. $('#btn').click(function(){
  11. $('#the_div').append('<button>new button</button>');
  12. })
  13.  
  14. $("#the_div button").click(function(){
  15. alert('clicked');
  16. })
  17. });
  18.  
  19. </script>
  20. </head>
  21. <body>
  22. <div id="the_div">
  23. <button>new button</button>
  24. </div>
  25. <button id="btn">test</button>
  26. </body>

3.Why
- 第一次$(function(){}) 載入html時,只有寫死的new botton有被『註冊
- 後面動態加載的並沒有被載入

4.Solution
- 使用.on方式
- $( document ).on( events, selector, data, handler );
- 舉例,將方法置換成下列程式

  1. $(document).on('click','#the_div button',function(){
  2. alert('clicked');
  3. })

2016年9月5日 星期一

Intellj Java Command Line (命令列參數) 使用

1.注意:
- command line 參數以『String [ ]』的方式存放,所以也要用同樣方式『
- command line 參數,『最先進入』的地方是『main方法

2.範例:
a. Intellj 輸入指令 ( Program arguments: Ian Lillian)(指令間用空白隔開)








b.main方法,透過String[] 接到參數













c.看結果












3.補充-cmd 如何帶參數
- command line 輸入指令(帶在要執行的檔案後面)
- 執行前需要先進行javac 編譯
- javac test.java
- 執行java檔