2014/12/19

systemctl

systemctl stop iptables.service
systemctl stop ip6tables.service
systemctl stop ebtables.service

systemctl mask iptables.service
systemctl mask ip6tables.service
systemctl mask ebtables.service


・maskしてサービスを無効にする
sudo systemctl mask httpd.service
=>ln -s '/dev/null' '/etc/systemd/system/httpd.service'
Unitファイルは/etc/systemd/system⇒/usr/lib/systemd/systemの順に参照される。優先度の高い/etc/systemd/system上に/dev/nullへのシンボリックリンクを配置することで、対象Unitへの操作を無効化している事が分かる。


・変更を有効にする
systemctl daemon-reload

・変更ログ
journalctl
該当サービスの直近のシステムログが表示されています。
rsyslogに送られるメッセージは、systemd-journaldというデーモンが監視しており、
すべてsystemd独自のログ(ジャーナル)にも保存されています。
ここで表示されるログは、ジャーナルから取り出しているため、実際のログの出力ファイルに関わらずすべてのログがここで確認できます。
上記のコマンドに-fオプションをつけると、「tail -f」と同じように新たなログが追記されるのを監視することもできます。



・serviceとの比較
systemctlは全てのUnitタイプを扱えるのに対して、serviceはserviceタイプのUnitしか取り扱う事ができない。
service-->**.service serviceは省略可能
systemctl-->**.socket *.mount

・chkconfig確認
systemctl is-enable httpd
systemctl enable httpd
systemctl disable httpd
systemctl restart httpd
systemctl reload httpd
===>[Service]
 ExecReload=/bin/kill
 ==>これはないと、エラーになる

systemctl show sshd.service
systemctl daemon-reload

現在稼働中の
systemctl list-units --type=service
関係なく、全てのサービス
systemctl list-unit-files --type=service

==>起動ON/OFFのチェック

・メリット
プロセスを並行起動する
==>UNITの関係を解析して、最適な順位で並行起動する
==>早くなる

initの場合は/etc/rc.d/rc[runlevel].dディレクトリのシンボリックリンクの命名規則によって起動順を指定していたが、
Systemdでは、Unitに定義されたUnit間の関係を元にSystemd側で起動順を決定する。

・cgroups

★systemctl enable error

test@localhost etc]$ sudo systemctl enable redis
redis.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig redis on
The unit files have no [Install] section. They are not meant to be enabled
using systemctl.
Possible reasons for having this kind of units are:
1) A unit may be statically enabled by being symlinked from another unit's
   .wants/ or .requires/ directory.
2) A unit's purpose may be to act as a helper for some other unit which has
   a requirement dependency on it.
3) A unit may be started when needed via activation (socket, path, timer,
   D-Bus, udev, scripted systemctl call, ...)
  

★systemd-cgls
groupsは、Kernelが持つ機能の1つで、CPUやメモリなどのリソースをプロセスグループごとに割り当てることができるものです。
各グループの階層については、systemd-cglsコマンドで確認できます。

★systemd service type?? foring simple
「Type」は、「ExecStart」で指定したコマンドでサービスのプロセスを起動した際に、起動完了をどのように判定するかを指定します

simple==>普通の
forking==>後ろで実行続ける
デーモン型のプロセスではなく、一度だけ指定のコマンドを実行するタイプのサービスについては、「Type=oneshot」とすると、「ExecStart」で指定したコマンドを実行して、それが完了したタイミングで起動完了(かつサービス終了)と判断します。コマンドが完了したあともサービスとしては起動状態として認識させたい場合は、「RemainAfterExit=yes」を指定します。このタイプについては、「Type=simple」とすることも可能ですが、この場合、systemdは、コマンドの実行を開始したタイミングで起動完了と判断します。

svn 衝突

編集 (e)      - マージされたファイルにエディタで変更を加えます
  全差分 (df)   - マージによってファイルに加えられた変更をすべて表示します
  解決版 (r)    - マージされたバージョンのファイルを採用します
  衝突表示 (dc) - (マージされたバージョンを無視して) 衝突をすべて表示します
  衝突自分 (mc) - (同上) すべての衝突に関して自分のバージョンを採用します
  衝突他人 (tc) - (同上) すべての衝突に関して他人のバージョンを採用します
  完全自分 (mf) - (衝突がなくても) ファイル全体で自分のバージョンを採用します
  完全他人 (tf) - (同上) ファイル全体で他人のバージョンを採用します
  延期 (p)      - 競合に、後で解決する予定であるという印をつけます
  起動 (l)      - 競合を解決するために外部ツールを起動します
  全表示 (s)    - この選択肢一覧を表示します
 

linux apache2.4 module memo

■proxyモジュール多いね
LoadModule proxy_module modules/mod_proxy.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so


/etc/httpd/conf.d/proxy.conf
=->/etc/httpd/conf.modules.d/00-proxy.conf

・apache 設定ファイル

UseCanonicalName
    サーバが自分自身の名前とポートを決定する方法を設定する
    canonical--->正典的。ネーミングは良くない。自分自身でown?

==>onの場合
 ServerName ディレクティブで指定されている ホスト名とポート番号を使って、その正規名 (自己参照の名前) を生成します
 じゃないと、ServerNameは意味がないだね。
==>offの場合
 UseCanonicalName Off の場合、 クライアントがホスト名とポートを指定したときには、 それらを元に自己参照 URL を作成します (指定がなかったときは 上の定義と同様にして正規名を解決します)

これぐらいだね。。。。
====>URL が最後のスラッシュ無しの ディレクトリになっている http://www/splat のようなとき、 Apache はリクエストを http://www.domain.com/splat/ へリダイレクトします


★apache Access Control
=->mod_authz_core
   mod_authz_host
  
・mod_rewrite
   ==>
   RewriteEngine On
   RewriteCond %{TIME_HOUR} >= 20 {OR}
   RewriteCond %{TIME_HOUR} < 07
   RewriteRule ^/fridge - [F]
   ==>The [F] RewriteRule flag causes a 403 Forbidden response to be sent
   07-20の間にOK
  
・ Require
  RequireAll
  RequireAny
  RequireNone
  =>Allow Deny Orderはdeprecated...........

<RequireAll>
    Require all granted
    Require not ip 10.252.46.165
    Require not host host.example.com
</RequireAll>

Require expr %{HTTP_USER_AGENT} != 'BadBot'
==>あいつだけだめ。。。


 Options Includes,FollowSymLinks
  =->FollowSymLinks シンボリックリンクファイルを認識させるかを設定します。
  =->Includes SSI を実行できるかどうかを設定します
 
.htaccess ファイル
==>AllowOverrideはnone、httpd.confで設定すれば、htaccessの設定は無効になる



★apache httpd module

apache mod-dav-------------
文字や画像、音声、動画などの要素を組み合わせて一つのソフトウェアやコンテンツ作品を組み立てること。

異なる種類の素材データを組み合わせ、配置や出現順、利用者の操作に対する反応などを設定していく編集作業を意味するが、(従来は必須であった)プログラミング言語やマークアップ言語などによるコードの記述を極力廃し、マウス操作など直感的な方法で作業を進めるという含意がある。

多くの場合、そのような作業に対応した専用のソフトウェアが用いられ、「オーサリングソフト」「オーサリングツール」などと呼ばれる。多くのツールは上級者が複雑な設定を行うことができるよう、補助的にプログラミングができるようになっていることが多い。

Apache Module mod_lua-------
==>this module allows the server to be extended with scripts written in the Lua programming language

Luaは、C言語のホストプログラムに組み込まれることを目的に設計されており、高速な動作と、高い移植性、組み込みの容易さが特徴である。いったんバイトコードにコンパイルされ、Lua VMで実行される。LuaJITは The Computer Language Benchmarks Game によると、変数に型のないスクリプト言語では最速の言語・処理系である[1]。


event------------------------------------
The event MPM handles some connections in an asynchronous way, where request worker threads are only allocated for short periods of time as needed, and other connections with one request worker thread reserved per connection. This can lead to situations where all workers are tied up and no worker thread is available to handle new work on established async connections.

To mitigate this problem, the event MPM does two things: Firstly, it limits the number of connections accepted per process, depending on the number of idle request workers. Secondly, if all workers are busy, it will close connections in keep-alive state even if the keep-alive timeout has not expired. This allows the respective clients to reconnect to a different process which may still have worker threads available.

This directive can be used to fine-tune the per-process connection limit. A process will only accept new connections if the current number of connections (not counting connections in the "closing" state) is lower than:

ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)

This means the absolute maximum numbers of concurrent connections is:

(AsyncRequestWorkerFactor + 1) * MaxRequestWorkers

MaxRequestWorkers was called MaxClients prior to version 2.3.13. The above value shows that the old name did not accurately describe its meaning for the event MPM.

AsyncRequestWorkerFactor can take non-integer arguments, e.g "1.5".

モジュールhttpd-------------
httpd -l
===>Compiled in modules

httpd -M==>モジュールの一覧

★TraceEnable off
HTTPのメソッドには、よく使うものとしてGETやPOSTというものがありますが、TRACEメソッドというものがありまして、これを有効にしておくと危ないよという話

==>なんか情報漏れので、無効にする


<IfModule mime_module>
 TypesConfig /etc/mime.types

</IfModule>


★mod_filter
This module enables smart, context-sensitive configuration of output content filters.
For example, apache can be configured to process different content-types through different filters,
even when the content-type is not known in advance (e.g. in a proxy).

★indirection -->間接参照、遠回し
AddOutputFilter
complex boolean expressions

FilterDeclare

★Register Providers
    FilterProviders
   
   

★2.4系
LogLevel alert rewrite:trace3

linux command tips

ssh  sed 正規表現

sed -i "s/\r//"
sed "s/aaa/bbb/i"
    ==->i 大文字と小文字区別しない

grep -i

-i Aとaは区別しない


★disown nonhup

disown---->番号が分かれば、disown 番号
nonhup---->事前でやる


★vi 小文字、大文字変換---------------------
g~~===>小文字、大文字変換

★★linux exec----
シェルから
% ls
とコマンドを実行すると、シェルは以下のことを行う。

    システムコール fork(2) を呼び、子プロセスを生成する。
    子プロセスは ls を exec(2) する。
    親プロセスであるシェルは、ls の実行が完了するのを待つ (wait する)。


一方、
% exec ls
と exec を使うと、シェルは fork(2) せず、いきなり ls コマンドを exec(2) する (シェルの内部コマンド exec(1) を実行すると、内部でシステムコール exec(2) が呼ばれるということ)。シェルのプロセス情報は ls のプロセスの情報で上書きされる。なお、子プロセスは生成されないので、シェルと ls のプロセス ID は同じになる。

実際にやってみるとわかるが、kterm などの端末エミュレータ上でシェルを動かしているときに
% exec ls
とすると一瞬 ls の結果が実行されるが、kterm は終了してしまう
(kterm は通常シェルが終わるのを待っているが、シェルのプロセスは ls のプロセスに上書きされるので、
ls が終了すると kterm も終了してしまう)。

★sudo------
sudo -l
==>内容をリストして、確認できる


★linux set オプション---------
set -m
-->-m -o ジョブ制御を有効にする

UNIX では,二つ以上のコマンドを一つの単位として,一度に実行することができます。 この実行の単位のことをジョブ (job) といいます。
例えば, ls -al /etc | more のような パイプラインはジョブの一例です。
==>


★linux echo------
echo $$
==>pid?

★tar 一部解凍

・中身を確認する
    tar tvf some.tar
   
・一部解凍
    tar xzvf some.tar  aa/bb/cc.dd

★ls
ls -d ==>フォルダだけを表示する
   
★linux ssh log-------------
cat /var/log/secure
grep -c invalid /var/log/secure
grep -c Failed /var/log/secure
grep -c Accepted /var/log/secure

★linux rpm -ql
=->

rpmコマンドに、-qオプションと--scriptsオプションを付けて、preinstallのscriptletを確認すれば良い。
==>ここで、rpmでのインストール時に実行されるスクリプトレットを見てみよう


インストールされたRPMパッケージのディレクトリを調べるには、「-ql」オプションを使用する。
pip install
sudo -E pip install mysql-python --proxy=http://10.25.5.10:8080

ファイル取り出す-------------
***src.rpmをダウンロードする
=>
rpm2cpio | cpio -id

★ifconfig
==>eth0,eth1,eth2

ifconfig eth1

ifconfig eth1 up
ifconfig eth1 down

ifconfig -a


★linux watch---------------
whileループとかを利用しなくてもwatchコマンドを使えば簡単

# 1秒間隔で"ls"コマンドを実行
$ watch -n 1 ls

★linux eval ----------------------------
文字列を変数名にする

bashtest$ cat eval-test2.sh
#!/bin/bash

hoge1="one"
hoge2="two"

for (( i=1; i<3; i++ ))
do
    echo $hoge$i
done

echo

for (( i=1; i<3; i++ ))
do
    eval echo '$hoge'${i}
done


==->



1
2

one
two

eval echo '$hoge'${1}
!!

★★linux command 記録----------------------------------
★script test.log
..
..
ctrl+D
===>ログの記録

★history
HISTIMEFORMAT
==>strftimeの形式で指定する
HISTTIMEFORMAT='%F %T'

ECHO HISTCONTROL;
=>ignoredups,==>直前の同じコマンドを記録しない

unset HISTCONTROL;

HISTIGNORE=ls*:pwd:history*

HISTSIZE

「/etc/profile」に設定しておくことで、すべてのアカウントで常に同じ設定が使えるようにしておきます。
※これでも、各アカウントの「~/.bash_profile」を編集されたら、各種の環境設定ファイルの読み込み順序の関係で、「~/.bash_profile」で上書きされてしまいますが...



★ ssh t オプション 複数
 -t
    強制的に仮想端末を割り当てます。
    これはリモートマシン上で任意の画面ベースのプログラムを実行するとき(たとえば、メニューサービスを実装するときなど)に非常に便利です。
    複数の-t をつけると、たとえssh がローカル側での端末を持っていない場合でも強制的に仮想端末を割り当てます。
   
    通常、Linuxの場合、最初の6つの仮想コンソール (/dev/tty1?/dev/tty6) が
    Unixシェルへのログインプロンプトが表示されたテキストターミナルである
   
    ほとんどのアプリケーションがX Window Systemなどのグラフィカルフレームワーク上で動き、それぞれのプログラムがウィンドウを持っていて、
    テキストモードのアプリケーションは端末エミュレータのウィンドウで動く現在、仮想コンソールの必要性は減っている。
    ユーザの簡易切り替え (fast user switching) や異なるXサーバーでのXアプリのデバッグなど、複数のX Window Systemのログインセッションが同時に並行して動く必要がある場合、
    通常はそれぞれのXセッションは異なる仮想コンソールで動く。GNU Screenは一つのテキストログインの中で、複数のテキストモードのアプリケーションを動かし、それらを切り替えられるようにするプログラムである。
   
    ==>何が見た目、セッション管理上必要な物みたい
   
   
   
★route
routeコマンドは、IPパケットをルーティングするためのルーティングテーブルの内容表示と設定を行う。ルーティングテーブルは、おもにOSが管理するルーティング情報を保管したメモリテーブルだ。テーブルのエントリーが経路を表している。経路はネットワークまたはホストへ到達するために通過する必要のあるゲートウェイを表している。

scala study memo

・Predef is a great place to start to understand the Scala Library
==>Predefに定義された関数は、すべてのScalaのソースにおいて自動でimportされている
printやprintlnはPredefで定義されている。JavaのようにSystem.out.printlnという長い記述をしなくても、printlnのみで標準出力ができるのは、これのお陰。

・Array===>scala.collection.mutable.ArrayLike

scala myfirstScript.scala my first script
==>args...引数のこと  args.foreach(println);


追加:
    var oldList=List(1,2)
    val newList=3 :: oldList
    ==>newList 3:2:1
    var theList= newList : +3

the :: method. The job of the :: method is to create a new List with all the existing
elements plus the new element added at the front of the List. To add at the end of
the List, invoke the :+ method:


val afterDelete = newList.filterNot(_ == 3)
==>filterNot(_ == 3)


_  An underscore has a special meaning in Scala, and in this context it’s a placeholder
for a parameter; in your case, use two underscores
==> evenNumbers.foldLeft(0) { _ + _ }

val hasUpperCase = name.exists(_.isUpper)

==>temporary value,variablesだよね。。。



・def breakable(op: => Unit) { ... }
What’s this op: => Unit? The special right arrow (=>) lets Scala know that the
breakable function expects a function as a parameter
The right side of the => defines the return type of the function

def foldLeft(initialValue: Int, operator: (Int, Int) => Int)= { ... }
==>the funuction paramater with two its own paramters!



val files = new java.io.File(".").listFiles
   for(file <- files) {
   val filename = file.getName
   if(fileName.endsWith(".scala")) println(file)
}
 <- In Scala this is called a generator, and the job of a generator is to iterate
through a collection.


for { a <- aList; b <- bList } println(a + b)
for { a <- aList; b <- bList } yield(a + b)
==>yield 新たなListが作成された。。。


mkString(",")
==>java splitだよね。。。


def ordinal(number:Int) = number match{
  case 1 => println("1st")
  case 2 => println("2st")
  case 3 => println("3st")
  case 4 => println("4st")
  case 5 => println("5st")
  case _ =>
}


java.util.Arrays.asList(scalaList.toArray:_*)
====》
:_*
tells the Scala compiler to send the result of toArray as a variable argument to the
Arrays.asList method;


class MongoClient(val host:String, val port:Int)
val client = new MongoClient("127.0.0.1", 123)
==>Scala also uses the new keyword for creating instances of a class. But
wait a minute?where’s the body of the MongoClient class? In Scala that’s optional

private
==>so that the Scale will not create get ,set methord automiclly



class MyScript(host:String) {
    require(host != null, "Have to provide host name")
    if(host == "127.0.0.1") println("host = localhost")
    else println("host = " + host)
}
==>require!


・package is a special object to grouping classes
package com {
  package mongo {
    import ....
    class
  }
}


import java.sql.{Date => SqlDate}
val sqlDate = new SqlDate(now.getTime)

import java.sql.{Date => _ }
==>The Date class from the java.sql package is no longer visible for use.


:load nnnn.scala
:l nnn.scala


object RichConsole {
def p(x: Any) = println(x)
}
Here RichConsole is a singleton object. The object declaration is similar to a class declaration
except instead of class you’re using the object keyword. To invoke the new
p method,


object DB {
def apply(underlying: MongDB) = new DB(underlying)
}
====>factory in scala

Class UpdatableCollection
extends DBCollection(collection(name)) with Updatable
==>with .... trait



class Outer {
    class Inner {
        private[Outer] def f() = "This is f"
        private[innerpkg] def g() = "This is g"
        private[outerpkg] def h() = "This is h"
}
}
==>Outer,innerpkg,outerpkg



final」はクラスやメンバーに対して設定できる修飾詞です。
   finalが設定されたクラスは継承できません。
   finalが設定されたメンバーはオーバーライドできません。
sealed」はクラスに設定できる修飾詞です。
   sealedとされたクラスは、同一ファイル内のクラスからは継承できますが、別ファイル内で定義されたクラスでは継承できません。
   ただし、sealedクラスを継承したクラスは、別ファイルのクラスからも継承できます。



・class Stack[+A] {
class Stack[-A] {
=>Scalaのコレクションクラス(List, Seqなど)は、List[+A]と型名の前に+を付けてcovariant(共変)な型を許すように定義されています。covariantとは、Aのクラスを拡張したクラスBがあれば、List[B]はList[A]として代入できることを意味します
関数側で型パラメーターに縛りが必要ない場合は_を使えばOKだった。
共変はサブクラスを許容する場合に使う


・値クラス (value class) は実行時のオブジェクトの割り当てを回避するための Scala の新しい機構だ
は新たに定義付けされる AnyVal のサブクラスによって実現される
=>    class Wrapper(val underlying: Int) extends AnyVal


・case class VS class
パターンマッチを使う場合にはcase class、
それ以外は普通のclass、と使い分けています
==>case classはcase classを継承することができない



hierarchy

.git
==>index file
The index records
and retains those changes, keeping them safe until you are ready to commit them.


=>content-addressable storage system
location-addressed disk storage with built-in search capability. The search logic was incorporated into the disk controller
First, Git’s object store is based on the hashed computation of the contents of its objects,
not on the file or directory names from the user’s original file layout.
If two separate files have exactly the same content, whether in the same or different
directories, Git stores a single copy of that content as a blob within the object store.

★It’s important to see Git as something more than a VCS: Git is a content tracking system.


★What if you only add, say,one line to a file, doesn’t Git store the complete content of both versions?
Luckily, the answer is “No, not really!”
Instead, Git uses a more efficient storage mechanism called a pack file.

Instead, Git uses a more efficient storage mechanism called a pack file. To create a
packed file, Git first locates files whose content is very similar and stores the complete
content for one of them. It then computes the differences, or deltas, between similar
files and stores just the differences. For example, if you were to just change or add one
line to a file, Git might store the complete, newer version and then take note of the one
line change as a delta and store that in the pack too.



★blod <- tree <- commit <- tag(branch)

INI-style

構造の単純なテキストファイルであり、設定ファイルの標準です。
このファイルは主にWindowsで使用するが、他のプラットフォームでも使われる。
INIファイルという名前はこのファイルの一般的な拡張子「.INI」から来ている。INIとはinitializationである。
その他に「.CFG」や「.conf」、あるいは「.TXT」も使われる。


パラメータ name=value
セクション  [section]
コメント ; comment text


★ansible lineinfile
This module will search a file for a line, and ensure that it is present or absent.
 This is primarily useful when you want to change a single line in a file only.
 For other cases, see the copy or template modules.

 オプション
 ・backrefs->insertbefore and insertafter will be ignored, and if the regexp doesn't match anywhere in the file,
 the file will be left unchanged.
 If the regexp does match, the last matching line will be replaced by the expanded line parameter.
 ・insertafterーー> the line will be inserted after the specified regular expression

jmeter NonGUIDriver Could not find the TestPlan class

結論から言うと親要素が無い不完全なJMXファイルを作成していたから
翻訳のせいかな。。
save=->保存
save Test Plan As =>テスト計画に名前を使って保存する
Save Selection As =>別名で保存
 ==>選択された部分だけ保存する、これは罠である!!

php study memo

Each active resource has a unique identifier. Each identifier is a numerical index into
an internal PHP lookup table that holds information about all the active resources. PHP
maintains information about each resource in this table, including the number of references
to (or uses of) the resource throughout the code. When the last reference to a
resource value goes away, the extension that created the resource is called to free any
memory, close any connection

=->
$res=database_connect();
...
$res="boo"

automatic cleanup

// is_resource()
==>Many modules provide several functions for dealing with the outside world

if(is_resource($..)){
   
}

is_null($x)


★static variables
function updateCounter(){
     static  $counter=0;
     $counter ++;
     echo "Static function variables is now {$counter}\n";
}



★copy on write----------
必要な時だけ、メモリーを使う

Symbol
Each value pointed to by a symbol table has a reference count, a number that represents
the number of ways there are to get to that piece of memory. After the initial assignment
of the array to $worker and $worker to $other, the array pointed to by the symbol table
entries for $worker and $other has a reference count of 2.1 In other words, that memory
can be reached two ways: through $worker or $other. But after $worker[1] is changed,
PHP creates a new array for $worker, and the reference count of each of the arrays is
only 1.


★function parameter----------------------
func_num_args ==>$#?
func_get_args=>
func_get_arg(1)=>$1

isset(a)
isset(b)
==>設定されている?


Single-quoted strings do not interpolate variables.
echo '$name'
==>$name


$a= array(,,)
print_r($a)

Beware of using print_r() or var_dump() on a recursive structure such as $GLOBALS
(which has an entry for GLOBALS that points back to itself). The print_r() function loops
infinitely, while var_dump() cuts off after visiting the same element three times.

var_dump(true)
==>bool(true)


★echo $_COOKIE['PHPSESSID'];
==>これはないと、何もかわらない。。
session_start() ;

Build-in PHP Data Objects
==>PDO
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for
accessing databases in PHP. Each database driver that implements the PDO interface can
expose database-specific features as regular extension functions. Note that you cannot
perform any database functions using the PDO extension by itself; you must use a database-
specific PDO driver to access a database server.


file_exists($folder)
mkdir
folder
fread
fclose


imagecreate(width,heigth)
imagecolorallocate(image,red,green,blue)
imagegif
imagejpeg

a library vs a framework

・your code call libraries ,frameoworks call your code
・framework==>Don't call us, we'll call you


framework
===>
Frameworks are not the cure for all programming
problems. Putting aside today's awesome state of
development, you should always remember how
frameworks were created a few years ago. Most of them
were more or less unoptimized junk created by one guy to
help him speed up his development process, without much
care for documentation, elegance, ease of use, or even
readability of his code. Then another group of guys took
this code and bloated it with a patchwork of extra
functionalities barely consistent with the original code.
Then it became apparent that this whole lot needs a solid
cleanup in order to be usable, but this would mean either
rewriting it from scratch or packaging code in additional
wrapper classes, further increasing its unnecessary
complexity.
Of course, today the disorganized origin of frameworks is
not as evident as before because the quality of code has
risen considerably. But still, that's why most beefed-up
frameworks have performance issues. That's why they are
39
www.it-ebooks.info
not always easy to learn. And that's why new ones emerge
to cover up weaknesses of older ones. And finally that's
why major frameworks provide completely rewritten 2.0
versions, which address all previously mentioned
problems.

ftp 421 service not available vsftpd

yum install vsftpd
--->サーバー
yum install ftp
--->テスト用のクライアント


★vsftpd tcp_wrappers=YES
    ==>権限/etc/hostsに渡る

★vsftpd tcp_wrappers=YES
500 failed to open file
 =>SeLinux有効になっってる。
  getenforce
  sudo setenforce 0;

2014/11/14

systemd mysql.service file where

Q:
mysqlをrpmをインストールして、systemctlの設定はどこ?
==>何?mysql?

sudo systemd show mysql

here is the same man

Implementation of systemd is imminent, yet after days of research I can
not find a mysqld.service file that actually works in Debian.  I've
searched and searched, asked on mailing lists, and asked in IRC on
#debian, #systemd, and #mysql.

Nobody knows, or at least nobody helps.  There isn't even a
mysqld.service file in Sid's mysql-server package.

=ーー>ぜんぜんみつかりません。。。

じゃ。。rpmファイルを解析する
=ー>そんなsrc.rpmはない。。

yum localinstall
==>
ローカルにあるのrpmファイルをyumでインストールする方法。
依存性のファイルをレポジトリから探してきてくれるのが超便利です。

=-->ないです。

How Do I Convert A SysV Init Script Into A systemd Service File?
SysV Init Script????
systemd Service File??
何か合っている。


A:==>init.d/のしたにtestを作って、
sudo systemctl show testを確認するところ
    ExecStart={ path=/etc/rc.d/init.d/test ; argv[]=/etc/rc.d/init.d/test start ; ignore_errors=no ; start_time=[n/a] ;
    ExecStop={ path=/etc/rc.d/init.d/test ; argv[]=/etc/rc.d/init.d/test stop ; ignore_errors=no ; start_time=[n/a] ;
ありますね。。。
結論的には、mysql.serviceは存在しない。systemdはinit.d↓のスクリプトを使って偽装(init.dしたのスクリプトは大体、start,stop restart status)があるので

2014/11/13

linux eth1 ifconfig network-scripts

Q:今のVMですが、自動的にIPをアサインする物があり、
ifconfigで=> eth1 eth2
 /network-scriptsのところは、eth0だけ。。。中にIPがない
再起動してIPはかわらない。VMであるが、このIPの情報はどこで保存された?
ネットワーク
 1準仮想化ネットワーク(NAT)
 2準仮想化ネットワーク(ホストオンリーアダブター virtualBox Host-only Ethernet Apapter)

A:
  ifup eht0
  ==>デバイスはない
  ifup eht1
  ==>デバイスに対する設定はみつかりません

==>設定ファイルの名前たしかに対応している
eth1を作ればいい。。

ーーーーーーーーー
DEVICE=eth1
TYPE=Ethernet
IPADDR=
NETMASK=
NETWORK=127.0.0.0
BROADCAST=
OTPROTO=static
ONBOOT=yes
HWADDR=。。。
ーーーーーーーーー

2014/11/07

msg: the python mysqldb module is required

まずは pip を入れる。

 # yum -y install python-setuptools
 # easy_install pip

必要な依存パッケージをインストールする。

 # yum -y install python-devel mysql-devel

 # pip install mysql-python
 # pip freeze | grep -i mysql
 MySQL-python==1.2.3

以上。

2014/10/28

bash if option

if test -x ....
then
fi
====>いろいろな条件

[ -a FILE ]    True if FILE exists.
[ -b FILE ]    True if FILE exists and is a block-special file.
[ -c FILE ]    True if FILE exists and is a character-special file.
[ -d FILE ]    True if FILE exists and is a directory.
[ -e FILE ]    True if FILE exists.
[ -f FILE ]    True if FILE exists and is a regular file.
[ -g FILE ]    True if FILE exists and its SGID bit is set.
[ -h FILE ]    True if FILE exists and is a symbolic link.
[ -k FILE ]    True if FILE exists and its sticky bit is set.
[ -p FILE ]    True if FILE exists and is a named pipe (FIFO).
[ -r FILE ]    True if FILE exists and is readable.
[ -s FILE ]    True if FILE exists and has a size greater than zero.
[ -t FD ]    True if file descriptor FD is open and refers to a terminal.
[ -u FILE ]    True if FILE exists and its SUID (set user ID) bit is set.
[ -w FILE ]    True if FILE exists and is writable.
[ -x FILE ]    True if FILE exists and is executable.
[ -O FILE ]    True if FILE exists and is owned by the effective user ID.
[ -G FILE ]    True if FILE exists and is owned by the effective group ID.
[ -L FILE ]    True if FILE exists and is a symbolic link.
[ -N FILE ]    True if FILE exists and has been modified since it was last read.
[ -S FILE ]    True if FILE exists and is a socket.
[ FILE1 -nt FILE2 ]    True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
[ FILE1 -ot FILE2 ]    True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not.
[ FILE1 -ef FILE2 ]    True if FILE1 and FILE2 refer to the same device and inode numbers.
[ -o OPTIONNAME ]    True if shell option "OPTIONNAME" is enabled.
[ -z STRING ]    True of the length if "STRING" is zero.
[ -n STRING ] or [ STRING ]    True if the length of "STRING" is non-zero.
[ STRING1 == STRING2 ]     True if the strings are equal. "=" may be used instead of "==" for strict POSIX compliance.
[ STRING1 != STRING2 ]     True if the strings are not equal.
[ STRING1 < STRING2 ]     True if "STRING1" sorts before "STRING2" lexicographically in the current locale.
[ STRING1 > STRING2 ]     True if "STRING1" sorts after "STRING2" lexicographically in the current locale.
[ ARG1 OP ARG2 ]    "OP" is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if "ARG1" is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to "ARG2", respectively. "ARG1" and "ARG2" are integers.

linux gnome 電源管理問題、vboxディスク拡張

----
インストールに問題があります!
GNOME電源管理のデフォルトの設定が正しくインストールされていないようです。
システム管理者に問い合わせてみて下さい。
---

原因はおそらくHDD残量の不足かと思います。
df -h
==>Use 100%

・virtualbox ハードディスク拡張
VBoxManager.exe modifyhd "*.vid" --resize **

で。。。GParted Live (Default settings)でやる

・linux disk構成管理
ここもいろいろわからない
disk-->物理ボリュームー>論理ボリュームグループー>論理ボリューム
(下記はファイルシステムの領域に入る)
ー>マウントポイントー>フォルダ/file

df,fdisk===>などなど、普段は使っているが、上記のどの段階で何のためのコマンド、よくわからず。。。
df ==>ファイル・システムについて,使用領域と空き領域のサイズを表示する
mount ==>論理ボリュームをファイルシステムにいれる。/etc/fstab 自動的に入れる物

fdisk コマンドで領域の確保を行い、 mke2fs コマンドで領域のフォーマットを行っておく必要があります(ファイルシステム)
fdiskコマンドでは、ハードディスクのパーティションの作成、削除、また、パーティション情報を調べる事ができます。

・ディスクの状況を確認する
dmesg | grep sd
dmesg | grep sd=>SATAの場合

ここでも
/dev/hd...
/dev/sd...

そして sudo fdisk -l /dev/...
/dev/sda2              64        1045     7875584   8e  Linux LVM
==>こいつはLVM


sudo pvdisplay
sudo vgdisplay
sudo lvdisplay

Lvmのサイズを拡張する
lvextend -L12G /dev/myvg/homevol

sudo pvcreate /dev/sdb5
  sudo vgextend ubuntudevbox2 /dev/sdb5
  sudo lvextend 100% /dev/ubuntudevbox2/root
  lvextend --help
  sudo lvextend -l 100%FREE /dev/ubuntudevbox2/root
  sudo lvextend -r -l 100%FREE /dev/ubuntudevbox2/root
sudo resize2fs  /dev/mapper/ubuntudevbox2-root

==>resize2fsようなの物がまるね。。。
==>resize2fs - ext2/ext3 ファイルシステムのサイズを変更する

何となく。。

2014/10/26

eclipse jdk os 32bit/64bit

I am confusing with that
I think if the os is 32bit ,then jdk,eclipse also 32bit 
64bit the same
but .....
there is a lot aborting ...
i am wrong? they are wrong?

eclipse-java-luna-SR1-win32-x86_64
window7 64bit
jdk-8u20-windows-x64


i think it will  be ok
but ....


oh ,this time it goes oK! I uninstall all the jdk,and reinstall them

2014/10/24

ruby `require': no such file to load -- mysql (LoadError)

require 'mysql'
でエラーになった
でも
sudo gem install ruby-mysqlをインストール済みが。。
先に
require 'rubygems'
が必要だ。。

で、sudo ruby
=>sudo: ruby: コマンドが見つかりません
which ruby
==>/usr/local/bin

で、visodu
visudoでsecure_pathに「/usr/local/bin」を追加する。

linux 色 front 環境設定

★vi
:syntax on
:syntax off


★lsの色
echo $LS_COLORS
sudo vi /etc/DIR_COLOR
eval ``

★front PS1
==>Linuxの標準シェルであるbashでは、PS1という環境変数によってプロンプトを定義している。従って、exportコマンドでPS1を変更すればいい。
==>front?
ログインして、「test@somehostname」のことね。
export PS1="$"
ログインして、「$」に変わる

~/.bashrcを修正して

PS1="\[\033[0;34m\]$PS1"
の0;32の部分はfrontの色変わる

linux sed

・sed 's/^192.168.0.1/&localhost/ example
==>^頭、192.168.0.1ーー>192.168.0.1&localhost

・sed '/test/'d example
==>testを含める行を削除する
 g-->これはないと、行単位の初めての物がターゲットになる

・sed '2d' example =->d 削除、2第二行
 sed '$d' example  最後の一行を削除する
 sed '2,$d' example  第2行から最後の一行を削除する
 
・sed -n '/test/mytest/p' example
  ==>-n p 条件を満たす行をプリンターする
 
・sed 's#10#100#g' example
=->s後ろの物が分隔用になる

・sed -n '/test/,/let/p' example
testとletの間で確定された行をプリンタする

・sed -e '1,5d' -e's/let/letus/g' example
実行できる

2014/10/03

pipをインストール

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py --proxy="http://proxy.jp:8080"

apache Invalid command 'Order'Add Star

LoadModule authz_host_module modules/mod_authz_host.so
=>load module mod_access_compat, or update configuration to 2.4 authorization directives.

ruby require エラー

Rubyファイルを実行するとrequireでエラーがでてるよってとき

require "kakiku"
==>エラーになり、書き方を修正する
require File.expand_path('kakiku.rb',__FILE__)=>NG
require File.expand_path('./kakiku.rb',__FILE__)=>NG
require File.expand_path('../kakiku.rb',__FILE__)=>OK

バージョン:
ruby 2.0.0p353 (2013-11-22) [x86_64-linux]

perl モジュール install

mysql_install_db --defaults-file=/etc/my.cnf --user=mysql
==>Data-Dumperのperlのモジュールが必要で。。



perlモジュールをインストールするにはCPANを使用すると便利である

http://search.cpan.org/でほしい物を検索する

例:
http://search.cpan.org/~smueller/Data-Dumper-2.154/Dumper.pm

wget http://search.cpan.org/~smueller/Data-Dumper-2.154/Dumper.pm
tar xzvf Data-Dumper-2.154.tar.gz
cd Data-Dumper-2.154
perl Makefile.PL
インストールして途中でエラーになった。
Can't locate ExtUtils/MakeMaker.pm in @INC
==>yum install perl-ExtUtils-MakeMaker

make
make test
==>エラーになった!!


make install


★他のエラー

    Can't locate CPAN.pm in @INC (@INC contains:....)

⇒ yum install perl-CPAN

    Can't locate Test/More.pm in @INC (@INC contains:....)

⇒ perl -MCPAN -e 'install Test::More'

    Can't locate LWP/Simple.pm in @INC (@INC contains:....)

⇒ perl -MCPAN -e 'install LWP::Simple'

    perl -MCPAN -e 'install URI'
    Can't locate object method "install" via package "URI" at -e line 1.

⇒CPANシェルで実行するとOK

   Can't locate Time/HiRes.pm in @INC
==>yum install perl-Time-HiRes


===>ああ。。あきらめる

yum list | grep perl | tee perl_package.log
==>あった。
sudo yum install perl-Data-Dumper.x86_64

easy_installなどなど、みんなyumにしていいじゃん?

2014/09/19

mysql function DETERMINISTIC

・エラー:
This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)


・ファンクション生成に対する(SUPER権限を持たなければならず、決定論的か、データを修正しないかの別を宣言しなければならない)前の規制を緩和するには、グローバル log_bin_trust_function_creatorsシステム変数を1に設定します。
デフォルトで、これは0に設定されていますが、ユーザはこのようにして変更することができます。

mysql> SET GLOBAL log_bin_trust_function_creators = 1;

DETERMINISTIC特性とNOT DETERMINISTIC特性は、
あるインプットに対して、いつも同じ結果を生成するか否かを示します。
いずれかの特性を附与しない場合、デフォルト設定はNOT DETERMINISTICとなります。
ファンクションが決定論的であると宣言するには、DETERMINISTIC を明確に規定しなければなりません。

2014/08/18

mysqldumpでwhen using LOCK TABLESというエラーが出る

MySQLはダンプする前にテーブルにLockをかけるらしいのだが、そのLockをかけることができないようだ。
そこで、ダンプ時に誰も使っていない事が確認できたので(INSERTすることがない)、「--skip-lock-tables」というオプションを使ってダンプを行ったところ無事に完了した。
==>だれがつかったね。。

==> single-transaction
このオプションだとテーブルをロックせず、トランザクションの範囲でバックアップしてくれるとのことだった。

ruby on rails

bundle install
==>Install the modules include in the gemfile.
Unless you specify a version number to the gem command, Bundler will automatically install the latest version of the gem.
bundle update===>update!!


・deployの準備
bundle install --without production
group :production do
    gem 'pg'
    gem 'rails_12factor'
end

・@なになに。。
Once the @users variable is defined, the controller calls the view (Step 6), shown in Listing 2.6. Variables that start with the @ sign, called instance variables, are automatically available in the view;

・rails new sample_app --skip-test-unit
===>not to create test directory

・rails generate controller StaticPages home help --no-test-framework
===>「home help」MVCセットで2つ作る

・rails generate rspec:install
bundle exec rspec spec/requests/..rb==>実行、red->green->refactor

・JetBrains:
==>alt+ctr+s =->editerのところでline番号を表示する。

・<% provide(:title, 'Home') %>
Rails should call the provide function and associate the string ’Home’ with the label :title.
<%= yield(:title) %>
    yield==->自分で定義したブロック付きメソッドでブロックを呼び出すときに使います

・application.html.erb:
<%= yield %>
==>This code is responsible for inserting the contents of each page into the layout. It’s not important to know exactly how this works; what matters is that using this layout ensures that, for example, visiting the page /static_pages/home converts the contents of home.html.erb to HTML and then inserts it in place of <%= yield %>.


・first_name + " " + last_name
===
"#{first_name} #{last_name}"

・# Single-quoted strings don't allow interpolation

・Note that Ruby functions have an implicit return
meaning they return the last statement evaluated

・a = [42, 8, 17]
a[-1]==>17
a.sort
a.sort!===>a!
a.push(6)
a << 7
a << "foo" << "bar"

a.split--->array になる
array.join-->stringになる


(0..9).to_a
a[0..2]


・|i|
==>The vertical bars around the variable name in |i| are Ruby syntax for a block variable

mysql crash

★MySQL のクラッシュの多くは、インデックスファイルやデータファイルの破壊が原因です
-flush を指定して mysqld を開始することによって、各 SQL コマンド実行後、強制的にすべてをディスクと同期させることができます。
 つまり、以下のことがなければ、通常は破壊されたテーブルを得ることはありません。

    誰かまたは何かが、更新中に mysqld またはマシンを強制終了した。

    更新中に mysqld が死ぬようなバグを見つけた。

    テーブルを適切にロックしないで、mysqld 外でデータまたはインデックスフファイルを操作している。

    優れたファイルシステムロック(通常、lockd デーモンによって処理される)をサポートしていないシステム上で、同じデータに対して、多くの mysqld サーバを実行しているか、--skip-external-locking で複数サーバを実行している。

    mysqld を混乱させるような不正なデータを含んだ、破損したインデックスまたはデータファイルがある。

    データストレージのコードにバグを発見した。これはおそらくあり得ないことだが、可能性としてはある。この場合、修正されたテーブルのコピーに対して ALTER TABLE を使用して、ファイルタイプを別のデータストレージエンジンに変更することができる。

★クラッシュの原因を見つけるのは非常に難しいので、まず、他で動作しているものが自分の環境でクラッシュするかどうかを確認してください。
mysqld --log を使用して、ログの情報から、特定のクエリがサーバを終了させるかどうかを判断する。バグの 95% が特定のクエリに関係している。

mysqldump view only

 mysql -u username INFORMATION_SCHEMA
  --skip-column-names --batch
  -e "select table_name from tables where table_type = 'VIEW'
      and table_schema = 'database'"
  | xargs mysqldump -u username database
  > views.sql
===>テーブルを分けるbackupする際、これがあればべんり。

--skip-column-names:
 結果にカラム名を記述しません===>列名がないこと?
--batch
ブとして、カラムセパレータを使用することで、各行が新しいライン上に配置されるように、結果をプリントします。

2014/08/09

window commandline sleep hibernate

Sleep Computer
Rundll32.exe powrprof.dll,SetSuspendState Sleep
If it hibernates instead of Sleep: Hibernate must be OFF

■休止状態機能の有効・無効を切り替える方法

コマンドプロンプトを管理者として実行し、次のコマンドを入力する。
  • 有効にする場合
    > powercfg /hibernate on
  • 無効にする場合
    > powercfg /hibernate off
  • 現在の設定を確認する場合
    > powercfg /a

2014/07/17

git 理解深める

git config --global alias.co checkout ==>カスタマイズ
git config --global core.editor "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
.gitignore
==>
/.bundel
/db/*.sqlite3
/db/*.sqlite3-
/log/*.log


git log

remote/master
--->git clone ../...を実行する
local:master

リモートサーバーは更新された!
git fetch origin ==>リモートの更新を取得する

git remote add theName address ==>remote サーバー追加、ローカルでtheNameの名前で
git fetch name==>


Git 開発者の多くはこの考え方にもとづいた作業の流れを採用しています。つまり、完全に安定したコードのみを master ブランチに置き、いつでもリリースできる状態にしているのです。それ以外に並行して develop や next といった名前のブランチを持ち、安定性をテストするためにそこを使用します。常に安定している必要はありませんが、安定した状態になったらそれを master にマージすることになります

・git push -u origin masterとすると、次回からは git pushだけでorigin masterにpushする
==>For every branch that is up to date or successfully pushed, add
           upstream (tracking) reference

・git checkout -b modified-locally 
git branch==->全てのブランチ

・localで、
git checkout old-branch
git merge new-branch
==>new-branchをold-branchにmergeする
git branch -d new-branch
git branch -D new-branch--->mergeしていない物があってもDELETE!

・config
git config  --add receive.denyCurrentBranch ingore
git push
===>git config --unsetall key

・ちなみにcommit -vをすると、今から何をコミットしようとしているかのdiffなどが見れるからより安心

ansible 特殊 オプション

対象ホスト:
    hosts:
    [test-sever]
    test-test-[1:2][1:6]

テストオプション
★--list-hosts 対象ホスト名をリストするだけ、ほかに何もしない
    ansible test-server -m ** -a "...." -i hosts --list-hosts
    =>
    test-test-11..test-test-16
    test-test-21..test-test-26

★-l されにホストのfilterである!
  ansible test-server -m ** -a "...." -i hosts -l test-test-11 ==>test-test-11だけ対象になる
  ansible test-server -m ** -a "...." -i hosts -l test-test-1* ==>test-test-11~16 対象になる

★-f 一回実行する数
★-C テストモード

2014/07/15

Ruby On Rails

・ruby をインストールする
==>環境変数に追加する
・DevKit
ーー>downloadして解凍し、インストールする
ruby dk.rb init
==>rubyのディレクトリをconfi.ymlにincludeする
ruby dk.rb install

gem update --system
gem update rake
gem install rails

エラー==>x86_64-w64-mingw32-gcc command not found
    ==>devkitのバージョンが間違った!!


rails new blog
==>project作成

bundle install
==ー>projectを配置する

rake db:create
=->dbを作成する、sqlite is default

rails server
==>serverを起動する

=->地雷:no source of timezone data
----------
Try changing the tzinfo-data line in your Gemfile to gem 'tzinfo-data', platforms: [:x64_mingw, :mingw, :mswin] and then running bundle update.

The :x64_mingw platform option is needed to match 64-bit Windows MinGW builds of Ruby (such as the RubyInstaller x64 builds).
bundel update
---------

rails g controller home index
rails g scaffold post name:string title:string content:text
=>postのapp Templateみたいな物!



class Post < AcitveRecond :: Base
end

==>AcitveRecond :: Baseを継承しているから、CRUD、validate、などすごい機能があります。

==>何となくPLAY Frameworkに似っている!!。同じスタイル!

rails g model comment commenter:string body:text post:references

rake db:migrate===>dbを更新する,modle更新の後で。。

linux awk

ファイルを行ベースで読み込んで、ディフォルトにスペースを使ってその
行をsplitする

awk '{pattern + action}' {filename}
 -F フィルド分割用
 

cat /etc/passwd | awk -F ':' '{print $1}'
=>etc/passwdのアカウントだけ
cat /etc/passwd | awk -F ':' '{print $1"\t"$7}'

・header,tailerを出力
cat /etc/passwd | awk -F ':' 'Begin {print "name,shell"} {print $1"\t"$7} {print "blue,/bin/nosh"}'

・awk -F: '/root/' /etc/passwd
==>rootを含める行を出力する

linux vi 置換 行

%1,10s/a/b/g
==>1行目から10行目まで

%11s/a/b/g
==>11行目から

2014/07/14

bash pass array as paramater

baba=booba
variable=baba
echo ${variable} # baba
echo ${!variable} # booba
==>!の使い方==>更にこれを変数として扱う

bashの引数はそもそもARRAYに入れている!こいつです==>$@

---------
show_array(){
for port in $@
do
    echo $port
done
}
show_array 1 2 3
==>OK

show_array(){
arrayParam=$@
for port in $array
do
    echo $port
done
}
show_array 1 2 3
==>OK

arr=(1 2 3)
show_array(){
for port in $@
do
    echo $port
done
}
show_array ${arr[@]}
=>OK

${arr[@]}==>[@]がないと、C言語と同じ、始めの一つのパラメータだけ対象になる

#===>長さの意味で。。。

2014/07/03

ajax



借助于Ajax,可以在用户单击钮时,使用JavaScriptDHTML立即更新用户页面,并向服出异步行更新或查询数据操作。当求返回,就可以使用JavaScriptCSS来相地更新面中的某一部分,而不是刷新整个面(節約!!)最重要的是,用甚至不知道浏览器正在与服器通信(危ない?水面下のやりとりで、複雑になるWeb站点看起来像是即作出响

基于Ajax用需要增加大量JavaScript,增加大量JavaScript后的Web面在第一次加载时速度将比传统Web面慢==>複雑

avaScript本身不是面向象的言,这严重限制了JavaScript的可重用性。JavaScript并没有一个完善的调试工具,无形中也加重了程序担==>今のところ何となく改善された?

Ajax术则是用入一个字符,用都将向服送一次求==>監視
ちょっと使って、痒いところを少し触って、ユーザーに少し快感を与える程度でいいと思う。。。。。。。

angularJS scope.$apply

JavaScript is Turn Based
私たちが記述するJavaScriptのコードは一度に全て実行されるのではなく、ターンベースで実行される。各ターンは始めから終わりまで中断せずに走り、ターンが走っている間はブラウザ上では何も起きない。他のどのJavaScriptのコードも走っていない時は、Webページインタフェースは完全に固まる。だから不十分なJavaScriptコードはウェブページの動きを止めてしまう。

変更した時に通知でき、ページを更新できる。==>EmberJS や KnockoutJS

どのJavaScriptコードのターンが終わった時でも、値が変化したことを確認する。=>AngularJS
この戦略を動かすためには、データが変更された可能性がある時点を知る必要がある。そしてこれが $scope.$apply が動き始める場所だ。
  $scope.$apply(function () { $scope.msgs.push(JSON.parse(msg.data)); });

==>このapplyの中の物は、後で実行される感じだね。。。

JavaScript EventSource

・どこの仕様?Server-Sent Eventsで
var source = new EventSource("/chatFeed/");

# receive messages
$scope.chatFeed.addEventListener("message", $scope.addMsg, false);
/** handle incoming messages: add to messages array */
    $scope.addMsg = function (msg) {
        $scope.$apply(function () { $scope.msgs.push(JSON.parse(msg.data)); });
    };

・サーバー側は、必ず text/event-stream という MIME type で返さなければならない。
 /** Controller action serving activity based on room */
  def chatFeed(room: String) = Action { req =>
    println(req.remoteAddress + " - SSE connected")
    Ok.feed(chatOut
      &> filter(room)
      &> Concurrent.buffer(50)
      &> connDeathWatch(req.remoteAddress)
      &> EventSource()
    ).as("text/event-stream")
  }
 
==>
handle data streams reactively
I know, the method's name "&>" can make some of you go away. Please stay! This sign is like the pipe in bash. It is very easy to understand:
fileLineStream(file) &> lineParser
==>fileLineStream(file).through(lineParser)


Server-Send Events
When we want to send events in "real time" to the browser, what technologies are available?

    polling: the browser pools the server every x milliseconds to check if there is a new message. This method is not very efficient, because a lot of requests are necessary to give the illusion to update the application in real time.
    long-polling (or Comet): the browser opens a connection to the server (for example in a iframe), and the server keeps the connection opened. When the server wants to push data to the client, it sends this data with the opened connection. The client receives the data, and opens a connection again for further messages. With this method, the browser is always showing that it is waiting for data. This technology does not scale on threaded system, as each opened connection uses a thread. In JEE environment, we need an asynchronous servlet 3.1 not to make the server exploding.
    Server-Send Events (SSE) are quite similar to Comet. The main difference is that the browser manages this connection. For example, it opens the connection again if it falls.
    WebSockets provide a bi-directional, full-duplex communications channels. It is a different protocol than HTTP.

I choose to use Server-Send Events instead of WebSockets because of the following reasons:

    I've already played with WebSockets and wanted to try something new.
    WebSockets are great and can communicate in both directions. But this technology is a new protocol, sometimes difficult to integrate in an existing infrastructure (Proxy, Load-Balancer, Firewall...) Server-Send Events, on the other hand, use the HTTP protocol. The PaaS Heroku does not support WebSockets yet, but support SSE. When pushing data from the server to clients is all what you need, SSE can be what is the most appropriate and is well supported (except in IE for the moment)

2014/06/27

java Fork/Join

★The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.
===>それはいいね!!



★例:

package testfork;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class MaximumFinder extends RecursiveTask {

    private static final int SEQUENTIAL_THRESHOLD = 100;

    private final int[] data;
    private final int start;
    private final int end;

    public MaximumFinder(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    public MaximumFinder(int[] data) {
        this(data, 0, data.length);
    }

    private Integer computeDirectly() {
        System.out.println(Thread.currentThread() + " computing: " + start
                + " to " + end);
        int max = Integer.MIN_VALUE;
        for (int i = start; i < end; i++) {
            if (data[i] > max) {
                max = data[i];
            }
        }
        return max;
    }

    @Override
    protected Object compute() {
        final int length = end - start;
        if (length < SEQUENTIAL_THRESHOLD) {
            return computeDirectly();
        }
        final int split = length / 2;
        final MaximumFinder left = new MaximumFinder(data, start, start + split);
        left.fork();
        final MaximumFinder right = new MaximumFinder(data, start + split, end);
        return Math.max((Integer) right.compute(), (Integer) left.join());
    }

    public static void main(String[] args) {
        // create a random data set
        final int[] data = new int[100000];
        final Random random = new Random();

        for (int i = 0; i < data.length; i++) {
            data[i] = random.nextInt(100);
        }

        // submit the task to the pool
        final ForkJoinPool pool = new ForkJoinPool(4);
        final MaximumFinder finder = new MaximumFinder(data);
        System.out.println(pool.invoke(finder));
       
    }
}


★ForkJoinPoolに入れるタスクはForkJoinTask型であるが、実際にはRecursiveTaskかRecursiveActionのいずれかから派生するのが便利である。
RecursiveTaskは戻り値のあるタスク、RecursiveActionは戻り値が無いタスクを定義するのに使う。

★Callable, RunnableをForkJoinTaskに変換するためのForkJoinTask.adapt()メソッドを使うこともできる


ForkJoinPool pool = new ForkJoinPool(
 Runtime.getRuntime().availableProcessors(),
 ForkJoinPool.defaultForkJoinWorkerThreadFactory,
 null,
true); // タスクの積み上げにFIFOモードを使用する.(通常はSTACKモード)

Why reduce the size of the Java JVM thread stack

★あれ、threadStack is out of heap...

When Java creates a new thread, it pre-allocates a fixed-size block of memory for that thread's stack. By reducing the size of that memory block, you can avoid running out of memory, especially if you have lots of threads - the memory saving is the reduction in stack size times the number of threads.

The downside of doing this is that you increase the chance of a Stack Overflow error.

Note that the thread stacks are created outside of the JVM heap, so even if there's plenty of memory available in the heap, you can still fail to create a thread stack due to running out of memory (or running out of address space, as Tom Hawtin correctly points out).

redis 試し

・can write to db automatically
・can store thing with four structures not only plain string key
=->redis can used to slove a wider range of problems
STINGS、LIST、SET、HASH、ZSET(順番あるET)

・publish/Subscribe 機能?raid,master/slave機能

・in-memory databases! write to hardDisk

Depending on how careful you want to be with your
data, append-only writing can be configured to never sync, sync once per second, or
sync at the completion of every operation.

・for most
databases, inserting rows is a very fast operation (inserts write to the end of an on-disk
file, not unlike Redis’s append-only log). But updating an existing row in a table is fairly
slow (it can cause a random read and may cause a random write).

===>何が良さそうだね。。


redis-cli
=->クライアントを起動する

set hello world
get hello
del hello

大文字と小文字は違う。。。

rpush list item
rpush list item2
rpush list item3

lrange list 0 -1 ==>全ての物を表示する
lrange list start end

lindex list 1 ==>items
lpop list==>item左側から吐き出す
==>stackだね。。。

In Redis, SETs are similar to LISTs in that
they’re a sequence of strings, but unlike
LISTs, Redis SETs use a hash table to keep
all strings unique


sadd set item1
sadd set item2
sadd set item3
smembers==>item1 item2 item3
sismember set item3
srem set item1


Whereas LISTs and SETs in Redis hold
sequences of items, Redis HASHes store a
mapping of keys to values.

HSET hashName key value
Hget hashName key
HDEL hashName key
HGETALL


The keys (called members)
are unique, and the values (called scores) are limited to floating-point numbers. ZSETs
have the unique property in Redis of being able to be accessed by member (like a
HASH), but items can also be accessed by the sorted order and values of the scores
==>得点あり score

zadd zset 333 item1
zadd zset 444 item2
zadd zset 555 item3

zrange zset 0 -1
zrange zset 0 -1 withscores
zrangebyscore zset 0 335 withscores



conn = redis.Redis()
conn.get('key')
conn.incr('key')
conn.decr('key')

★snapshots persistence
redis-cli

=>bgsave,save(専務)
dbfilename dump.rdb
dir /var/lib/redis
==>/var/lib/redis/dump.rdbで保存される
設定ファイルでの設定:
save 900 1
save 300 10
save 60 10000
==>
Redis will automatically
trigger a BGSAVE operation if 10,000 writes have occurred within 60
seconds since the last successful save has started

When Redis receives a request to shut down by the SHUTDOWN command, or it
receives a standard TERM signal, Redis will perform a SAVE


if we’re
running on a virtual machine, letting a BGSAVE occur may cause the system to pause
for extended periods of time, or may cause heavy use of system virtual memory, which
could degrade Redis’s performance to the point where it’s unusable.

★append-only file persistence

file.write();
file.flush();