廣告

2015年3月7日 星期六

[python] FILE I/O (read) & to Dictionary | FILE I/O (write) & input(raw_input)


readFile.py
import pickle
#save object type

file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part



print people

print '=========use pickle======'

file.close()

pick = open('picktest.txt','w')
pickle.dump(people,pick)
pick.close

pick = open('picktest.txt')
people = pickle.load(pick)
print(people)


consol
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

{'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], 'jim': ['3', 'jim', '170', '60'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}
=========use pickle======
{'jim': ['3', 'jim', '170', '60'], 'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}


people.txt

1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70


writeFile.py
#inpput can't get blank

count = input("input how many people:")

list = []

for x in range(count):
        print 'input number name height weight,splite by blank'
        a = raw_input("-->:")
        list.append(a)


print 'your input is ' ,list


f = open('people2.txt','w')
for x in list:
        f.write(x+"\n")

f.close()

consol

([pythonTutorai])lewis@lewis-virtual-machine:~/pythonTutorial/tutorial2$ python writeFile.py
input how many people:3
input number name height weight,splite by blank
-->:6 aa 134 11
input number name height weight,splite by blank
-->:7 bb 431 233
input number name height weight,splite by blank
-->:8 cc 167 70
your input is  ['6 aa 134 11', '7 bb 431 233', '8 cc 167 70']

people2.txt
6 aa 134 11
7 bb 431 233
8 cc 167 70

[python]Passing by reference or value| mutable type &immutable type




variable asign in python is  just a reference,
and all data is object.

但是又分為mutable type (list) & immutable type (String)

Function:
  mutable type  :reference
  immutable type:value


範例如下:




print 'List (mutable type)'
def ange_list_reference(the_list):
    print 'got', the_list
    the_list = ['and', 'we', 'can', 'not', 'lie']
    print 'set to', the_list

outer_list = ['we', 'like', 'proper', 'English']

print 'before, outer_list =', outer_list
ange_list_reference(outer_list)
print 'after, outer_list =', outer_list

print '==================================='


print 'String(immutable type)'

def try_to_change_string_reference(the_string):
    print 'got', the_string
    the_string = 'In a kingdom by the sea'
    print 'set to', the_string

outer_string = 'It was many and many a year ago'

print 'before, outer_string =', outer_string
try_to_change_string_reference(outer_string)
print 'after, outer_string =', outer_string


print 'Int (immutable type)'

def change_int(the_int):
    print 'got', the_int
    the_int = '9'
    print 'set to ',the_int

outer_int  = 1

print 'before ,outer_int=',outer_int
change_int(outer_int)
print'after ,outer_int=' ,outer_int



print 'asign operation is use reference not copy'
print 'example:'
L = [1,2,3]
M = ['X' ,L, 'Y']
print M
print 'set L[0]=9'
L[0]=9
print M
print 'the content of M will be set too'


print'============='
print 'if dont want set M, you need use copy'
L = [1,2,3]
M = ['X',L[:],'Y']
print M
print 'set L[0]=9'
L[0] = 9
print M
print 'the content of M wont be set '

consol
===================================
String(immutable type)
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
Int (immutable type)
before ,outer_int= 1
got 1
set to  9
after ,outer_int= 1


asign operation is use reference not copy
example:
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [9, 2, 3], 'Y']
the content of M will be set too
=============
if dont want set M, you need use copy
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [1, 2, 3], 'Y']
the content of M wont be set

2015年3月6日 星期五

[ubuntu] Configure Static IP Address on Linux VM in VMware Player


Everytime I use putty to connect VM,
It's ip will be changed.
This situation is very annoying.
So i decide to set static.IP
There are three networking options for virtual
machines running there: Bridged, NAT, Host-Only.
I use NAT in order to coneect web.
see this  BLOG for detail

$ sudo vim /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5)
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet static
  address 192.168.22.146
  netmask 255.255.255.0
  broadcast 192.168.22.255
  gateway 192.168.22.2
dns-nameservers 192.168.22.2


you need to restart
$ sudo service networking restart


then you will encounter a problem,
lewis@lewis-virtual-machine:~$ sudo service networking restart
stop: Job failed while stopping

let's to check log
lewis@lewis-virtual-machine:~$ sudo  tail -f /var/log/upstart/networking.log
Stopping or restarting the networking job is not supported.
Use ifdown & ifup to reconfigure desired interface.

//it indicate that not supported

So use this to do
$ sudo ifdown eth0 && ifup eth0
$ sudo /etc/init.d/networking restart


ref:

2015年3月5日 星期四

[java] monitoring menory & try list.clear() vs new List : Which one will be better


package test_fb_api;

import java.util.ArrayList;
import java.util.List;

public class testMemory {

    public static void main(String[] args) {

        int kb = 1024;

        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();

        //Print used memory
        System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / kb);

        //Print free memory
        System.out.println("Free Memory:" + runtime.freeMemory() / kb);

        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / kb);

        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / kb);

        List list = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 10000; j++) {
                list.add("abcdefghij" + i + j);
            }
            if (i % 200 == 0) {
                try {
                 System.gc();
                    Thread.sleep(100);
                    System.out.println("Free Memory:" + runtime.freeMemory() / kb + " Kb");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        System.out.println("done");
    }
}


you can add code to line38 to monitoring
1. list.clear
2. list = new list();

ref:http://stackoverflow.com/questions/6757868/map-clear-vs-new-map-which-one-will-be-better

2015年3月4日 星期三

[ubuntu] cp


cp -r getBookList    / /opt/app/abStore/data/Ibobar/getBookList
       來源             目的地

-a  :相當於 -pdr 的意思,至於 pdr 請參考下列說明;(常用)
-d  :若來源檔為連結檔的屬性(link file),則複製連結檔屬性而非檔案本身;
-f  :為強制(force)的意思,若目標檔案已經存在且無法開啟,則移除後再嘗試一次;
-i  :若目標檔(destination)已經存在時,在覆蓋時會先詢問動作的進行(常用)
-l  :進行硬式連結(hard link)的連結檔建立,而非複製檔案本身;
-p  :連同檔案的屬性一起複製過去,而非使用預設屬性(備份常用);
-r  :遞迴持續複製,用於目錄的複製行為;(常用)
-s  :複製成為符號連結檔 (symbolic link),亦即『捷徑』檔案;
-u  :若 destination 比 source 舊才更新 destination

[java][log4j] Install Log4j & how to use it


1. 下載log4j的jar檔 (log4j.1.12.17.jar)

2. 放到C:\Users\1409035\workspace\NewsstandWS\web\WEB-INF\lib 底下

3. 新增一個log4j_WS.properites檔放到
   C:\Users\1409035\workspace\NewsstandWS\web\WEB-INF\properties 底下
   設定內容直接參考code

4. 新增 Log4JInitServlet.java 到
   C:\Users\1409035\workspace\NewsstandWS\src\java\com\ws\controller
   做為初始化用 

5. 修改 web.xml 新增如下
   
    Log4JInitServlet
    com.ws.controller.Log4JInitServlet
     
    log4j-properties-location
        /WEB-INF/properties/log4j_WS.properties
     
    1 
   

6. 使用範例
   final Logger log = Logger.getLogger(GetZinioDataJobs.class);
   log.info("orderBook info message");




參考:
http://www.programcreek.com/2009/06/a-simple-example-to-show-how-to-use-java-properties-file/ [^]
http://www.avajava.com/tutorials/lessons/how-do-i-initialize-log4j-in-a-web-application.html [^]
http://www.codejava.net/coding/how-to-initialize-log4j-for-java-web-application [^]
http://toyangel.pixnet.net/blog/post/32953401-eclipse-%E4%BD%BF%E7%94%A8-log4j-%E7%9A%84%E5%BF%AB%E9%80%9F%E8%A8%AD%E5%AE%9A [^]


簡單版:
log4j.properties
直接放到src/java下面

web.xml
也可拿掉上述所新添加的部分。


===========================================
原因:
tomcat 啟動時的順序-->
tomcat --> AP(newsstands) -->看底下web-inf 裡面的classes jar, 
因為log4j 已經有default , 且我又將 properties 命名為 logj4.properties
所以他default找的到這隻,
如果我不命名為 logj4.properties,
就要遵循 本篇一開始的步驟

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


將log4j改為 大於 10M 就產生新的檔案
# A2 is set to be a file
# produce log record document every day
#log4j.appender.A2 = org.apache.log4j.FileAppender
log4j.appender.A2 = org.apache.log4j.RollingFileAppender
log4j.appender.A2.layout = org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern = [%d{yyyy-MM-dd HH:mm}][%p][%C-%L] %m%n
log4j.appender.A2.File =/volume1/homes/tomcatupload/logs/system_notice.log
log4j.appender.A2.MaxFileSize=10MB 

log4j.appender.A2.DatePattern = '.'yyyyMMdd-HHmm


log4j寫到不同file
=======================================================================
  log4j.rootLogger=TRACE, stdout

  log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

  log4j.appender.debugLog=org.apache.log4j.FileAppender
  log4j.appender.debugLog.File=logs/debug.log
  log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
  log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

  log4j.appender.reportsLog=org.apache.log4j.FileAppender
  log4j.appender.reportsLog.File=logs/reports.log
  log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
  log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

  log4j.category.debugLogger=TRACE, debugLog
  log4j.additivty.debugLogger=false

  log4j.category.reportsLogger=DEBUG, reportsLog
                 可自訂 可自訂
  log4j.additivty.reportsLogger=false
 

  [The configure the loggers in the Java code thusly:]

  static final Logger debugLog = Logger.getLogger("debugLogger");
  static final Logger resultLog = Logger.getLogger("reportsLogger");
=========================================================================
[Do you want output to go to stdout? If not, change the first line of log4j.properties to:]

  log4j.rootLogger=OFF
  and get rid of the stdout lines.


參考http://stackoverflow.com/questions/9652032/how-can-i-create-2-separate-log-files-with-one-log4j-config-file [^]



[java]use "return" is better than System.eixt(0)


Because as far as the compiler is concerned, 
System.exit() is just another method call.

The fact that what it does is end the process can only 
be found out from the implementation 
(which is native code, not that it makes any difference).

If you have to put System.exit() in your code 
(usually it's best to avoid it, unless you want to return a code other than 0), 
it should really be in a method that returns void, main() for example. It's nicer that way.

As for the reachability, the explanation is the same: 
return is a keyword of the Java language, 
so the compiler or the parser the IDE uses can tell 
that it's theoretically impossible for code after the return statement to be executed.