2012年6月14日木曜日

Python: Separate a list into subsequences using diff

リストを、隣り合う数の差がしきい値より大きい複数のリストに分割したい。


x = [1, 2, 3, 100, 101, 102, 103, 200, 201, 202, 203]
y = [[1, 2, 3], [100, 101, 102, 103], [200, 201, 202, 203]]
に変換したい。


import numpy
thresh = 60
x = [1, 2, 3, 100, 101, 102, 103, 104, 200, 201, 202, 203]
y = [numpy.array(x)[i+1:j+1].tolist()
     for i, j 
     in zip(numpy.concatenate([
                [-1,], 
                numpy.where(numpy.diff(x) > thresh)[0]
              ]), 
            numpy.concatenate([
                numpy.where(numpy.diff(x) > thresh)[0], 
                [len(x),]
              ])
            )
     ]

2012年6月4日月曜日

複数行を1行にまとめるコマンド

paste を使えば、複数行をまとめられる。

# ls
dira
dirb
filea

の場合、
# ls | paste -s
dira dirb filea
と出力される。

2012年2月18日土曜日

emac flyspell

emacs で M-x flyspell-mode とすると、スペルチェックをしてくれる。

apt-get install aspell-en
とかを入れとくとよい

また、
echo "lang en_US" > ~/.aspell.conf
をする必要がある。

Reference: 
http://d.hatena.ne.jp/mooz/20091107/p1

2012年2月15日水曜日

python で記憶つきの関数を作る

関数に静的変数を使いたいときは、 クラス +  __call__ を使う。
オブジェクトを作っておけば、そのオブジェクトを呼び出したとき (= __call__呼び出し) に色々できる。


例えば、3の倍数が与えられたときだけカウントする関数 memory
class Memory:
    def __init__(self):
        self.count = 0
    def __call__(self, i):
        if i % 3 == 0:
            self.count += 1
        return self.count

if __name__ == "__main__":
    memory = Memory()
    for i in range(10):
        print i, memory(i)


結果が以下。
左列がカウント, 右列が3で割った余りが0の数。

0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3
9 4


2012年1月31日火曜日

pylab でプロットした画像の余白を消す方法 その2

以前は Inkscape を使う方法を紹介したが、
http://mzmttks.blogspot.com/2011/03/pylab.html

pylab.savefig のオプションで、画像生成時に余白を消せる。

pylab.savefig("filename", bbox_inches="tight", pad_inches=0.0)

ちょっとだけつけたければ pad_inches に値を入れればよい。
これは、画像のフォーマットによらない。

Thanks @miracjp

2012年1月29日日曜日

HTML5 Canvas ratio is strange

HTML5 の Canvas で描画したとき、拡大されているように見える。

これは、
canvas の attribute の width, height と,  style の width, height が一致していないのが原因。

つまり、以下の設定で
< canvas height="H1" style="height: H2; width: W2;" width="W1">
W1 != W2
H1 != H2
のとき、描画が拡大/縮小されているように見える。


English:
If the drawn figure of canvas in HTML5 is strange, check the width and height.
if the ATTRIBUTE of them and STYLE of them are not the same,
this is the reason.

In other words,
in the following tag:
   [lt] canvas height="H1" style="height: H2; width: W2;" width="W1" [gt]
if W1 != W2 or H1 != H2, the ratio is not valid.

2011年12月12日月曜日

wsgiref を使ってpythonで書いた HTTPサーバで画像をアップロード


結構大変だったのでメモ。参考文献は忘れたのでパス。
HTTPでアクセスできるサーバを、 wsgiref というモジュールで書きました。

以下のプログラムどっかでを実行して、
http://localhost:8080 にブラウザからアクセスすると、フォームが現れます。
ブラウザから画像を選択 -> サーバがカレントディレクトリに aaa.png という名前で保存します。

import cgi, StringIO
from wsgiref import simple_server
import numpy, Image

class Selector(object):
    def __init__(self, table, notfound = None):
        tmp = sorted(table, key=lambda x:len(x), reverse=True)
        table = [(x, table[x]) for x in tmp]
        self.table = table # url table
        if notfound:
            self.notfound = notfound # when not found

    def __call__(self, environ, start_response):
        name = "SCRIPT_NAME"
        info = "PATH_INFO"

        scriptname = environ.get(name, "")
        pathinfo = environ.get(info, "")

        for p, app in self.table:
            print p, pathinfo
            if p == "" or p =="/" or pathinfo.startswith(p):
                print app
                return app(environ, start_response)

        if pathinfo == p or pathinfo.startswith(p) and pathinfo[len(p)] == "/":
            scriptname = scriptname + p
            pathinfo = pathinfo[len(p):]
            environ[name] = scriptname
            environ[info] = pathinfo
            return app(environ, start_response)

        return self.notfound(environ, start_response)

    def notfound(self, environ, start_response):
        start_response('404 Not Found', [('Content-type', 'text/html')])
        fp = StringIO.StringIO()
        fp.write(r"""<html><header><title>Not Found</title></header>
<body> 
<H1> URL not found. </H1>
<ul>
""")
        for entry in self.table:
            fp.write(r"<li/> %s %s" % (entry[0], entry[1]))
        fp.write(r"</ul></body></html>")
        fp.seek(0)
        
        return fp

def imageupload(environ, start_response):
    try:
        clen = int(environ["CONTENT_LENGTH"])
    except:
        clen = 0

    f = cgi.FieldStorage(fp=environ["wsgi.input"], 
                         environ=environ, 
                         keep_blank_values=True)
    handle = open("aaa.png", "wb")
    handle.write(f["filename"].file.read())
    handle.close()


    fp = StringIO.StringIO()
    fp.write(r"<html><body> environmental variables <dl>")

    for key in sorted(environ.keys()):
        fp.write(r"<dt>%s</dt><dd>%s</dd>" % (key, environ[key]))
    fp.write(r"</dl></body></html>")
    fp.seek(0)
    
    start_response("200 OK", [("Content-type", "text/html")])
    return fp

def showtop(environ, start_response):
    start_response("200 OK", [("Content-type", "text/html")])
    return r"""<html><body> 
imageupload 
<form action="/image" enctype="multipart/form-data" method="post">
<input type="file" name="filename"><input type="submit" value="Upload">
</form>
</body></html>"""

if __name__ == '__main__':
    application = Selector({"/":showtop, "/image":imageupload})
    srv = simple_server.make_server('', 8080, application)
    srv.serve_forever()