Learn to Live and Live to Learn

IT(たまにビジネス)に関する記事を読んで、考えて、使ってみたことをまとめる場。

配列の添字

配列の添字に正の数と0以外を設定した場合の挙動を調べてみました。

  • 負の値を添字に指定すると、添字の中で最大のものを-1に割り当てて、絶対値が大きくなるに連れて配列を逆向き(末尾から先頭)に見ていきます。

例、
要素数3である@fredを使用。
$fred[-1] = $fred[2]
$fred[-2] = $fred[1]
$fred[-3] = $fred[0]

  • 添字の中にアンスコ(_)を書くとアンスコは無視されます。

例、$fred[1_2]は$fred[12]。


上記を確かめるために利用したスクリプトはこちら。
実際はuse strict;を指定してmyとか付けたほうが良いと思います。

#!/usr/bin/perl -w

$fred[0] = "yabba";
$fred[1] = "dabba";
$fred[2] = "doo";

$length = @fred;

print "Array is\n";
for ( $i = 0; $i < $length; $i++ ) {
	print $fred[$i] . "\n";
}

print "\n";

print "\$fred[-1] is\n";
print $fred[-1] . "\n\n";

print "\$fred[-2] is\n";
print $fred[-2] . "\n\n";

print "\$fred[-3.456] = \$fred[-3] is\n";
print $fred[-3.456] . "\n\n";

print "\$fred[1_2] = \$fred[12] is\n";
print $fred[1_2] . "\n";

実行結果

$ perl list.pl 
Array is
yabba
dabba
doo

$fred[-1] is
doo

$fred[-2] is
dabba

$fred[-3.456] = $fred[-3] is
yabba

$fred[1_2] = $fred[12] is
Use of uninitialized value $fred[12] in concatenation (.) or string at list.pl line 27.

$

おまけ
そもそもリストと配列の違いって普段あまり意識しないのですが
(と言いますか私は≒だと思ってました…)

リストは順序付けされたデータのこと。
配列はそのデータ=リストを格納する変数。

と定義されています。

Rの関数を使いこなす。

1. 関数を組み合わせる
2. 関数を自作する
3. 比較・判断文に、繰り返し文
4. 入力・編集

関数を組み合わせる

下記のように関数を組み合わせて出力することができます。

> life1
     [,1] [,2] [,3] [,4]
[1,]  101  120   70   35
[2,]  153  162   88   46
[3,]   89  135   78   24
[4,]   26   49   42   17
[5,]   36   70   30   16
[6,]  167  216  144   71
[7,]  125  143   89   65
> apply(life1,1,sum)
[1] 326 449 326 134 152 598 422
apply(データ,1(行)or2(列),関数)

行・列別に基本統計量=関数の結果を出します。

> round(t(t(life2))-apply(life2,2,mean),2)
       [,1]  [,2]  [,3]   [,4]
[1,]   3.41 25.55 -1.57 -27.39
[2,]  -4.05  8.51  8.34 -12.80
[3,]   4.26  3.28 -3.64  -3.90
[4,]   8.14 13.53 -6.79 -14.88
[5,]  -3.89 34.79 -3.30 -27.60
[6,] -10.20  8.55 12.82 -11.17
[7,]   6.58 -4.24 -6.48   4.14

実際は二回t()=転置する必要はありません。
小数点2位までの四捨五入にするため、round(データ,桁数)を使っています。

関数を自作する

> 関数の名前<-function(引数){
+ プログラムの本体
+ }

比較・判断文に、繰り返し文

Rにも他のプログラミング言語と同様にif文やfor文があります。

if( 条件式 ) 真の処理 else 偽の処理

print()もあります。

for( 変数 in 変数の開始値 : 変数の終了値 ) {
    処理
}

他にもwhile、repeatがあります。

入力・編集

Rでのプログラムの入力には

  • Rのコンソール
  • 関数

があります。関数は以下です。

fix(program1)
program1<-edit(program1)

Iterator

HadoopのReducerや、Androidアプリによく登場するIterator。いつも書き方を調べてしまうので自分用にまとめます。

例、

public void reduce ( Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter ) throws IOException
{
    int sum = 0;
    while ( values.hasNext() )
    {
        sum += values.next().get();
    }
    output.collect(key, new IntWritable(sum));
}

Iteratorとは、Collectionの要素に順番にアクセスするための機能です。
hasNext()メソッドで次の要素があるか確認し、next()メソッドで取得します。

import java.util.*;

public class Iterator {

	public static void main(String[] args) {
		HashMap map = new HashMap(); // オブジェクトの生成。
		String[] tel = {"03", "075", "06", "052"}; //key
		String[] area = {"Tokyo", "Kyoto", "Osaka", "Nagoya"}; // value
		
		// HashMapにキーバリューを代入。
		System.out.println("HashMap");
		for ( int i = 0; i < 4; i++ ) {
			map.put(tel[i], area[i]);
			System.out.println("|" + tel[i] + "|" + area[i] + "|");
		}
		
		// Iteratorを使って取り出す。
		System.out.println("Iterator");
		/*
		 * Iterator"i"に
		 * HashMap"map"の
		 * キーバリューを保持したSetをentrySet()で取得して
		 * iterator()によって反復しを
		 * 代入する。
		 */
		for ( java.util.Iterator i = map.entrySet().iterator(); i.hasNext(); ) { // java.utilを外すとなぜかエラーになる。
			System.out.println("キーバリューのペア: " + i.next());
		}
		
	}

}

実行結果。HashMapの順に出てくるわけではないことに注意。

HashMap
|03|Tokyo|
|075|Kyoto|
|06|Osaka|
|052|Nagoya|
Iterator
キーバリューのペア: 075=Kyoto
キーバリューのペア: 06=Osaka
キーバリューのペア: 052=Nagoya
キーバリューのペア: 03=Tokyo


Iterator
http://www.javaroad.jp/java_collection5.htm
http://www.geocities.jp/m_hiroi/java/abcjava09.html
Hadoop
http://xamry.wordpress.com/2012/09/11/your-first-hadoop-map-reduce-job/

シンボリックリンクを作る。

リンクとは、ファイルやディレクトリを移動したりコピーしたりせずとも、違うファイル・ディレクトリのように扱える機能です。

シンボリックリンク
元ファイルのパスを指し示す擬似的なファイルを作成。
元ファイルを消すとエラー。

$ ln -s ファイル名 リンク名

ハードリンク:
元ファイルを直接指す。
元ファイルを削除してもOK。

$ ln ファイル名 リンク名

削除

$ rm リンク名
$ touch test

$ ls -la
-rw-r--r--   1 A_01  staff     0 12 21 00:29 test

$ ln -s touch symbolic_link

$ ls -la
lrwxr-xr-x   1 A_01  staff     4 12 21 00:29 symbolic_link -> test←頭にlと付くのか!
-rw-r--r--   1 A_01  staff     0 12 21 00:29 test

$ ln test hart_link

$ ls -la
lrwxr-xr-x   1 A_01  staff     4 12 21 00:29 symbolic_link -> test
-rw-r--r--   1 A_01  staff     0 12 21 00:29 test
-rw-r--r--   2 A_01  staff     4 12 21 00:35 hard_link

$ vim test
aaa

$ cat symbolic_link 
aaa

$ cat hard_link
aaa

$ rm test
 
$ cat hard_link 
aaa

$ cat symbolic_link 
cat: symbolic_link: No such file or directory


参考
http://www.linux-beginner.com/linux_kihon129.html
http://itpro.nikkeibp.co.jp/article/COLUMN/20060227/230812/
http://trialpc.net/blog/2007/09/post-986.php

HadoopのWebUIを見てみる!【HDFS編】

Web UIでHDFSやMapReduceを確認したい!と思い
やってみました。

http://localhost:50030 JobTracker→MapReduce
http://localhost:50070 NameNode→HDFS

※50030番はやっているところです。

$ hadoop namenode -format
必要なデータのフォーマットを行う。
$ start-all.sh
起動しようとする。
しかしlocalhost::22にsshできないというエラー。
$ ps aux | grep sshd
sshdが起動していない。。

$ /usr/sbin/sshd 
Could not load host key: /etc/ssh_host_rsa_key
Could not load host key: /etc/ssh_host_dsa_key
なんかホストキーがロードできないと言っている。。

$ sudo ssh-keygen -N "" -f /etc/ssh_host_rsa_key
$ sudo ssh-keygen -N "" -f /etc/ssh_host_dsa_key
鍵を作って

$ sudo /usr/sbin/sshd
起動!sudoがいります。

$ ssh localhost
いけた(´∀`)
$ start-all.sh

WebUI〜♩

見られない( ̄□ ̄|||)

$ jps
2848 Jps
2812 NodeManager
2720 ResourceManager
NameNodeとDataNode、JobTracker、TaskTrackerが起動してないやんか!

$ stop-all.sh
一旦終了。

$ vim etc/hadoop/core-site.xml
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>

NameNodeの設定をする。

$ vim etc/hadoop/hdfs-site.xml 
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>

DataNodeの設定をする。

$cp etc/hadoop/mapred-site.xml.template etc/hadoop/mapred-site.xml
$ vim etc/hadoop/mapred-site.xml
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>mapred.job.tracker</name>
<value>localhost:9001</value>
</property>
</configuration>

JobTrackerを設定。

$ hadoop namenode -format

ちなみに
share/hadoop/common/templates/core-site.xml
share/hadoop/hdfs/templates/hdfs-site.xml
はディレクトリ名の通りテンプレートであって、ここを編集しても意味はない。

$ start-all.sh

$ jps
6098 Jps
5738 DataNode
6065 NodeManager
5971 ResourceManager
5850 SecondaryNameNode
5648 NameNode

JobTrackerが立ち上がってない?
だから
http://localhost:50070
HDFSはOKだけど
http://localhost:50030
は見られない。なぜ。
原因は調べときます。

Hadoop
http://codezine.jp/article/detail/2485
SSH
http://stmind.hatenablog.com/entry/20110802/1312302164

MacでHadoop【スタンドアロンモード編】

サーバが複数台なくてもHadoopは使えます(知ってるわ!という話かもしれませんし、早い処理はできませんが)。
勉強のためMacにHadoopを入れてみました。

http://ftp.yz.yamagata-u.ac.jp/pub/network/apache/hadoop/common/stable2/
にてhadoop-2.2.0.tar.gzをダウンロード(2系初の安定板!)。

hadoopと打ってみる。

$ /usr/local/bin/hadoop-2.2.0/bin/hadoop
Usage: hadoop [--config confdir] COMMAND
       where COMMAND is one of:
  fs                   run a generic filesystem user client
  version              print the version
  jar <jar>            run a jar file
  checknative [-a|-h]  check native hadoop and compression libraries availability
  distcp <srcurl> <desturl> copy file or directories recursively
  archive -archiveName NAME -p <parent path> <src>* <dest> create a hadoop archive
  classpath            prints the class path needed to get the
                       Hadoop jar and the required libraries
  daemonlog            get/set the log level for each daemon
 or
  CLASSNAME            run the class named CLASSNAME

Most commands print help when invoked w/o parameters.

Usage出たー!

ファイルとディレクトリを用意。

$ mkdir input
$ vim input/test.txt
To be or not to be, that is the question.
$ mkdir output

jarファイルを実行してみる。

$ hadoop jar hadoop-mapreduce-examples-2.2.0.jar wordcount input output/wordcount

よし!

$ ls output/wordcount/
_SUCCESS	part-r-00000
$ cat output/wordcount/part-r-00000
To	1
be	1
be,	1
is	1
not	1
or	1
question.	1
that	1
the	1
to	1


Hadoopをどこに置くか(/usr/bin/と/usr/local/bin/の差異)
http://oswald.hatenablog.com/entry/20100416/1271368477

Hadoop事始め
http://www.scienceq.com/itinfra/index.php?Hadoop%2F%A5%A4%A5%F3%A5%B9%A5%C8%A1%BC%A5%EB

Cookieって何?

Cookieはよく耳にするのですが何者なのかわかっていなかったので調べました。

HTTPはステートレスな(クライアントの状態=ステートを管理しない)プロトコルです。
Cookieは、複数のアクセスが同一のクライアントから来たものだ、とサーバが知るための技術です。
アクセス解析やログイン管理に使われます。

Cookieの大まかな流れです。

<1回目のアクセス>
1. クライアントがサーバにwebページを要求。
2. サーバは、Set-Cookie:という現在時刻
(ものによってはクッキーが適応されるドメインやパス
有効期限なども)を付けたクッキーをクライアントに返す。
3. クライアントはクッキーをHDDに保存。
<2回目以降のアクセス>
4. クライアントはアクセス先のクッキーがHDDにあることを確認。
5. クライアントはCookie:というヘッダを付けてサーバに送信。

参考
http://tennensui.sakura.ne.jp/pcrikai/category3/entry22.html
http://ja.wikipedia.org/wiki/HTTP_cookie

ちなみに自分がどんなCookieを持っているかは、Chromeだと
Google Chromeの設定>設定>詳細設定を表示…>プライバシーにあるコンテンツの設定>すべてのCookieとサイトデータ…
で見られます。

以下にCookieの動作を確認するCGIがありましたので、今度試してみます。
http://itpro.nikkeibp.co.jp/article/COLUMN/20080331/297574/