6.28.2011

Glancing at the code of 'bitarray'

Python: bitarray パッケージ

bitarray のメインモジュールは以下の2つ。

・__init__.py

インポート

from _bitarray import _bitarray, bits2bytes, _sysinfo
ローカルな関数の定義
def _btree_insert(tree, sym, ba):
def _mk_tree(codedict):
def _check_codedict(codedict):
クラス定義
class bitarray(_bitarray):
クラス関数(一部)
    def decode(self, codedict):
        """decode(code)

Given a prefix code (a dict mapping symbols to bitarrays),
decode the content of the bitarray and return the list of symbols."""
        _check_codedict(codedict)
        return self._decode(_mk_tree(codedict))

    def encode(self, codedict, iterable):
        """encode(code, iterable)

Given a prefix code (a dict mapping symbols to bitarrays),
iterates over iterable object with symbols, and extends the bitarray
with the corresponding bitarray for each symbols."""
        _check_codedict(codedict)
        return self._encode(codedict, iterable)

    def search(self, x, limit=-1):
        """search(x[, limit])

Given a bitarray x (or an object which can be converted to a bitarray),
returns the start positions of x matching self as a list.
The optional argument limits the number of search results to the integer
specified.  By default, all search results are returned."""
        return self._search(bitarray(x), limit)

・bitarray.c

Python.hのインクルード

#include "Python.h"
グローバル変数
typedef struct {
    PyObject_VAR_HEAD
    char *ob_item;
    Py_ssize_t allocated;
    idx_t nbits;
    int endian;
    PyObject *weakreflist;   /* List of weak references */
} bitarrayobject;

static PyTypeObject Bitarraytype;
スタティックな関数(ごくごく一部)
static void
setbit(bitarrayobject *self, idx_t i, int bit)
{
    char *cp, mask;

    mask = BITMASK(self->endian, i);
    cp = self->ob_item + i / 8;
    if (bit)
        *cp |= mask;
    else
        *cp &= ~mask;
}
インストール
/*********************** Install Module **************************/

PyMODINIT_FUNC
init_bitarray(void)
{
    PyObject *m;

    Bitarraytype.ob_type = &PyType_Type;
    BitarrayIter_Type.ob_type = &PyType_Type;
    m = Py_InitModule3("_bitarray", module_functions, 0);
    if (m == NULL)
        return;

    Py_INCREF((PyObject *) &Bitarraytype);
    PyModule_AddObject(m, "_bitarray", (PyObject *) &Bitarraytype);
}

http://pypi.python.org/pypi/bitarray

6.26.2011

Code coverage in Python

Python: コード網羅率の可視化ツール

Python における Code coverage ツールは現時点において以下の2種類である。
インストールコマンドと共に記す。
 ・Code coverage (coverage.py)  => easy_install coverage
 ・trace2html (trace2html.py)  => easy_install trace2html

後者の方がより明解なHTMLで表示されるので、こちらを採用する。

・ヘルプ

   1: Usage: trace2html.py [options]
   2:  
   3: Utility to generate HTML test coverage reports for python programs
   4:  
   5: Example usage
   6: -------------
   7:  
   8: Use trace2html to directly compute the coverage of a test suite by
   9: specifying the module you are interested in::
  10:  
  11:   $ trace2html.py -w my_module --run-command ./my_testrunner.py
  12:   $ firefox coverage_dir/index.html
  13:  
  14: Or you can collect coverage data generated with trace.py::
  15:  
  16:   $ /usr/lib/python2.4/trace.py -mc -C coverage_dir -f counts my_testrunner.py
  17:  
  18: Write a report in directory 'other_dir' from data collected in 'counts'::
  19:  
  20:   $ trace2html.py -f counts -o other_dir
  21:   $ firefox other_dir/index.html
  22:  
  23:  
  24:  
  25: Options:
  26:   -h, --help            show this help message and exit
  27:   -f COVERAGE_FILES, --coverage-file=COVERAGE_FILES
  28:                         Use the content of a trace file
  29:   -o REPORT_DIR, --output-dir=REPORT_DIR
  30:                         Directory to store the generated HTML report. Defaults
  31:                         to 'coverage_dir'
  32:   -s CSS, --with-css-stylesheet=CSS
  33:                         Use an alternative CSS stylesheet
  34:   -t, --self-test       Run the tests for trace2html
  35:   -v, --verbose         Set verbose mode on (cumulative)
  36:   -r, --run-command     Collect coverage data by running the given python
  37:                         script with all trailing arguments
  38:   -b BLACKLIST_MODS, --blacklist-module=BLACKLIST_MODS
  39:                         Add a module to the black list
  40:   -B BLACKLIST_DIRS, --blacklist-dir=BLACKLIST_DIRS
  41:                         Add a directory to the black list
  42:   -w WHITELIST_MODS, --whitelist-module=WHITELIST_MODS
  43:                         Add a module to the white list
  44:   -W WHITELIST_DIRS, --whitelist-dir=WHITELIST_DIRS
  45:                         Add a directory to the white list

基本的な構文は、
 trace2html.py –w Coverageを計測したいモジュール名 [-w モジュール名] –r ユニットテストモジュールのパス
といった塩梅。

・実行例

   1: > trace2html.py -w shogi.state -w shogi.piece -r .\test_state.py
   2: Testing...
   3: .....
   4: ----------------------------------------------------------------------
   5: Ran 5 tests in 5.373s
   6:  
   7: OK
   8: report written to: カレントディレクトリ\coverage_dir\index.html

すると、カレントディレクトリに「coverage_dir」というディレクトリが作成され、配下に計測結果のHTMLが格納される。
image

画面を遷移すると、ソースコードの各行ごとに処理された回数が表示され、未処理の行は赤く表示される。
image

参考:
http://pypi.python.org/pypi/trace2html
http://lab.hde.co.jp/2008/07/pythonunittestcodecoverage-1.html

Bitboards/bitsets in Python (installing .egg file)

Python: ビットボード(またはビットセット)の実装

bitarray パッケージを利用すればよい。
Windows環境におけるセットアップ手順は以下のとおり。

1. setuptools のインストール

以下のURLからexeファイルをダウンロードし実行。(たとえば、setuptools-0.6c11.win32-py2.7.exe
http://pypi.python.org/pypi/setuptools

image 「次へ」

image インストール先が正しいことを確認し、「次へ」

image 「次へ」

image 「完了」

2. bitarray パッケージのインストール

以下のURLからeggファイルをダウンロード。(たとえば、bitarray-0.3.5-py2.7-win32.egg
http://pypi.python.org/pypi/bitarray/

・コマンドプロンプトから、「easy_install eggファイル名」を実行するだけ (easy_install URLでも可とのこと)

   1: >easy_install bitarray-0.3.5-py2.7-win32.egg
   2: Processing bitarray-0.3.5-py2.7-win32.egg
   3: creating e:\python\python27\lib\site-packages\bitarray-0.3.5-py2.7-win32.egg
   4: Extracting bitarray-0.3.5-py2.7-win32.egg to e:\python\python27\lib\site-packages
   5: Adding bitarray 0.3.5 to easy-install.pth file
   6:  
   7: Installed e:\python\python27\lib\site-packages\bitarray-0.3.5-py2.7-win32.egg
   8: Processing dependencies for bitarray==0.3.5
   9: Finished processing dependencies for bitarray==0.3.5
  10:  
  11: >

3. bitarray のテスト

・ユニットテスト

>>> import bitarray
>>> bitarray.test()
bitarray is installed in: E:\Python\Python27\lib\site-packages\bitarray-0.3.5-py2.7-win32.egg\bitarray
bitarray version: 0.3.5
2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]
...........................................................................................
----------------------------------------------------------------------
Ran 91 tests in 3.016s

OK
<unittest.runner.TextTestResult run=91 errors=0 failures=0>
>>> 

・簡単なテスト(論理和、論理積)

>>> from bitarray import bitarray
>>> a = bitarray(10)
>>> a.setall(False)
>>> b = bitarray(10)
>>> b.setall(True)
>>> a
bitarray('0000000000')
>>> b
bitarray('1111111111')
>>> a[1] = True
>>> b[2] = False
>>> a
bitarray('0100000000')
>>> b
bitarray('1101111111')
>>> a & b
bitarray('0100000000')
>>> a | b
bitarray('1101111111')
>>> 


参考:
http://d.hatena.ne.jp/SumiTomohiko/20070609/1181406701
http://peak.telecommunity.com/DevCenter/setuptools

Using multi-byte characters in a Python module

Python: マルチバイト文字列をソースコードに使用する

コメントも含め、Python でマルチバイト文字列をソースに含む場合は、1行目か2行目に以下のようなコメントを書く必要がある。

・UTF-8 を指定する場合

   1: # -*- coding: utf-8 -*-

これはEmacsと互換性のある書き方。
表記は、以下の正規表現にマッチしていればよい。

coding[:=]\s*([-\w.]+)

参考:Python クックブック 第2版 A.2章

6.24.2011

Windows: Run commands!

Windows: 「ファイル名を指定して実行」覚書

マイナーなコマンドのメモ。おそらくWindows XP以降で使用可能。

logoff        ログオフ

shell:personal        マイドキュメントを開く
shell:system        システムフォルダ(system32)を開く
shell:system\drivers\etc\        system32\drivers\etc 配下を開く(パスを「\」で連結可能)

rundll32.exe user32.dll,LockWorkStation        コンピュータのロック

参考:
http://mypchell.com/guides/34-guides/69-156-useful-run-commands
http://suika.fam.cx/~wakaba/wiki/sw/n/shell

6.17.2011

MS Office 2003: SKU011.CAB could not be found

ファイルSKU011.CABからの読み込みに失敗しました

Office 2003 をインストールした後、ユーザの初回アクセス時や
パッチ適用時などに以下のようなメッセージが出現する場合がある。

エラー1309.ファイル(インストールメディアのパス)SKU011.CABからの読み込みに失敗しました。
ファイルが存在するかどうか、また、このファイルへのアクセス権があるかどうかを確認して下さい。

インストールメディアを再度挿入するか、
レジストリの値を変更し、該当のOfficeモジュールのキャッシュを
強制的に無効とすることで解決する。

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\11.0\Delivery\{XX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\CDCache
のデータを「0」に設定
(XXの部分は16進数によるDownloadCode)

参考:
http://www.sku011cab.com/
http://ginolog.blogspot.com/2010/11/ms-office.html
http://support.microsoft.com/kb/896866/en-jp