2016年4月17日日曜日
2016年4月7日木曜日
.screenrc
term screen-256color
escape ^Oo
termcapinfo xterm* ti@:te@
hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%t%n*%f%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %m-%d %{W}%c %{g}]'
チートシート:
http://www.pixelbeat.org/lkdb/screen.html
2016年2月20日土曜日
pythonのスクリプトファイルとの相対パス
import os
this_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(this_dir, 'lib')
print filename
2016年2月19日金曜日
python によるPID のロック
import time
import os
import sys
pid = str(os.getpid())
pidfile = "/tmp/scripy.pid"
if os.path.isfile(pidfile):
print "exit"
sys.exit(0)
file(pidfile, 'w').write(pid)
try:
f = open('workfile', 'a')
f.write("1")
f.close
time.sleep(10)
finally:
os.unlink(pidfile)
2015年12月31日木曜日
MRIをでバックビルドしてgdbでデバッグ
MRIのビルド
./configure時の–enable-debug-envオプションは、コンパイラによる最適化を抑止してgdbでソースをおえるようにしてくれているはず。 システムのrubyと競合しないように–prefixでインストール先を指定する。
./configure --enable-debug-env --prefix /home/sato/ruby/ CFLAGS="-g3 -O0"
make
make install
環境変数を設定
さっきインストールしたrubyの実行ファイルが呼び出されるように環境変数を設定してやる。
RUBYPATH=$HOME/ruby/bin
export RUBYPATH
export PATH=$RUBYPATH:$PATH
export RUBYLIB=$RUBYPATH/lib/ruby
gdb用のヘルパーをホームディレクトリに入れておく
rubyの内部のデータは殆どがVALUEポインタで表現され、後でキャストしてから使用される。 この時、キャスト後が何のデータであるかがわからなければ、gdbのprintで中を覗くことができない。 このため、rubyのソースにバンドルされているgdb用のヘルパーを使う。
以下からダウンロード
https://github.com/ruby/ruby/blob/trunk/.gdbinit
cp .gdbinit ~/
定義されたヘルパーの一覧はhelp user-definedで見ることができる。
(gdb) help user-defined
User-defined commands.
The commands in this class are those defined by the user.
Use the "define" command to define a command.
List of commands:
******略******
rb_p -- User-defined
rb_ps -- Dump all threads and their callstacks
rb_ps_thread -- User-defined
rb_ps_vm -- Dump all threads in a (rb_vm_t*) and their callstacks
rbi -- User-defined
rp -- Print a Ruby's VALUE
rp_class -- Print the content of a Class/Module
rp_id -- Print an ID
rp_imemo -- Print the content of a memo
rp_string -- Print the content of a String
ruby_gdb_init -- User-defined
sdr -- User-defined
重要なのはrpで、これでVALUEの中身を知ることができる。
irbを起動しgdbをアタッチ
irb
まず、起動したirbのプロセスIDを調べる。
$ ps x|grep irb
1742 pts/1 Sl+ 0:00 irb
別のターミナルから起動したirbにアタッチする。
gdb /home/sato/ruby/bin/irb -p 1742
ブレークポイントを設定してみる。
(gdb) b proc_curry
Breakpoint 3 at 0x7f60aa2bff64: file proc.c, line 2755.
(gdb) c
Continuing
proc_curryはProc#curryのC側での実装。 以下の関数がそれにあたる。
rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
static VALUE
proc_curry(int argc, const VALUE *argv, VALUE self)
{
int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
VALUE arity;
rb_scan_args(argc, argv, "01", &arity);
if (NIL_P(arity)) {
arity = INT2FIX(min_arity);
}
else {
sarity = FIX2INT(arity);
if (rb_proc_lambda_p(self)) {
rb_check_arity(sarity, min_arity, max_arity);
}
}
return make_curry_proc(self, rb_ary_new(), arity);
}
この状態で、irb側から以下のようにProc#curryを呼び出す
Proc.new {|x,y|x+y}.curry
gdbがbreakする。
Breakpoint 1, proc_curry (argc=0, argv=0x7f48ea86d258, self=139951178000880) at proc.c:2755
warning: Source file is more recent than executable.
2755 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
コードの中の現在位置を確認
(gdb) l
2750 * p b.curry[] #=> :foo
2751 */
2752 static VALUE
2753 proc_curry(int argc, const VALUE *argv, VALUE self)
2754 {
2755 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
2756 VALUE arity;
2757
2758 rb_scan_args(argc, argv, "01", &arity);
2759 if (NIL_P(arity)) {
selfのVALUEポインタを見てみる。
(gdb) rp self
T_DATA(proc): $4 = (struct RTypedData *) 0x7f48ec4029f0
(gdb) print *(struct RTypedData *) self
$5 = {basic = {flags = 12, klass = 139951178175800}, type = 0x7f48eae51ca0 <proc_data_type>,
typed_flag = 1, data = 0x7f48ec85bd80}
(gdb) print (*(struct RTypedData *) self)->basic
$6 = {flags = 12, klass = 139951178175800}
(gdb) print (*(struct RTypedData *) self)->basic->klass
$7 = 139951178175800
2015年12月20日日曜日
Haskell入門者のための素晴らしいサイト3つ
最近、Haskellを勉強しています。型クラス、型コンストラクタ、Functor、Applicative、Monoid、Monad、カリー化などなど、他のプログラミングにない謎な概念のおかげで かなりとっつきにくいです。しかし、とてもおもしろい。純粋な関数型言語で関数や型に対する厳密な制約を を持っているにもかかわらず、様々な工夫で生産性を下げないようにしています。(JAVAみたいにならない)
そんなHaskellの入門中に、これは素晴らしいと思ったHaskell入門用のサイトが以下の3つ。
Learn You a Haskell for Great Good!
書籍だが、webで無料公開している。 日本語版の本が「すごいHaskellたのしく学ぼう!」のタイトルで出版されている。 入門者が最初にみるべきだと思う。Haskellの謎な概念を丁寧に解説してくれている。書籍版の購入がオススメ。
ペンシルバニア州立大学の講義、Haskell初心者に大人気で、ペンシルバニア大学の学生以外も勝手にやっている。
講義資料と宿題があり、といていくとHaskell的なプログラムを書けるようになる。
再帰を頻繁に使い、手続き型言語しかやっていない人は確実に躓く。アメリカの大学だけあってさすがに難度が高い。
欠点は講義資料という性質上、宿題の答えが用意されていないことだが、githubで検索すると自分なりの回答を載せている人がたくさんいるため参考にできる。
Fpcompleteという会社の解説記事。関数の呼び出し方のような基本的な内容から、並列処理の実装方法といった応用的なのまで 揃っている。CIS 194で詰んだら、見てみよう。
2015年10月23日金曜日
Ruby Net::HTTPの使い方と(直接)使うべきでない時
rubyで単純なHTTP Getをするのであれば、openuriが圧倒的に便利ファイルと同じように、http getリクエストを扱えてしまう。
しかし、比較的複雑なリクエスト(例:POST、ヘッダに何か入れる)の場合、net/httpを使う。
最も単純なGET
Net::HTTPでのgetは以下のようになる。 この程度ならopenuriを使った方が良い。
require "net/http"
# レスポンスをブロックの外で使いたい時には事前に定義しておこう
# ブロックがクロージャであることを忘れずに
response=nil
uri = URI.parse("http://example.net/")
Net::HTTP.start(uri.host, uri.port) do |http|
response = http.get("/index.html")
puts response.code # ステータスコード
puts response.message # メッセージ
puts response.body # レスポンスボディ
end
puts response.message # => OK
以下のようにインスタンスを作成してからコネクションを開く事もできる。
しかしこの場合には、最後にクローズしないとだめ。忘れるとシツレイ。
startにブロックを渡せば、ファイルオープンと同じように最後にクローズを勝手にやってくれるので安心。
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new("/index.html")
http.close
HTTPSへのGET
以下のようにstartの引数に:use_ssl=>trueを渡してやる。
require "net/http"
uri = URI.parse("https://example.net/")
Net::HTTP.start(uri.host, uri.port,:use_ssl=>true) do |http|
response = http.get("/index.html")
puts response.body
end
POSTの場合
require "net/http"
uri = URI.parse("http://example.net/")
Net::HTTP.start(uri.host, uri.port) do |http|
response = http.post("/search.cgi",'query=foo',header=nil)
puts response.code
puts response.message
puts response.body
end
素晴らしいNet::HTTP解説のリンク
チートシート
http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
RestでJSONリクエストを投げる例。
https://www.socialtext.net/open/very_simple_rest_in_ruby_part_3_post_to_create_a_new_workspace
http://altarf.net/computer/ruby/2890
restを作る時に便利なgem
https://github.com/rest-client/rest-client
以下に該当する場合にはNet::HTTPを使うべきでない。
単純なGETしかしない
→openuriを使う
http://ruby-doc.org/stdlib-2.1.0/libdoc/open-uri/rdoc/OpenURI.html
クローラーを作りたい
→anemoneを使う
https://github.com/chriskite/anemone
Amazonの商品検索、操作APIを使いたい
→asinを使う
https://github.com/phoet/asin
AWSのRESTを使いたい
→aws-sdk-rubyを使う
https://github.com/aws/aws-sdk-ruby
なんかRESTを使いたい。
→rest-clientを使う
https://github.com/rest-client/rest-client
2015年10月22日木曜日
2015年10月17日土曜日
10分でdocker入門
10分でdocker入門
近年、Linuxカーネが導入したcgroupなどの機能によって、コンテナによる仮想化が可能になった。 OSのファイルシステムや、CPU、メモリなどのリソースをプロセスごとに割り振り、お互いを孤立されることができるようになったことで、 1つのマシンの中にコンテナと呼ばれる仮想のマシン環境を作っていくことができるらしい。VMwareやVirtualBoxとくらべて、区画を作るだけな分、リソースの使用効率が良く、高速らしい。 使ってみた感想は、兎に角速い。VMwareやVirtualBoxに比べて、とにかく仮想環境の作成が早くできる。 コンテナはむこうと違って異るカーネルの環境は作れないが、この速さは一定の環境でのソフトウェアの動作を検証したい時などにとても便利。 たとえばインストーラの動作確認をするなら是非使いたい。
インストール
cat >/etc/yum.repos.d/docker.repo <<-EOF
[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/7
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
EOF
yum install docker-engine -y
起動
docker daemon
(service docker startでも良いはずだがそっちはエラーが出た)
イメージのダウンロード
https://hub.docker.com/explore/でイメージを探して
sudo docker pull centos
sudo docker images
コンテナの中でshellを立ち上げて、ユーザーを作ってみる。
07:15:19 sato@localhost docker $ sudo docker run -i -t centos /bin/bash
[sudo] password for sato:
[root@d0f14de7ac35 home]# useradd nyanchu
[root@d0f14de7ac35 home]# su - nyanchu
[nyanchu@d0f14de7ac35 ~]$
[nyanchu@d0f14de7ac35 ~]$ exits
[root@d0f14de7ac35 /]# exit
exit
さっき抜けたコンテナを確認
07:16:26 sato@localhost docker $ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d0f14de7ac35 centos "/bin/bash" About a minute ago Exited (130) 44 seconds ago hopeful_engelbart
再度コンテナに接続
終了しているので最初に起動してやる必要がある。
さっき作ったユーザーが存在しているのがわかる。
07:17:17 sato@localhost docker $ sudo docker start d0f
d0f
07:17:27 sato@localhost docker $ sudo docker attach d0f
[root@d0f14de7ac35 /]# su nyanchu
[nyanchu@d0f14de7ac35 /]$ ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
コンテナからイメージを作成
12:28:49 root@localhost ~ $ docker commit d0f my_image
d583edebf68931c8aa5b52565a3b0182f759a79b4b0924d040468c8241bfa19a
docker imagesでできたイメージの確認
12:29:10 root@localhost ~ $ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
my_image latest d583edebf689 10 seconds ago 263.7 MB
centos latest e9fa5d3a0d0e 3 days ago 172.3 MB
作ったイメージからコンテナを作成
作成したイメージに作って置いたユーザーが最初から存在することが確認できる。
12:30:36 root@localhost ~ $ docker run -i -t my_image /bin/bash
[root@e12f0ec2d79f /]# su - nyanchu
Last login: Sat Oct 17 03:22:52 UTC 2015 on console
[nyanchu@e12f0ec2d79f ~]$
2015年9月27日日曜日
rubyのテクニック覚書
rubyの勉強をしていくうちに、好ましい記述法や技術が分かってきた。
正規表現でマッチした文字を取り出したいだけ時にはmatchメソッドや=^メソッドではなくString型の[]メソッドが最も短く書ける
p "@@@@@hoge@@@@@"[/[a-z]+/] #=> "hoge"
パーセント記法はとても便利、場合によってはかなりみやすくなる。
p %s|symbol| #=> :symbol
p %w|abc def gh| #=> ["abc", "def", "gh"]
p %x|ruby -v| #=> "ruby 2.1.4p265 (2014-10-27 revision 48166) [x86_64-linux]\n"
p %r|[A-Z]| #=> /[A-Z]/
ある配列から他の配列を作りたいときなどに、以下のようにeachの前で結果を入れるための配列を初期化しておくのは冗長
array=[1,2,3,4,5,6]
array2=[]
array.each{|i| array2 << i * 2}
p array2 #=> [2, 4, 6, 8, 10, 12]
以下のようにmapメソッドで関数型言語の流儀で書くべき。
array=[1,2,3,4,5,6]
array2 = array.map{|i| i * 2}
p array2 #=> [2, 4, 6, 8, 10, 12]
条件によって要素を外したい、条件に合う要素のみの配列を作りたい場合にはreject,selectメソッドがよい。
さらに、配列からハッシュを作りたいときなどには、以下のようにreduceメソッドがよい。
array=[1,2,3,4,5,6]
hash = array.reduce({}){|h,i| h[i]= i*2; h }
p hash #=> {1=>2, 2=>4, 3=>6, 4=>8, 5=>10, 6=>12}
case文は===演算子で含有関係が評価されため、単純な一致の場合以外にも使える。
Integerの場合にはRangeがそれを含むかどうかを評価できる。
i = 10
case i
when 1..50
puts 'small'
when 51..10
puts 'big'
end
Stringの場合には正規表現が使える。
str = 'dojadf@ss'
case str
when /@/
puts "include @"
when /[a-z]+/
puts "only small letter"
end
2015年8月30日日曜日
PyCharm, RubyMineでのデバック時の変数の表示をprint文(p文)で
こちら
もちろん、ブレイクポイントを作れば、停止時に変数の中身は全て見えるが、複雑なクラスの場合、みたい部分がどこにあるかわからなかったりするので、print文の方が便利。
同じJetBrain製のIDEのRubyMineも似たような感じでできるでしょう。(多分)
2015年8月15日土曜日
one hot encoding (python scikit-learn)
pythonのscikit-learnで以下のように、この変換ができる。
次のような、accounts.csvがあると仮定する。
name,occupation
sato,adventurer
ito,engineer
inoue,student
tanaka,engineer
oda,adventurer
基本的にはDictVectorizerに入れるだけだが、その前に[(occupation=adventurer),(occupation=engineer)]のようなディクショナリの配列にする必要がある。
# -*- coding: utf-8 -*-
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
accounts=pd.read_csv('./accounts.csv', encoding='utf-8')
occupation_vectorizer = DictVectorizer(sparse=False)
i = [ dict(occupation=occupation) for occupation in accounts[u"occupation"] ]
X = occupation_vectorizer.fit_transform(i)
names = occupation_vectorizer.get_feature_names()
# original table
print accounts
# label names
print names
# transformed one-hot encoding
print X
結果
name occupation
0 sato adventurer
1 ito engineer
2 inoue student
3 tanaka engineer
4 oda adventurer
[u'occupation=adventurer', u'occupation=engineer', u'occupation=student']
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 1. 0.]
[ 1. 0. 0.]]
2015年8月7日金曜日
Rails runnerの簡単な使い方
実行の方法は2つある。
- Railsで作成したアプリのメソッドを直に指定してやる
- ファイルを読み込ませる
個人的には、Webアプリと独立したバッチ処理を長々とWebアプリにメソッドとして追加するのは違和感があるので(2)の方が良い気がする。 それに、autoload_pathsを変更しなくていいので簡単。
例:
予めRailsルートはいかにrunner/を作っておく。mkdir runner
あとは適当なファイルを作って呼び出すだけ。runner/runner.rb
# Railsでつくったアプリが読み込まれてから実行されるので、何もrequireしなくてもActive Record経由でモデルにアクセスできる
# この場合はTagという名前のモデルが存在する環境
p Tag.count
成功。
$ rails runner runner/runner.rb
21931
2015年8月4日火曜日
AmazonAPIとruby gem asin
https://github.com/phoet/asin
上記ではcurbを使ってアクセスしているが何故かうまくいかなかった。
かわりにhttpiを使うと動いた。
直接、ハッシュを返してくれるので楽。
require 'asin'
require 'httpi'
# Setting for amazon API
include ASIN::Client
ASIN::Configuration.configure do |config|
config.secret = 'SECRET'
config.key = 'SECRET'
config.associate_tag = 'SECRET'
config.host = 'ecs.amazonaws.jp'
end
HTTPI.adapter = :net_http
client = ASIN::Client.instance
# Define amazon api response group
RESPONSE_GROUP = [:Medium,:Reviews]
# Search!!
api_responses = client.search({:Title => "我輩は猫である", :SearchIndex => :Books, :ResponseGroup => RESPONSE_GROUP})
p api_responses
アマゾンAPIの仕様
2015年8月1日土曜日
IEではhttp://user:pass@example.com/みたいなリンクが開けない
クロームとかはできる
https://support.microsoft.com/ja-jp/kb/834489
おすすめなgitのエイリアスの設定
git config --global user.name "sato"
git config --global user.email sato@example.com
git config --global alias.st 'status'
git config --global alias.llog 'log --graph --decorate --color --stat'
git config --global alias.slog 'log --oneline --color'
git config --global alias.ch 'checkout'
git config --global alias.d 'diff --color'
git config --global alias.diff 'diff --color'
2015年5月16日土曜日
python3.3、pip3.3インストール
python3.3インストール
yum groupinstall -y development
yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel
wget http://www.python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz
xz -d Python-3.3.3.tar.xz
tar -xvf Python-3.3.3.tar
make && make altinstall
pip3.3インストール
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.6.38.tar.gz#md5=a0bc8fdb8b7b36234dcb1ff3d1fc702d
tar zxvf distribute-0.6.38.tar.gz
cd distribute-0.6.38/
sudo python3.3 setup.py install
sudo easy_install pip
pyyamlを入れてみる
sudo pip3.3 install pyyaml
2015年5月7日木曜日
Linuxでのファイルの絶対パスの表示
Linuxでのファイルの絶対パスの表示
readlink -f を使うとよい
$ readlink -f bow_test.csv
/home/sato/workspace/book/Learn/data/bow_test.csv
2015年5月6日水曜日
gitでのコミットの打ち消し
gitで過去の変更を取り消したいときgit reset --hardは危険。コミットしてない変更があると完全に中身を消去してしまう。(これのせいで半日を無駄にした)
コミットログを汚して許容される環境ではgit revertで打ち消すべき
revertしただけだと、消したファイルはワーキングディレクトリから消えたままなのでそのcheckoutすべき
git revert <commit>
git checkout .
