2012年3月28日 星期三

[ Java 常見問題 ] JFreeChart : 中文亂碼問題


轉載自 這裡
前言 :
最近剛使用JFreeChart 完成項目的圖片導出任務,中文亂碼問題. 以下是我的解決方法.

解決說明 :
直接用代碼來說明, 關鍵就在於使用 Font 來設置顯示的標題與 Label :
  1. /**  
  2. * 配置字體   
  3. * @param chart JFreeChart 對象  
  4. */    
  5. private  void  configFont(JFreeChart chart){    
  6.     // 配置字體    
  7.     Font xfont =  new  Font( "宋體" ,Font.PLAIN, 12 ) ; // X軸    
  8.     Font yfont =  new  Font( "宋體" ,Font.PLAIN, 12 ) ; // Y軸    
  9.     Font kfont =  new  Font( "宋體" ,Font.PLAIN, 12 ) ; //底部    
  10.     Font titleFont =  new  Font( "隸書" , Font.BOLD ,  25 ) ;  //圖片標題    
  11.     CategoryPlot plot = chart.getCategoryPlot(); //圖形的繪製結構對象    
  12.         
  13.     // 圖片標題    
  14.     chart.setTitle( new  TextTitle(chart.getTitle().getText(),titleFont));    
  15.         
  16.     // 底部    
  17.     chart.getLegend().setItemFont(kfont);    
  18.         
  19.     // X 軸    
  20.     CategoryAxis domainAxis = plot.getDomainAxis();       
  21.     domainAxis.setLabelFont(xfont); //軸標題    
  22.     domainAxis.setTickLabelFont(xfont); //軸數值      
  23.     domainAxis.setTickLabelPaint(Color.BLUE) ;  //字體顏色    
  24.     domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);  //橫軸上的label斜顯示     
  25.         
  26.     // Y 軸    
  27.     ValueAxis rangeAxis = plot.getRangeAxis();       
  28.     rangeAxis.setLabelFont(yfont);     
  29.     rangeAxis.setLabelPaint(Color.BLUE) ;  //字體顏色    
  30.     rangeAxis.setTickLabelFont(yfont);      
  31.         
  32. }  

2012年3月26日 星期一

[Python Std Library] String services : struct — Interpret strings as packed binary data


轉載自 這裡
Preface :
在某些時候你可能會需要對 Binary 的資料或是來自網路的 Traffic 進行 Parsing. 在有固定 Format 的情況下, 你可以利用此模組自動幫你進行切割與分析. 底下是原文說明 :
This module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

Functions and Exceptions :
在 struct 模組定義以下的例外與函數 :
- exception struct.error
Exception raised on various occasions; argument is a string describing what is wrong.

- struct.pack(fmt, v1, v2, ...)
根據 fmt 指定將後面的 v1, v2, ... 組合起來並以 binary 返回. 如果 fmt 與 v1, v2, ... 等長度或是數目不符, 會拋出 struct.error.
>>> struct.pack('fh', 1.0, 12)
b'\x00\x00\x80?\x0c\x00'

- struct.pack_into(fmt, buffer, offset, v1, v2, ...)
根據 fmt 將 v1, v2, ... 以 offset 指定的開始位置 pack 到 buffer 中. (New in version 2.5.)
>>> from ctypes import create_string_buffer
>>> b = create_string_buffer(10)
>>> b.raw
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import struct
>>> struct.pack_into("hhh", b, 0, 1, 2, -1) # h->short(2)
>>> b.raw
b'\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00'

- struct.unpack(fmt, string)
將 string 內容以 fmt 規定進行分析並將每個分割的內容以 tuple 回傳. 要注意的是 string 的長度 (in bytes) 必須與 fmt 分析的長度一致 ; 可以使用 len(string) = calcsize(fmt) 檢驗.
>>> bs = struct.pack('hh', 1, 2)
>>> struct.unpack('hh', bs)
(1, 2)
>>> len(bs)
4
>>> struct.calcsize('hh')
4

- struct.unpack_from(fmt, buffer[, offset=0])
New in version 2.5.
根據 fmt 對位置在 offset 指定 buffer 開始位置進行 unpack. (len(buffer[offset:]) must be at least calcsize(fmt))
>>> b = create_string_buffer(10)
>>> b.raw
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> struct.pack_into("hhh", b, 2, 1, 2, -1)
>>> b.raw
b'\x00\x00\x01\x00\x02\x00\xff\xff\x00\x00'
>>> struct.unpack_from("hhh", b, 2)
(1, 2, -1)

- struct.calcsize(fmt)
分析 fmt 預期要分析的資料長度 (in byte).
>>> struct.calcsize('ihL') # i->int(4) ; h->short(2) ; L->unsigned long(4). 4+2+4=12
12

Format Strings :
struct 模組利用定義好的 Format Characters 對資料進行分析與切割, 除此之外有所謂的 Big-endian, Little-endian 也可以參考 Byte Order, Size, and Alignment 進行設定.

- Byte Order, Size, and Alignment
在使用 Format Characters 時, 第一個字元可以用來指定 Byte Order. 而支援的類型可以參考下表 :

(如果第一個字元沒有指定成上述類型, 預設是使用 '@')

Native byte order 是平台相依的, 不同的平台可能是 Big-endian 或是 Little-endia :
Native byte order is big-endian or little-endian, depending on the host system. For example, Intel x86 and AMD64 (x86-64) are little-endian; Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature switchable endianness (bi-endian). Use sys.byteorder to check the endianness of your system.
>>> import sys
>>> sys.byteorder
'little'

- Format Characters
底下是支援資料格式的列表, 你可以組合來定義如何解析資料 :


底下是使用注意事項 :
1. The '?' conversion code corresponds to the _Bool type defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte. (New in version 2.6.)
2. The 'q' and 'Q' conversion codes are available in native mode only if the platform C compiler supports C long long, or, on Windows, __int64. They are always available in standard modes. (New in version 2.2.)
3. When attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a __index__() method then that method is called to convert the argument to an integer before packing. If no __index__() method exists, or the call to __index__() raises TypeError, then the __int__() method is tried. However, the use of __int__() is deprecated, and will raise DeprecationWarning.
4. For the 'f' and 'd' conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f') or binary64 (for 'd') format, regardless of the floating-point format used by the platform.
5. The 'P' format character is only available for the native byte ordering (selected as the default or with the '@' byte order character). The byte order character '=' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the 'P' format is not available.

在使用這些格式字元, 你可以在前面加上數字說明 repeat 的次數. 如 '4h' = 'hhhh' ; 另外如果你在格式字元間夾帶 White space 將會被忽略.

- Examples
底下的範例假設使用 native byte order, 並且 alignment 是 big-endian 的 machine. 先來看看簡單 unpack/pack 三個整數的範例 :
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'\x01\x00\x02\x00\x03\x00\x00\x00'
>>> unpack('hhl', b'\x01\x00\x02\x00\x03\x00\x00\x00')
(1, 2, 3)
>>> calcsize('hhl')
8

更方便的是你可以透過 unpack 回來的 tuple, 用 Python 的語法一一分配給對應變數, 或是使用 namedtuple :


接著我們來看看 little-endian 與 big-endian 的差別 :
>>> import sys
>>> from struct import *
>>> sys.byteorder # 我的 OS 使用 little-endian
'little'
>>> pack('llh', 1, 2, 3)
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00'
>>> pack('>llh', 1, 2, 3) # 使用 big-endian 包裝
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03'


2012年3月24日 星期六

[Python Std Library] String services : string — Common string operations


翻譯自 這裡
Preface :
The string module contains a number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings. In addition, Python’s built-in string classes support the sequence type methods described in the Sequence Types section, and also the string-specific methods described in the String Methods section. To output formatted strings use template strings or the % operator described in the String Formatting Operations section. Also, see the re module for string functions based on regular expressions.

String constants :
在 string 模組, 你有以下常數可以使用 (底下範例需先 import string):
- string.ascii_letters

包含了常數 ascii_lowercase 與 ascii_uppercase.
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

- string.ascii_lowercase / string.ascii_uppercase
直接看下面範例 :
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

- string.digits
>>> string.digits
'0123456789'

- string.hexdigits
>>> string.hexdigits
'0123456789abcdefABCDEF'

- string.octdigits
>>> string.octdigits
'01234567'

- string.punctuation
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

- string.printable
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

- string.whitespace
>>> string.whitespace
' \t\n\r\x0b\x0c'

String functions :
這邊只列出一個常用函數 :
- string.capwords(s[, sep])
這個函數會先使用 str.split() 將字串切成一個個 word, 再使用 str.capitalize() 將word 首字元大寫, 最後便是使用 str.join() 將每個 word 結合. 這邊第二個參數 sep 便是決定 word 要怎麼切與最後怎麼結合 ; 如果為 None 或是沒有給的話, 使用空白 white space.
>>> string.capwords('hi john. long time no see')
'Hi John. Long Time No See' # 多出來的 white space 會被移除, 包含 leading/trailing space.
>>> string.capwords('a-b--c def', '-')
'A-B--C def'

String Formatting :
New in version 2.6.
The built-in str and unicode classes provide the ability to do complex variable substitutions and value formatting via the str.format() method described in PEP 3101. TheFormatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format()method. 接著我們來看看類別 Formatter 提供的方法 :
- format(format_string, *args, **kwargs)
這個函數用法跟 Java/C 的 printf() 雷同, 而 format 的語法可以參考 Format String Syntax. 簡單範例可以參考下面 :
>>> fmt = string.Formatter()
>>> fmt.format("{0} {1}", 'a', 'b')
'a b'
>>> fmt.format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42)
'int: 42; hex: 2a; oct: 52; bin: 101010'

更多 Formatter 的用法可以參考 這裡.

Format String Syntax :
字串物件上的 str.format() 與上面 Formatter 在格式字串語法相同. 在使用格式字串時, 使用 {} 來替換後面的參數. 如果你只是要單純的列印字元 '{' 或 '}', 可以 double 他們成 '{{' 或 '}}' 來取消原有替代字串的功能. 參考範例如下 :
>>> str.format(r"Formta string arg1={0}, arg2={1}. Single brace char : '{{{{' and '}}}}'".format("abc", 123))
"Formta string arg1=abc, arg2=123. Single brace char : '{' and '}'"

在使用 {} 時的一般語法如下所示 :


有看沒有懂? 沒關係我也是. 直接來看幾個範例 :


另外上面有提到 flag conversion ::= "r" | "s" ; 對應到底字串是如何產生. '!s' 指呼叫物件上方法 str() ; 而 '!r' 呼叫物件上方法 repr().

Format Specification Mini-Language :
看完語法後, 接著來看怎麼對字串或特定的資料 (如數字) 進行格式化. 首先來看說明 :


霧煞煞? 沒關係有範例有真相, 先來看看 align 與 fill 的用法 :


接著來看看 align 的說明 :


而 sign 的說明如下 :


接著來看 sign 使用範例 :


至於 precision 則是用來顯示 float point 數值時最多小數位數. 例如 :
>>> "{0:.3f}".format(0.123456) # Only 3 digit after . will show
'0.123'

至於數字的呈現, 可以使用 10進位, 2 進位 16進位 etc. 底下為其格式字元說明 :


接著是範例 :


如果你的參數是 float, 則可以使用的格式字元說明如下 :


Format examples :
基本上目前所說明的格式語法與舊式的 % 用法差異不大. 原本的 '%03.2f' 只要使用 {} 便可以輕鬆改寫成 '{:03.2f}'. 這邊利用一堆範例來複習你剛剛學的格式語法. 首先來看看accessing arguments 的範例 :
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('-', 'abc') # arguments' indices can be repeated
'-abc-'

接著你也可以使用 key arguments 來 mapping :
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

格式語法也可以 access 參數的 attribute :
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point(object):
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

如果你的參數是 Sequence type 也是沒問題的拉 :
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'

另外 conversion 的使用差別可以參考下面範例 :
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

那如果我要對齊字串呢, 使用 align 格式字元 : <, >, = 或 ^ 來完成 :
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'

對於數字的正負號, 其實也有學問的拉 :
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

數字的進位有 2, 8, 10 與 16 進位的選擇 :
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'

如果你要表現一個比較大的數字, 可以使用 comma 讓數字看起來比較有可讀性 :
>>> '{:,}'.format(1234567890)
'1,234,567,890'

至於小數點的精準度 :
>>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 88.64%'

更神奇的是, 連時間的格式化也辦得到喔 :
>>> d = datetime.datetime(1980, 7, 31, 12, 12, 59)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'1980-07-31 12:12:59'

其實格式字元使用還可以更豐富, 如迭代格式字符 etc :

This message was edited 1 time. Last update was at 24/03/2012 21:48:49

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...