ここを参考に、
Asciiの場合
1 2 3 | cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", ('%{}%'.format(tag),)) |
Unicodeの場合
tagはunicode string
1 2 3 | cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (u"%{}%".format(tag),)) |
ここを参考に、
1 2 3 | cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", ('%{}%'.format(tag),)) |
tagはunicode string
1 2 3 | cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (u"%{}%".format(tag),)) |
MySQL+Pythonのエラー
1 | ValueError: unsupported format character 'Y' (0x59) at index 51 |
このようなエラーが出るときの対応。
1 2 3 4 5 6 7 8 9 10 11 | import MySQLdb ymd="2017-05-19" con=MySQLdb.connect(user="root",password="",host="localhost",db="test") cur=con.cursor() cur.execute("set names utf8") # 文字化け対応 cur.execute("select * from test_table where date_format(ymd,'%%Y-%%m-%%d')=%s",(ymd,)) for row in cur.fetchall(): print(row[0]) |
これだと上記エラーが発生します。
ここに解決策が載っていました。
ポイントはsql文の文字列をformat()するだけ
1 2 3 4 5 6 7 8 9 10 11 | import MySQLdb ymd="2017-05-19" con=MySQLdb.connect(user="root",password="",host="localhost",db="test") cur=con.cursor() cur.execute("set names utf8") # 文字化け対応 cur.execute("select * from test_table where date_format(ymd,'%%Y-%%m-%%d')=%s".format(),(ymd,)) for row in cur.fetchall(): print(row[0]) |
AWSの仕様がすぐ変わるのでメモ。
こちらの記事を参考にAPIGatewayにAPIキーをつけようとしたのですが、2017.5.16現在、仕様が変わってしまっているようでそのままでは設定できませんでした。
記事の中頃「API Keyの追加」の部分ですが、API Stage AssociationはAPI Keyのページには存在しません。
以下の手順となります
これでAPIキーが付加されます。
ちょっとハマったのでメモ。JavaはMavenでコンパイルします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.example; import java.util.Iterator; import java.util.Map; import com.amazonaws.services.lambda.runtime.Context; public class Test { //http://stackoverflow.com/questions/35545642/error-executing-hello-world-for-aws-lambda-in-java public String handler(Map<String,Object> input, Context context){ String ret=""; Iterator<String> ite=input.keySet().iterator(); while(ite.hasNext()){ String key=ite.next(); String val=input.get(key).toString(); ret+="("+key+","+val+"),"; } return ret; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Test</name> <url>http://example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-core</artifactId> <version>1.0.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <createDependencyReducedPom>false</createDependencyReducedPom> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> |
1 | mvn package |
Runtime | Java 8 |
Handler | com.example.Test::handler |
これで動きます。テストの際に与えるパラメタの値が表示されます
torchというディープラーニングのライブラリが有ります。Luaで書かれているようであまり馴染みがなかったのですが、論文を読んでいて、サンプルをどうしても動かしたくてデバッグできる環境の構築を行った時のメモです
こちらにubuntuの場合の設定方法があるのですが、Macではちょっと違いました。
1 | brew install lua |
これだけです
公式の手順通りにやれば問題なく終了します。
1 2 3 | git clone https://github.com/torch/distro.git ~/torch --recursive cd ~/torch; bash install-deps; ./install.sh |
下記URLからLuaプラグインをインストールします。1.4.1が最新でした
http://download.eclipse.org/ldt/releases/milestones/
これが一番ハマりました。
環境設定 > Lua > Interpreters で Addで追加します。
Interpreter type | Lua JIT 2.0 |
Interpreter executable | /Users/yourname/torch/install/bin/luajit |
Interpreter name | Lua JIT |
interpreter arguments | -lenv -e “io.stdout:setvbuf(‘no’); if os.getenv(‘DEBUG_MODE’) then require ‘debugger’ ; require ‘debugger.plugins.ffi’end” |
Linked Execution Environment | lua-5.1 |
また、Import…で/Users/yourname/torch/install/bin/torch-activateをインポートし環境変数を追加します
こちらのサンプルを動かしてみます。
EclipseでLuaプロジェクトを作成し、srcディレクトリ内にファイルを作成します。
ここでポイントは、ファイルのパスをコード中に記述する際にはプロジェクトのトップからの相対パスを書きます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | print '==> downloading dataset' -- Here we download dataset files. -- Note: files were converted from their original LUSH format -- to Torch's internal format. -- The SVHN dataset contains 3 files: -- + train: training data -- + test: test data tar = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/mnist.t7.tgz' if not paths.dirp('mnist.t7') then os.execute('wget ' .. tar) os.execute('tar xvf ' .. paths.basename(tar)) end train_file = 'src/mnist.t7/train_32x32.t7' test_file = 'src/mnist.t7/test_32x32.t7' ---------------------------------------------------------------------- print '==> loading dataset' -- We load the dataset from disk, it's straightforward trainData = torch.load(train_file,'ascii') testData = torch.load(test_file,'ascii') print('Training Data:') print(trainData) print() print('Test Data:') print(testData) print() ---------------------------------------------------------------------- print '==> visualizing data' -- Visualization is quite easy, using itorch.image(). if itorch then print('training data:') itorch.image(trainData.data[{ {1,256} }]) print('test data:') itorch.image(testData.data[{ {1,256} }]) end |
右クリックのRunで実行できます
Tensorflowをバージョンアップすると、昔動いていたスクリプトが動かなくなったりします
1 2 | cell = tf.nn.rnn_cell.BasicLSTMCell(size, forget_bias=0.0) AttributeError: 'module' object has no attribute 'rnn_cell' |
こんなエラーとか。
こちらを参照し修正します。
これを
1 | tf.nn.rnn_cell.BasicLSTMCell |
これに変更
1 | tf.contrib.rnn.BasicLSTMCell |
Mavenの起動時にエラーが出たのでメモ
1 2 | $ mvn package メイン・クラスorg.codehaus.plexus.classworlds.launcher.Launcherが見つからなかったかロードできませんでした |
こちらを参考に
1 2 | $ unset M2_HOME $ mvn package |
Pythonで並列化させたプログラムを走らせていたのですがあまりの遅さにJavaへと変更した際、並列化をomp4jで簡単にできたのでメモ。
OpenMPの説明は、Wikipediaをみてもらうことにして、ソースコード中にコメントを書いておいて、コンパイルをすれば並列化プログラムの出来上がるという便利なライブラリ。
ここからJarファイルをダウンロードします。
1 | wget https://github.com/omp4j/omp4j/releases/download/v1.2/omp4j-1.2.jar |
簡単なプログラムを作成します。スレッド5で10回計算しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import java.util.Random; public class OmpTest { private void run() { try { // omp parallel for threadNum(5) for (int i = 0; i < 10; i++) { new Task1(i).call(); } } finally { System.out.println("ThreadTest:finish"); } } static class Task1{ private int number; Task1(int number){ this.number=number; } public Long call() { System.out.println("Task1.start:"+this.number); long sleep=new Random().nextInt(10)*1000; long sum = 0; for (int i = 1; i <= 100 * 10000; i++) { sum += i; } try{ Thread.sleep(sleep); }catch(Exception e){} System.out.println("Task1.end:"+this.number+",sleep="+sleep); return sum; } } public static void main(String[] argv){ new OmpTest().run(); } } |
普通にコンパイルします。シングルスレッドで動作します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $ javac OmpTest.java $ java OmpTest Task1.start:0 Task1.end:0,sleep=3000 Task1.start:1 Task1.end:1,sleep=2000 Task1.start:2 Task1.end:2,sleep=1000 Task1.start:3 Task1.end:3,sleep=0 Task1.start:4 Task1.end:4,sleep=5000 Task1.start:5 Task1.end:5,sleep=6000 Task1.start:6 Task1.end:6,sleep=9000 Task1.start:7 Task1.end:7,sleep=3000 Task1.start:8 Task1.end:8,sleep=8000 Task1.start:9 Task1.end:9,sleep=2000 ThreadTest:finish |
シリアルに計算されているのがわかります。
並列化できるようにコンパイルします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $ java -jar omp4j-1.2.jar OmpTest.java $ java OmpTest Task1.start:3 Task1.start:1 Task1.start:2 Task1.start:4 Task1.start:0 Task1.end:1,sleep=0 Task1.start:5 Task1.end:0,sleep=3000 Task1.start:6 Task1.end:2,sleep=3000 Task1.end:5,sleep=3000 Task1.start:7 Task1.start:8 Task1.end:3,sleep=4000 Task1.start:9 Task1.end:4,sleep=7000 Task1.end:9,sleep=3000 Task1.end:6,sleep=8000 Task1.end:8,sleep=8000 Task1.end:7,sleep=9000 ThreadTest:finish |
並列に計算できているのがわかります。
実際にはコンパイル時にコードを変換してコンパイルしています。
ここにソースコードを貼り付けると変換後のソースが表示されます。上記サンプルだとエラーになってしまいましたが、簡単なコードならばそのコードが表示されます。
簡単にJavaのコードが並列化できます。色々と制約はありますが(変数関連など)、簡単に並列プログラムが作成できるのはメリットでしょう。
SQLite、手軽で便利なデータベースですが激しく使っていると速度が気になる時もあります。
SQLiteはインメモリデータベースもサポートしているので、既存のSQLiteのデータベースからインメモリ化して読み取り専用にすると早くなります。
適当に大きなデータベースを用意します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/bin/env python # coding:utf-8 import sqlite3 con=sqlite3.connect("test.db") con.cursor().execute("CREATE TABLE test( key integer, val integer , primary key(key))") con.commit() for key in range(1,10000000+1): con.cursor().execute("insert into test values(?,?)",(key,key+1,)) con.commit() |
1000万レコードのデータベースを作成しました。
1 2 3 4 5 6 7 8 | $ sqlite3 test.db SQLite version 3.7.6.3 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> select count(*) from test; 10000000 |
こちらを参考にプログラムを作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #!/bin/env python # coding:utf-8 import sqlite3 from StringIO import StringIO import time import random # in memory化 con=sqlite3.connect("test.db") tempfile=StringIO() for line in con.iterdump(): tempfile.write("%s\n" % line) tempfile.seek(0) mcon=sqlite3.connect(":memory:") mcon.cursor().executescript(tempfile.read()) mcon.commit() mcon.row_factory=sqlite3.Row current_milli_times = lambda: int(round(time.time() * 1000)) print "ready.." # normal # select 10000 times N=10000 nstart=current_milli_times() for i in range(N): key=random.randrange(10000000) res=con.cursor().execute("select * from test where key=?",(key,)) nend=current_milli_times() print "normal:"+str(nend-nstart) # inmemory mstart=current_milli_times() for i in range(N): key=random.randrange(10000000) res=mcon.cursor().execute("select * from test where key=?",(key,)) mend=current_milli_times() print "inmemory:"+str(mend-mstart) |
conのコネクションが通常のデータベースアクセス、mconがデータベースファイルをインメモリ化したものになります。10000回ランダムにSELECTしてみます。
1 2 3 | ready.. normal:414 inmemory:171 |
大学のスパコンで計算したのですが2倍以上の差が出ました。
スーパーユーザ権限のないサーバにソースコードからインストールしてみたのでそのメモ
大学のサーバなど勝手になんでもインストールできない環境ではローカルのユーザ環境に色々とインストールしないといけません。今回はRをインストールしてみました
cranからRのソースコードをダウンロードしコンパイルします
1 2 3 4 5 6 | wget https://cran.r-project.org/src/base/R-3/R-3.3.2.tar.gz tar zxvfp R-3.3.2.tar.gz cd R-3.3.2 mkdir builddir cd builddir ../configure --prefix=/work/$USER/local --with-cairo --with-jpeglib --with-readline --with-tcltk --with-blas --with-lapack --enable-R-profiling --enable-R-shlib --enable-memory-profiling |
エラーになります
1 2 | checking if bzip2 version >= 1.0.6... no checking whether bzip2 support suffices... configure: error: bzip2 library and headers are required |
足りないライブラリを入れていきます
。
1 2 3 | wget http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz tar zxvfp bzip2-1.0.6.tar.gz cd bzip2-1.0.6 |
このあたりを参考にMakefileを修正しておきます。CFLAGSに-fPICを追加します
1 | CFLAGS=-fPIC -Wall -Winline -O2 -g $(BIGFILES) |
makeします
1 2 3 4 5 | make -f Makefile-libbz2_so make clean make make -n install PREFIX=/work/$USER/local make install PREFIX=/work/$USER/local |
Rのconfigを再開します。この際、オプションにライブラリのパスを入れます
1 | ../configure --prefix=/work/$USER/local --with-cairo --with-jpeglib --with-readline --with-tcltk --with-blas --with-lapack --enable-R-profiling --enable-R-shlib --enable-memory-profiling CPPFLAGS="-I/work/$USER/local/include" LDFLAGS="-L/work/$USER/local/lib" |
またエラーです
1 2 | checking for lzma_version_number in -llzma... no configure: error: "liblzma library and headers are required" |
xzライブラリを入れます。
1 2 3 4 5 | wget http://tukaani.org/xz/xz-5.2.3.tar.gz tar zxvfp xz-5.2.3.tar.gz cd xz-5.2.3 ./configure --prefix=/work/$USER/local make install |
Rのconfigを再開
1 | ../configure --prefix=/work/$USER/local --with-cairo --with-jpeglib --with-readline --with-tcltk --with-blas --with-lapack --enable-R-profiling --enable-R-shlib --enable-memory-profiling CPPFLAGS="-I/work/$USER/local/include" LDFLAGS="-L/work/$USER/local/lib" |
またエラー
1 2 | checking for pcre_fullinfo in -lpcre... no checking whether PCRE support suffices... configure: error: pcre >= 8.10 library |
pcreライブラリを入れる。ここで、UTF8を有効にしておきます
1 2 3 4 5 | wget https://ftp.pcre.org/pub/pcre/pcre-8.10.zip unzip pcre-8.10.zip cd pcre-8.10 ./configure --prefix=/work/$USER/local/ --enable-utf8 make install |
Rのconfigを再開
1 2 | checking if libcurl is version 7 and >= 7.28.0... no configure: error: libcurl >= 7.28.0 library and headers are required with support for https |
またエラーです
1 2 3 4 5 6 | wget --no-check-certificate https://curl.haxx.se/download/curl-7.47.1.tar.gz tar zxvfp curl-7.47.1.tar.gz cd curl-7.47.1 ./configure --prefix=/work/$USER/local make -j3 make install |
Rのconfigを再開
1 | ../configure --prefix=/work/$USER/local --with-cairo --with-jpeglib --with-readline --with-tcltk --with-blas --with-lapack --enable-R-profiling --enable-R-shlib --enable-memory-profiling CPPFLAGS="-I/work/$USER/local/include" LDFLAGS="-L/work/$USER/local/lib" |
成功しました
1 | make |
またエラー。。
1 | /work/xxxxx/work/R-3.3.2/builddir/bin/exec/R: /usr/lib64/libgomp.so.1: version `GOMP_4.0' not found (required by /work/xxxxx/work/R-3.3.2/builddir/lib/libR.so) |
これは使っているGCCとそのライブラリがずれていたためでした。
LD_LIBRARY_PATHに使っているGCCのライブラリパスを前の方に追加し再度make
1 2 | make make install |
これでOKです。