jQuery復習

f:id:reonreon3reon:20140412033523p:plain

f:id:reonreon3reon:20140412033742p:plain

f:id:reonreon3reon:20140412033849p:plain

f:id:reonreon3reon:20140412033951p:plain
class mainの直下のitem要素

f:id:reonreon3reon:20140412034203p:plain

f:id:reonreon3reon:20140412034456p:plain
containsは要素の中身のフィルタ

f:id:reonreon3reon:20140412034749p:plain

f:id:reonreon3reon:20140412035009p:plain

f:id:reonreon3reon:20140412035147p:plain
a[href ] のように要素は囲む
=が同じ
!= はそれ以外
*=は要素に含む
^=は最初
$=は最後 と同じ要素を含む

f:id:reonreon3reon:20140412035622p:plain

f:id:reonreon3reon:20140412035631p:plain

cssで書いた要素を p 要素に付け加えれる

f:id:reonreon3reon:20140412040024p:plain
html属性を操作

f:id:reonreon3reon:20140412040049p:plain
カスタム属性を操作

f:id:reonreon3reon:20140412040336p:plain

textは文字列自体を変える
htmlはhtml部を変える

f:id:reonreon3reon:20140412040629p:plain
f:id:reonreon3reon:20140412040601p:plain
valで中身を取得っぽい

f:id:reonreon3reon:20140412040836p:plain

  • みたいなタグのテキストを作って、
    ulの次のeq(1)の前にあるものに要素を追加

    f:id:reonreon3reon:20140412041030p:plain
    insertBreforeとBeforeの書き方は違うが同じこと

    f:id:reonreon3reon:20140412041145p:plain
    子要素の最初が prepend / 最後が append

    f:id:reonreon3reon:20140412041435p:plain
    divがボックス
    hide( 800 ms ) はシュッと消える
    Fadeout( 800 ms )はファッと消える

    toggleは消えてたら出てくるし、
    出てたら消える

    f:id:reonreon3reon:20140412041656p:plain
    消えた後にアラートが出てくる、(要は、その後の処理ができる、関数を実行できる)

    f:id:reonreon3reon:20140412041829p:plain
    clickがクリックされたとき

    f:id:reonreon3reon:20140412041945p:plain
    mouseoverがmouseのカーソルがその要素の上にあるとき
    $(this)は同じ要素のことを指しているときにできる

    f:id:reonreon3reon:20140412042157p:plain
    メソッドチェーンを使ってる
    mouseoutで離れたとき、
    mousemoveはマウスが上で動いている時で、
    function( e ) の eは引数で、 e.pageX (カーソルのx軸を取る) などできる

    イベントは他にもあるので、jQueryの公式サイトを見る

    f:id:reonreon3reon:20140412042640p:plain
    これが要素で、
    f:id:reonreon3reon:20140412042706p:plain
    #nameにfocusがあたったとき、色を変える
    そのままだと元に戻らないので、blurで元に戻す(メソッドチェーン)

    changeはその要素の値が変わったときに使う

    f:id:reonreon3reon:20140412043156p:plain
    ボタンを作る

    f:id:reonreon3reon:20140412043231p:plain
    要素buttonがclickされたとき、
    変数pに、

    に text文字列が代入され、クラスも定義される.
    この要素の前に p が配置される

    普通に removeしたいが、 jQueryは一番最初に呼ばれたときに起動するもので、
    その時には vanishというクラスが出てきていないため、できない

    最初にvanishの親要素を選ぶ。
    "親要素".on ( どのような処理 , 'クラス', 処理 ) ;という感じ

  • vimの設定で...

    学校のサーバでFlask書こうとおもってたら、
    「あれ?よく考えたら先輩のvimrcぱくってたから使いづらい」
    って思ったので、ゴニョゴニョ書いてたら

    すべてのソースの最後に
    $
    が付くようになりました。
    わけが分からなかったのですが、
    原因は
    set list
    っぽかったです。

    対策です。

    Neobundleでjedi-vimとかも入れたのになぜか
    flaskの補完がでなくてイラツイてます…。

    あと、このサイトから学んだことなんですけど、
    f:id:reonreon3reon:20140409023704p:plain

    これはヤバイですねw
    ヤバイ。

    flaskというよりjedi-vimが機能してないのは
    vimのせい。vimが悪い。
    なぜかというと、python-devが入ってない?多分。
    vim --versionってすると

    1. python3

    ってなってることから、入れた人(先輩)が悪い。

    入れなおす

    % apt-get install mercurial

    参考サイト

    みながらやってみる。

    やってみたら、luaが入ってないとかいう…。
    出来なかったんですよ。

    これを参考にしてまたやり直し。

    また入れなおした!Lua入った!って思ったら

    で発狂したので、./configureを繰り返しました。

    iOS Hacker's HandBookを読みます

    Life is Techに参加してiOSのことを習ったので、
    iOSに興味を持ちました。

    だから、この本も読んでいきたいと思いまーす。
    あと、重要だと思ったところと個人的に面白いなーって思った文だけを抜粋しようと思います。
    意味がはっきりわからない文だけど、重要そうだな。って思ったものの先頭に "???"をつけているので、あとでバイナリの師匠に教えてもらおうかと。

    【Chapter1】iOS Security Basics

    “The original iPad had an ARM Cortex-A8 CPU, which, compared to the CPU present on the original iPhone, was roughly twice as fast.”

    “Another big step forward was the iPad 2 and the iPhone 4S. They both feature ARM Cortex-A9 dual-core processors, which are 20 percent faster compared to the A8 in terms of CPU operations. ”

    “ astonishing is the fact that the GPU of the A9 is nine times faster compared to the A8.”

    “the biggest hardware differences came with the iPhone 3GS and the iPad 2. The iPhone 3GS was the first one to support the “Thumb2 instruction set. The new instruction set changed the way ROP payloads needed to be created. Most code sequences present in previous versions of the device were suddenly different on the 3GS.

    ???“Another relevant hardware component from a security point of view is the baseband. In fact, in most countries the iDevices are bound to a carrier (locked).”
    もう一つのセキュリティの観点から関係のあるハードウェアコンポーネントとして、帯域がある。
    実は、ほとんどの国では、iDeviceはキャリアに紐付けられている(ロックされている)


    “Only recently with the iPhone 4 CDMA and iPhone 4S has Apple moved to Qualcomm.”

    “This malware might be bundled with software the user wants, or it might disguise itself as something the user wants.”

    “ it performs its malicious actions. These actions might include sending e-mails, allowing remote access to an attacker, installing a keylogger, and so on. ”

    “The typical way to protect devices from malware is with antivirus (AV) software. It is the AV's job to determine which software is safe to run and which is not safe to run.”

    “Such attacks are sometimes called drive-by-downloads because, unlike the malware example, the user is mostly an innocent victim and wasn't trying to install any code, but just trying to use his or her device! ”

    “ “Exploitation such as this requires two ingredients. The first is a flaw or vulnerability in the software on the device. The second is a way to leverage this vulnerability to get attacker-controlled code to run on the device. Because of this two-step process, you have two main ways to protect against this kind of attack. ”

    ???“This involves using privilege separation or sandboxing to keep sensitive data from some processes. ”

    “the discussion has centered on security threats for all devices. Next, you examine how attacking an iOS device might differ from attacking a personal computer.”

    iOS is a stripped-down version of Mac OS X, and so many of the vulnerabilities and attacks are shared between the two or are at least very similar."

    ???“The fact that iPhones parse these messages but you don't have corresponding code in Mac OS X demonstrates that in some regards, iOS has a larger attack surface.”

    “ Another example of the expanded attack surface of iOS includes the code running on the baseband processor of the iPhone. ”
    “ We talk about these two iOS-specific attack vectors later in this book in Chapters 6 and 12, respectively.”

    “ Just to see some numbers on the subject, Charlie Miller once fuzzed Preview (the native Mac OS X PDF viewer) and found well over a hundred crashes.”

    ???“When he tried these same files against iOS, only 7 percent of them caused a problem in iOS. This means that just by reducing the PDF features that iOS handled, it reduced the number of potential vulnerabilities by more than 90 percent in this case. Fewer flaws mean fewer opportunities for exploitation.”

    “Beyond just reducing the potential code an attacker might exploit, Apple also stripped down the number of useful applications an attacker might want to use during and after exploitation. The most obvious example is that there is no shell (/bin/sh) on an iOS device. In Mac OS X exploits, the main goal is to try to execute a shell in “shellcode.”

    ???“Therefore, attackers who get code running will have to either perform all of their actions within the context of the exploited process, or bring along all the tools they want to use. Neither or these options are particularly easy to pull off.”

    iOS separates processes using users, groups, and other traditional UNIX file permission mechanisms.”

    ???“Other system processes run as other users such as _wireless or _mdnsresponder. ”

    ???“an attacker who gets full control of a process such as the web browser will be constrained by the fact the code she is executing will be running as user mobile”

    “Likewise, apps from the App Store are limited in what they can do because they will be executed as user mobile as well.”

    ???“only pages in memory that come from signed sources will be executed. This means apps cannot change their behavior dynamically or upgrade themselves. ”

    “Once an exploit is executing code in memory, it might want to download, install, and execute additional malicious applications. This will be denied because anything it tries to install will not be signed.”
    code signedされてないアプリは実行できないってことかな。

    ???“exploits will be restricted to the process they originally exploit, unless it goes on to attack other features of the device.”

    “Once jailbroken, unsigned applications can be executed on the device. J”
    ありゃりゃ、jail breakなんてするもんじゃありませんね。
    (する必要ないからしてないけど)

    “(DEP) is a mechanism whereas a processor can distinguish which portions of memory are executable code and which portions are data; DEP will not allow the execution of data, only code. This is important because when an exploit is trying to run a payload, it would like to inject the payload into the process and execute it. DEP makes this impossible because the payload is recognized as data and not code. ”

    ???“code signing requires that no page may be executed unless it originates from code signed by a trusted authority.”

    “one to obtain code execution and one to leak a memory address in order to perform ROP — or the attacker may be able to get by with having only one very special vulnerability.”








    ぽてち先生からプラティカルな話も聞けて面白かった

    メモ and Keywords

    アロケータ

    ??? use during

    exploitにも限界があるということですな。

    NX bit

    ASLR

    DEP

    次は、Fuzzing読みたい>

    質疑応答タイム

    師匠: コード著名の説明を

    あしがる:
    Code-Signingは、
実行するときの許可書みたいなもので、App Storeからダウンロードしたときに
コード署名があると、実行できて、それがないと実行できない。
ゆえに、インターネットから適当にダウンロードしたアプリを実行しようとすると、
コード署名がないため実行できない。
これ自体がアンチウィルスの役目を果たしてる。


    師匠:
    良いと思います。
    実用的には、コード署名のおかげでいくつかの攻撃を防げていると思います。
    アップデートによる攻撃や、セカンドアプリ内包型のマルウェアなんかはその例ですねー
    最初は悪性な動作を持っていないけれど、外部から悪性なコードをダウンロードしてきて
    より悪性なマルウェアに変化するような攻撃です。
    アップデート
    コード署名が必要な状態でこれをやろうとすると
    新しく外部からダウンロードしてきた悪性なコードに署名がないので
    失敗しますね。

    Life is Tech!ガチ勢じゃない視点から2

    こんにちは、3日間IT高校生を再び勤めさせてもらったあしがるです。

    前回のウケの良かった「Life is Tech!ガチ勢じゃない視点から」です。

    考察

    いきなりですが、今回もビビリました。
    「そのときの感情を述べよ」と言われたら、僕は迷わず言えます。「場違いだ」と。
    >僕より年下しかいない<

    ちょ…僕「ウェイw」じゃなくて「アウェイw」っすよ…。

    今回は流山市のときと比べて中学生が多かったのは、
    初心者が8割を占めているという理由があるからです。
    (僕もその1人なんですが)

    そこから始まる場の緊張。
    「Life is Tech!始まるぞぉお!」「おぉーー!!」
    のときは、ずっと下を向いてました。
    僕はこのノリについていけないんですよぉ…

    とりあえず、班分けされたんですが高校生が固まっていたので
    安堵に包まれました。

    そこから優秀なメンターと開発をし始めました。
    やっぱりLife is Techのコンセプト(教科書、メンター、アイデア紹介)は良くて、
    僕もさっと何を作りたいかというものを考えることが出来ました。

    教科書をざっと読んで、
    自分のブログを参考して、電卓を作ろうと思いました。

    PythonのソースをObjective-Cに直すのが割りと大変で、泣きそうになりました。

    なんやかんやで、Obj-Cの構文のミスは全部とれたんですけど
    バグが取れなくて死亡だったんですが、2日目の夜に開発ブースというホテルの場所が設けられたので、
    そっちでアプリ開発の続きをやろうと思いました。

    開発途中に、代表の水野さんに呼ばれて…「あっもしやこれ…」
    やっぱりそれの件で、どういう感じに思ってるか腹を割って話しました。
    水野さんは、僕の考え方を否定するんじゃなくて2人でずーっとお互いがどういう考え方をしてるか話し合いました。

    水野さんは「ウェイw」の存在はいいと思ってる。
    「アプリ開発に対して、ポジティブにポジティブにやろうとしてる。」
    僕はそうじゃない、Life is Tech!というブランドを掲げてるだけだ。とかとか…。

    僕は自分から教科書を開くような人がもっと必要なんじゃないかと言うと、
    水野さんは「確率論の話で、Life is Techに参加した人が将来、エンジニアが不足した中でどういうポジションに立つか」などなど…。

    僕自身の話もしました。
    僕は自分に自信がないという話で、水野さんは「友達の起業した人とかも、みんな自分が天才だと思ってる」ということを言ってくれて、今は無理でもどんどん自分に自信を抱くべきかと思いました。

    って話し込んでて、気付いたら深夜の2時半でした(白目)
    (ી(΄◞ิ౪◟ิ‵)ʃ) < 開発進捗wwww

    感想

    水野さんの一番言いたかったこととしては、僕が自分より出来ない人を見たときに否定するんじゃなくて、教えれるようになれればいいんじゃないかということです。
    まさにその通りで、友達に「お前は否定でアイデンティティを確立しようとしてる」と言われたのも思い出して、僕自身そういう節があるので改善したいなぁーって…。

    f:id:reonreon3reon:20140402034805p:plain

    なんつって…

    水野さんと喋ってたこと書きましたが、語弊があるかもなので
    鵜呑み?にしないでほしいですけど、とりあえず書きました。
    4時間ぐらい喋ったのちょう楽しかった(進捗死)し、励まされたので頑張ろうと思いました。

    Geventの良さ4

    昨日の続きします。

    multiprocessingのPoolとProcessの違いがちょっとわからなかったんですが、聞いてみたところ、Processは人で,Poolは部屋だそうです。なるほど。わかりやすすぎる。

    > http://ideone.com/GhpaJU
    > これの、
    > gevent.sleep(0)って必要ですか?


    これはコンテキストスイッチさせているんですが、イメージわかりますかね?
    OSのプロセススケジューリングと同じです。

    1.geventはマルチプロセスではないのでプロセスは1つ、CPU(コア)を一つだけ使える
    2. 一つのCPUを複数のgreenletで順番に切り替えながら使う
    (あるときに動いているgreenletは1つだけ)
    3.動いているgreenletがgevent.sleep(0)とすると、CPUを次の人に渡す(コンテキストスイッチ)これはコンテキストスイッチさせているんですが、イメージわかりますかね?
    OSのプロセススケジューリングと同じです。
    なかなかいい絵がないんですが、↓こういう感じです。
    4. geventはマルチプロセスではないのでプロセスは1つ、CPU(コア)を一つだけ使える
    5.一つのCPUを複数のgreenletで順番に切り替えながら使う
    (あるときに動いているgreenletは1つだけ)
    動いているgreenletがgevent.sleep(0)とすると、CPUを次の人に渡す(コンテキストスイッチ

    ってなんでこんなわかりやすく説明できるんでしょ…

    f:id:reonreon3reon:20140329184632j:plain

    #source 01.py
    from multiprocessing import Process, Queue
     
    def f(queue):
        queue.put([42, None, 'hello'])
     
    if __name__ == '__main__':
        queue = Queue()
        p = Process(target=f, args=(queue,))
        p.start()
        print(queue.get())   # prints "[42, None, 'hello']"
        p.join()
    
    #source 02.py
    # your code goes here
    from multiprocessing import Process, Pipe
     
    def f(conn):
        conn.send([42, None, 'hello'])
        conn.close()
     
    if __name__ == '__main__':
        parent_conn, child_conn = Pipe()
        p = Process(target=f, args=(child_conn,))
        p.start()
        print(parent_conn.recv())   # prints "[42, None, 'hello']"
        p.join()
    

    source 01.pyと02.pyは全く同じ挙動をしているということです。
    もうちょっと勉強する必要があります…。


    あと、こんな宿題も出してもらいました。

    #source 03.py
    from multiprocessing import Process
    import time
     
    def f(queue):
        queue.insert(0, [42, None, 'hello'])   # queue.push()
     
    if __name__ == '__main__':
        queue = []   # using list as queue
        p = Process(target=f, args=(queue,))
        p.start()
     
        # get value from the child
        while True:
            try:
                val = queue.pop()
                break
            except IndexError:  # queue is empty
                time.sleep(0.1)
     
        print(val)   # never reached!
        p.join()
    
    #source 04.py
    from threading import Thread
    import time
     
    def f(queue):
        queue.insert(0, [42, None, 'hello'])   # queue.push()
     
    if __name__ == '__main__':
        queue = []   # using list as queue
        p = Thread(target=f, args=(queue,))
        p.start()
     
        # get value from the child
        while True:
            try:
                val = queue.pop()
                break
            except IndexError:  # queue is empty
                time.sleep(0.1)
     
        print(val)   # works fine
        p.join()
    

    内容

    source03.pyと04.pyは一見同じように見えますが、
    multiprocessingだとlistをQueueのように使えず、
    threadingだと使えるというとのことです。

    それはなぜかという宿題です。

    ヒント

    メモリ空間


    だそうです。本当にありがたいです。
    頑張って僕なりの答えを出したいと思います。

    Geventの良さ3

    Scapyに移りたかったんですけど、さすがに中途半端すぎるので、
    Geventの良さ1が始まってから、2日ぐらいしか経ってないので、一週間は頑張ろうと思います。

    #multiprocessing
    def queue_func(queue):
        for i in range(30):
            time.sleep(0.5 * random.random())
            queue.put(i*i)
        queue.put('STOP')
    
    def test_queue():
        q = multiprocessing.Queue()
    
        p = multiprocessing.Process(target=queue_func, args=(q,))
        p.start()
    
        o = None
        while o != 'STOP':
            try:
                o = q.get(timeout=0.3)
                print(o, end=' ')
                sys.stdout.flush()
            except Empty:
                print('TIMEOUT')
    
        print()
    

    また師匠に質問したのがですね、

    >Queueを引数にするのがよくわからないです
    Pipeは引数でイメージが考えやすいんですが…
    もしかしてですけど、
    i*iっていう計算をすべて並列でやってるってことですか?
    それだと、プロセス間の通信っていう概念ではなくなりますし///


    ッて感じです。
    僕のそもそもの「プロセス間通信」っていう考え方が間違ってるかもしれないですね。
    僕が思ってるのはManagerがやることかもしれない。
    かもしれない。

    #gevent
    
    import gevent
    from gevent.queue import Queue
    
    tasks = Queue()
    
    def worker(n):
        while not tasks.empty():
            task = tasks.get()
            print('Worker %s got task %s' % (n, task))
            gevent.sleep(0)
    
        print('Quitting time!')
    
    def boss():
        for i in xrange(1,25):
            tasks.put_nowait(i)
    
    gevent.spawn(boss).join()
    
    gevent.joinall([
        gevent.spawn(worker, 'steve'),
        gevent.spawn(worker, 'john'),
        gevent.spawn(worker, 'nancy'),
    ])
    

    ソースの内容は違いますが、なんとなく違いがわかりますねー。

    multiprocessingは Queueオブジェクト自体がアイテム、引数として並列らしき関数に渡されて、
    そこでputなりgetなりされてますね。
    一方、Geventはそれ自体を動かしてるって感じしますね。

    って書いてて思ったんですが、ソースの書き方によっては別に同じような書き方ができるんじゃないかと思いました。

    あと、ここにかかれてる gevent.sleep(0)の存在意義がわからなかったので、
    師匠に聴いてみました。

    Scapyから始めるリズムに合わせて1

    GeventとMultiprocessingは置いておいて、
    Scapyで必要なときに使おうかと思います。

    大雑把ですが、とりあえずプロトコルを作るモジュールから見ていこうと思います。
    結構挫折しそうな話題ですが、頑張っていきます。

    例となるプロトコルを選んでみましょう。
    有名なプロトコルがいいですね。

    最初ですし、WHAT WHY HOW の3つ書きたいと思います。

    WHAT

    Scapyは簡易にネットワークのパケットを生成できるツールです。
    これを使って、パケットを生成したいと思っています。

    WHY

    なぜかというと、制御システム系のプロトコルを実装されてないからです。
    だから、自分でできるようになれれば、制御系に収まらず、
    新しく出来たプロトコルにも対応できるんじゃないかって思ったかからです。

    HOW

    正直、やるぞっていういきおいで、まだちゃんとどうしたらいいかわかってないので
    師匠に相談しながら頑張っていこうかと思っています。

    Geventの良さ2

    これはメモです

    from multiprocessing import Pool
    
    def f(x):
        return x*x
    
    if __name__ == '__main__':
        with Pool(processes=4) as pool:         # start 4 worker processes
            result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
            print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow
    
            print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"
    
            it = pool.imap(f, range(10))
            print(next(it))                     # prints "0"
            print(next(it))                     # prints "1"
            print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow
    
            import time
            result = pool.apply_async(time.sleep, (10,))
            print(result.get(timeout=1))        # raises TimeoutError
    

    正直、asyncとかいう単語だけでも興奮しますね。
    このソースからでもmapとimapの違いわかりますね。

    map_unordered()の説明がいまいち理解出来ませんでしたが、


    class threading.Lock

    プリミティブロック (primitive lock) オブジェクトを実装しているクラスです。スレッドが一度ロックを獲得すると、それ以後のロック獲得の試みはロックが解放されるまでブロックします。どのスレッドでもロックを解放できます。

    バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。

    acquire(blocking=True, timeout=-1)

    ブロックあり、またはブロックなしでロックを獲得します。

    引数 blocking を True (デフォルト) に設定して呼び出した場合、ロックがアンロック状態になるまでブロックします。そしてそれをロック状態にしてから True を返します。

    引数 blocking の値を False にして呼び出すとブロックしません。 blocking を True にして呼び出した場合にブロックするような状況では、直ちに False を返します。それ以外の場合には、ロックをロック状態にして True を返します。

    正の値に設定された浮動小数点の timeout 引数とともに起動された場合、ロックを得られなければ最大で timeout によって指定された秒数だけブロックします。timeout 引数の -1 は無制限の待機を指定します。blocking が false の場合に timeout を指定することは禁止されています。

    ロックを獲得すると True を、ロックを獲得できなかったとき (例えば timeout が過ぎた場合) には False を返します。

    バージョン 3.2 で変更: 新しい timeout 引数

    バージョン 3.2 で変更: POSIX ではロックの取得がシグナルに割り込まれるようになりました。

    release()

    ロックを解放します。これはロックを獲得したスレッドだけでなく、任意のスレッドから呼ぶことができます。

    ロックの状態がロックのとき、状態をアンロックにリセットして処理を戻します。他のスレッドがロックがアンロック状態になるのを待ってブロックしている場合、ただ一つのスレッドだけが処理を継続できるようにします。

    アンロック状態のロックに対して起動された場合、 RuntimeError が送出されます。

    戻り値はありません。




    geventに

    from gevent.event import AsyncResult
    
    a = AsyncResult()
    ...
    a.set()
    ...
    a.get()
    

    と書いてて、なんだろうと調べてみました。

    すると、threading.Eventに書いてました。
    うん、セマフォと何が違うねん。っていうのが第一印象です。
    ちなみに、推測ですが、 getがclearと同じ挙動してると思います。

    Event オブジェクトの拡張の AsyncResult を使うと、モーニングコール (wakeup call) 付きの値を送ることができます。 これは将来どこかのタイミングで設定される値に対する参照を持っているので、 future とか deferred と呼ばれることもあります。
    

    って書いてありますが、意味がわかりません。

    import gevent
    from gevent.event import AsyncResult
    
    a = AsyncResult()
    
    def setter():
        
    	print("1")
    
    	gevent.sleep(3)
        
    	print("2")
        
    	a.set()
        
    	print("3")
    
    def waiter():
        """
        After 3 seconds the get call will unblock.
        """
        print("4")
        a.get() # blocking
        print("5")
        print 'I live!'
    
    gevent.joinall([
        gevent.spawn(setter),
        gevent.spawn(waiter),
    ])
    

    実行結果

    1
    4
    2
    3
    5
    I live!
    

    テストみました.

    すると,
    1
    4
    ここで、3秒間待ちます。
    2
    3
    5となります.
    要は、get()が呼ばれてから3秒待つという感じですね。

    そのあとに
    2
    3
    が出力されるのは分かるんですが、
    なんで 5 も出力されるんだろう?

    a.setされてるととかんがえるより、
    a.getでブロックが起こってるって考えるほうが無難なイメージです。

    import gevent
    from gevent.event import AsyncResult
    
    a = AsyncResult()
    
    def setter():
        
    	print("1")
    
    	gevent.sleep(1)
        
    	print("2")
        
        
    	print("3")
    
    def waiter():
    	print "4"
    	print "5"
    	a.get()
    	print "6"
    	print "I live"
    
    gevent.joinall([
        gevent.spawn(setter),
        gevent.spawn(waiter),
    ])
    


    テスト用に
    書いてみたら、

    1
    4
    5
    2
    3
    Traceback (most recent call last):
      File "07-2.py", line 26, in <module>
        gevent.spawn(waiter),
      File "/usr/local/lib/python2.7/dist-packages/gevent-1.0-py2.7-linux-i686.egg/gevent/greenlet.py", line 400, in joinall
        wait(greenlets, timeout=timeout)
      File "/usr/local/lib/python2.7/dist-packages/gevent-1.0-py2.7-linux-i686.egg/gevent/hub.py", line 645, in wait
        return list(iwait(objects, timeout))
      File "/usr/local/lib/python2.7/dist-packages/gevent-1.0-py2.7-linux-i686.egg/gevent/hub.py", line 598, in iwait
        item = waiter.get()
      File "/usr/local/lib/python2.7/dist-packages/gevent-1.0-py2.7-linux-i686.egg/gevent/hub.py", line 568, in get
        return self.hub.switch()
      File "/usr/local/lib/python2.7/dist-packages/gevent-1.0-py2.7-linux-i686.egg/gevent/hub
    .py", line 331, in switch
        return greenlet.switch(self)
    gevent.hub.LoopExit: This operation would block forever
    

    案の定エラーが起きました。

    並列っていうなら、gevent.sleep(5)とかしてる最中に違うプロセスでひたすらprintとか出来るんだろうか?

    Eventフラグの初期値って Falseですよね?
    だったら、その地点でブロッキングされてるんじゃないんですか?

    あとで、師匠に聞こう…

    今回は、Geventとmultiprocessingの似たような、似てないような
    クラスの困惑に詰みました。
    昨日も言いましたが、そろそろScapyに入りたい。


    ##追記##

    師匠の返事

    1.

    > multiprocessingは動かしてるコアの数を言っているんですかね?
    > で、geventの方は非同期のプロセスワーカの数を言ってるんですかね?

    これはイメージ的にはだいたいOKですが、厳密にはmultiprocessingの方が少し違います。
    マルチコアというのはHWです、CPUがコアを複数持っているってことですね。だから厳密にいうとmultiprocessingは動かす「プロセス」の数、geventの方はワーカ(greeenlet, コルーチン)ですね。
    プロセスとコアの関係は、以下のような感じです。
    OSがコア(CPU)にプロセスを割り当てる(プロセスにCPUを使わせる)んです。これがOSのスケジューリングですね。

    参考サイト

    2.

    >map() 組み込み関数の並列版です (iterable な引数を1つだけサポートするという違いはありますが)。結果が出るまでブロックします。
    >って書いてあるじゃないですか?
    >並列なのにブロックしてたら遅いというか、個人的には矛盾を感じるんですけど。
    Pool()

    ここでブロックするのは親プロセスですね、複数の子プロセスを作って子どもの仕事が終わるのを待つ(ブロックする)ってことです。
    普通のmapは一つのプロセスだけが仕事をしますが、multiprocessingのmapは複数の子プロセスを作って並列で仕事をさせるので高速になるという仕組みです。
    残りはまたちょっと後でー

    3.

    > これの不思議なのが、
    > multiprocessingがなんで、
    > [1,2,3,4,5...]とならないかっていうことなんですが、
    > そもそもなんでなんですか?

    ここのポイントはさっき言ったようにプロセスのスケジューリングをするのはOSだというところです。multiprocessingはプロセスを10こ作ってそれぞれにecho()を実行させますが、どのプロセスが実行されるか(CPUが割り当てられるか)はOSが決めます。
    その順番はいつも決まった順にはならないので[1,2,3,4,5,...]と順番にはならないということです。

    4.

    > p = Pool(10)で
    > コアを増やして10個分にタスクを分けるんですよね?
    >けど、greenletはコアは増えない
    > っていうその違いだけで、なんでこんなことがおこるんですか?

    greenletは1プロセスだからいつも同じ順ということですが、もう少し言うとgreenletがいつも同じ順になるように作られている(決定論的に動作する)からです。
    チュートリアルのとこに書いてある以下です。

      • -

    先に触れたように、 greenlet は決定論的に動作します。 同じように設定した greenlets があって、同じ入力が与えられた場合、 必ず同じ結果になります。例として、タスクを multiprocessing の pool に 与えた場合と gevent pool に与えた場合を比較します。

    例えばmultiprocessingでもEventとかの同期プリミティブを使うと[1,2,3,4,5...]となるようにもできます。
    ↓こんな感じに使います。
    参考サイト
    これだとプロセス間で同期を取っているので必ず[1,2,3,4,5...]となります。

    5.

    > それからそれををロック(acquire)すると、
    > Pool(10)で、10個ぐらい動かしていても、すべて止まってしまうんですか?

    みんなでロックを獲得しようとすると、一人以外はみんな待たされますね。
    lockは、複数人で同時に実行されると困る処理があったときに、必ず一人ずつに実行させたいときに使います。

    > ロックって同期的な処理ですよね?

    そうですね。
    でも同期的な処理というよりは、(複数のワーカー/プロセスで)同期を取るための手段ですね。


    > multiprocessingとかgeventのPoolは非同期ですよね?

    はい、そうですね。

    以上です

    Geventの良さ

    ここによく出てくるEvent Loop...

    Event LooPってなんだ?

    はい、イメージで言うとselectで待つこと。

    例えば、
    同期的な受信処理を書くと…

    sock = socket()
    sock.recv() #ここでデータが来るのを待つ
    


    これだと、一つのプロセスはデータが来るのを待ち続けることになる。

    ゆえに、非同期的にデータをselectで待ちます。

    すると

    sock = socket()
    select([sock],[],[])
    

    という感じになります。

    ちなみに、select関数はこのようになっております。

    FUNCTIONS
        select(rlist, wlist, xlist, timeout=None)


    Greenletというのは非同期の考え方をより抽象的にしたもので、
    ひとつのプロセスで複数のコンテキストを扱えるようになります。
    「2つ以上違うプロセスを同時で動かす」というイメージを持っています。

    gevent.spawnはバックグラウンドで別のプロセスを動かすというイメージです。

    geventが優秀なのは、自分でコンテキストスイッチを制御できるということです。

    通常はOSが制御するもんですね。

    コンテキストスイッチ (context switch)

    とは、複数のプロセスが1つのCPUを共有できるように、CPUの状態(コンテキスト)を保存したり復元したりする過程のことである。 from Wiki

    あと、感動的なのが
    select関数だとロックしてしまうところ、
    geventはその間別のgreenletが動かせるということになります。

    #!/usr/bin/python
    
    import gevent,random,time
    
    start = time.time()
    middle = 0
    
    def task(pid):
    	gevent.sleep(random.randint(0,2))
    	print("Task",pid,"End")
    
    def syn():
    	global middle
    	for i in xrange(10):
    		task(i)
    	middle = time.time() - start
    	print(middle)
    
    
    def asyn():
    	global middle
    	threads = [gevent.spawn(task,i) for i in xrange(0,10)]
    	gevent.joinall(threads)
    	end = time.time() - middle - start
    	print(end)
    
    if __name__ == '__main__':
    
    	print("1:")
    	syn()
    	print("2:")
    	asyn()
    
    
    

    実行結果

    1:
    ('Task', 0, 'End')
    ('Task', 1, 'End')
    ('Task', 2, 'End')
    ('Task', 3, 'End')
    ('Task', 4, 'End')
    ('Task', 5, 'End')
    ('Task', 6, 'End')
    ('Task', 7, 'End')
    ('Task', 8, 'End')
    ('Task', 9, 'End')
    10.011341095
    2:
    ('Task', 0, 'End')
    ('Task', 3, 'End')
    ('Task', 5, 'End')
    ('Task', 6, 'End')
    ('Task', 8, 'End')
    ('Task', 7, 'End')
    ('Task', 1, 'End')
    ('Task', 2, 'End')
    ('Task', 4, 'End')
    ('Task', 9, 'End')
    2.0019159317


    公式サイトからパクってきて、自分で少し書き換えました。
    非常に感動的ですね。
    synとasynで約8秒差もあります。

    もっと気になったことを師匠に聞いてみました。

    f:id:reonreon3reon:20140326043539p:plain

    「一番上が親プロセスで、中央の2つが(マルチ)コアで、下段がgevent ライクの
    マルチプロセス。これだと、相当効率よく処理ができるんじゃないかと」
    聞いてみたところ、難しいと答えられました。

    「複数のCPUコアを使いたいなら、それはOSの複数プロセスを使わないといけなくて、その場合multiprocessingを使います
    そうですね、それはできると思います(結構複雑になりますが)
    geventはmultiprocessingと合わせて使うことを意図されていないと思うので、データの受け渡しや同期の取り方が難しいってことです」

    とのことです。

    その他に

    このプログラムの重要な部分は、与えられた関数を greenlet スレッドの中に ラップする gevent.spawn です。 生成された greenlet のリストが threads 配列に格納され、 gevent.joinall 関数に渡されます。この関数は今のプログラムを、与えられた すべての greenlet を実行するためにブロックします。 すべての greenlet が終了した時に次のステップが実行されます。

    と書いてありますが、少し表現が難しいですね。



    仮にもできるんだから、やってみたいですね。
    何故やりたいか。それは、Scapyのようなstrを生成するのに時間がかかるプロセスを
    効率よく分担させたいからです。

    いっそうのこと、gevent勉強して、自分でTCPプロトコルスタック書いた方がいいんじゃないか
    という気持ちにもかられますが、やっぱり男はファンタジスタです。

    夢をもって、Scapyを追いかけたいと思います。

    明日ぐらいにはScapyのクラス継承を楽しみたいなと思っております。

    もし、geventに興味持ったら、公式サイト閲覧することを勧めます.

    筑波大学

    日記

    昨日2014/03/19、筑波大学に見学に行ってきました。
    まず、バスに乗って東京駅から筑波センター?まで行くはずが
    広すぎて、全くどこで止まっていいかわからず、迷子?
    筑波大学を案内してくださった方と合流出来て、
    筑波大学の色んな所を案内してくださいました。
    最初が、図書館です。図書館の蔵書の量が段違いすぎて、
    本を探すのにスゴイ時間がかかってしまいました。
    それから驚いたのが、図書館の一階にスタバがついてたことです。

    ドヤ = スタバ & Mac Air & ダークチョコチップクリームフラペチーノ in 筑波
    とかかっこよすぎ!って感じ。


    次に案内してくださった方の研究所を見させてもらいました。
    まず驚いたのが一人ひとりに高スペックのパソコンがあったこと。
    研究室に冷蔵庫があること。です。
    彼自身はあまり研究していませんでしたが、大体どういうことを
    している研究室かわかって、ずっと「すげぇなすげぇな」って
    言ってました。ファンタもおごってくれました。


    昼飯の時間が来たので、食堂に行ったら、「お母さんカレー」があったので
    それをチョイスしました。クソ普通のカレーに、嫌いなピーマンと、嫌いなトマトと
    カレーのルーの量に比べて明らかに多いやろ…っていうぐらいのご飯が入ってるものでした。
    非常に思い出になりました。


    最後に、筑波生の寮を見させてもらいました。
    「あっ15kにしては綺麗ですね」っていう寮もあれば、
    「廃墟かよ」っていう砂平寮wもありました。
    砂平寮(爆)には住みたくないなと思いました。

    収穫

    昨日の(筑波で)収穫としてなにより大きかったのが、
    案内してくださった方がベンチャーに詳しくて、
    それの話を聞けたことです。
    いつも感化されるんですが、昨日ずっと「起業してぇな起業」
    って思ってました。
    横のつながりのおかげで、縦のつながりも出来たことに感謝しています。
    昨日お世話になった方々ありがとうございました。

    最後に

    案内してくださった方が他中の先輩の毛戸さん(音信不通)にそっくりで、
    初めて会ったとき、「毛戸さん…?」ってなりました。

    PySideで何を作る3

    #!/usr/bin/python
    
    import sys
    from PySide.QtGui import *
    
    class SampleWin(QWidget):
      
      def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("Icon2")
        self.setGeometry(300,300,300,300)
        QToolTip.setFont(QFont("Decorative",8,QFont.Bold))
        self.setToolTip("Our Main Window")
    
    
      def setIcon(self):
        myIcon1 = QIcon('py.png')
        myLabel1 = QLabel('sample',self)
        pixmap1 = myIcon1.pixmap(50,50,QIcon.Active,QIcon.On)
        myLabel1.setPixmap(pixmap1)
        myLabel1.setToolTip("Active Icon")
    
        myIcon2 = QIcon('py.png')
        myLabel2 = QLabel('sample',self)
        pixmap2 = myIcon2.pixmap(50,50,QIcon.Disabled,QIcon.Off)
        myLabel2.setPixmap(pixmap2)
        myLabel2.move(50,0)
        myLabel2.setToolTip("Disabled Icon")
    
        myIcon3 = QIcon('py.png')
        myLabel3 = QLabel('sample',self)
        pixmap3 = myIcon3.pixmap(50,50,QIcon.Selected,QIcon.On)
        myLabel3.setPixmap(pixmap3)
        myLabel3.move(100,0)
    
    if __name__ == '__main__':
    
      try:
        myApp = QApplication(sys.argv)
        myWindow = SampleWin()
        myWindow.setIcon()
        myWindow.show()
        myApp.exec_()
        sys.exit(0)
    
      except NameError:
        print(sys.exc_info()[1])
      except SystemExit:
        print("Closing Window")
      except Exception:
        print(sys.exc_info()[1])
    

    Tooltipについてでした。はい。カーソルを合わせると説明が出てくると。


    f:id:reonreon3reon:20140317183535p:plain

    PySideで何を作る2

    #!/usr/bin/python
    
    import sys
    from PySide.QtGui import QApplication,QIcon,QWidget,QLabel
    
    class SampleWin(QWidget):
      
      def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("Icon2")
        self.setGeometry(300,300,300,300)
    
      def setIcon(self):
        myIcon1 = QIcon('py.png')
        myLabel1 = QLabel('sample',self)
        pixmap1 = myIcon1.pixmap(50,50,QIcon.Active,QIcon.On)
        myLabel1.setPixmap(pixmap1)
    
        myIcon2 = QIcon('py.png')
        myLabel2 = QLabel('sample',self)
        pixmap2 = myIcon2.pixmap(50,50,QIcon.Active,QIcon.Off)
        myLabel2.setPixmap(pixmap2)
    
        myIcon3 = QIcon('py.png')
        myLabel3 = QLabel('sample',self)
        pixmap3 = myIcon3.pixmap(50,50,QIcon.Active,QIcon.On)
        myLabel3.setPixmap(pixmap3)
        myLabel3.move(100,0)
    
    if __name__ == '__main__':
    
      try:
        myApp = QApplication(sys.argv)
        myWindow = SampleWin()
        myWindow.setIcon()
        myWindow.show()
        myApp.exec_()
        sys.exit(0)
    
      except NameError:
        print(sys.exc_info()[1])
      except SystemExit:
        print("Closing Window")
      except Exception:
        print(sys.exc_info()[1])
    

    f:id:reonreon3reon:20140317181935p:plain

    的な?

    QIcon.Active

    Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

    QIcon.Off

    Display the pixmap when the widget is in an "off" state

    QIcon.On

    Display the pixmap when the widget is in an "on" state

    pixmap func

    The syntax of the pixmap function isPySide.QtGui.QIcon.pixmap(width, height[, mode=Normal[, state=Off]]). The parameters width and height represents the icon size. The modes can be any of the following four modes depending on the action:

    PySideで何を作る

    Life is Tech!(流山市編)までにアプリ作れるようになっておかないといけないのに
    なにもできない、Unityも動かなくなったし ←これまじ辛い
    あと、Pygameはゲーム専門なので、使えそうにない
    だから、PySideで再挑戦。

    import sys
    import time
    from PySide.QtGui import QWidget,QApplication
    
    
    class Sample_Win(QWidget):
      """Main Window"""
    
      def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("THe First Program")
        self.setGeometry(400,400,400,400)
        self.setMinimumHeight(100)
        self.setMinimumWidth(250)
        self.setMaximumHeight(200)
        self.setMaximumWidth(800)
    
    if __name__ == '__main__':
    
      try:
        myApp = QApplication(sys.argv)
        myWindow = Sample_Win()
        myWindow.show()
        print("A") 
    #resize the window
        
        time.sleep(2)
        myApp.exec_()
        
        myApp = QApplication(sys.argv)
        myWindow = Sample_Win()
        myWindow.show()
        myWindow.resize(200,200)
        myWindow.setWindowTitle("THE THIRD Prog")
        myWindow.repaint()
        print("C") 
        
        sys.exit(0)
    
      except NameError:
        print("Name Error: {0}".format(sys.exc_info()[1]))
      except SystemExit:
        print("Closing Window...")
      except Exception:
        print("{0}".format(sys.exc_info()[1]))
    

    これが、Window開くやつ.

    import sys
    import time
    from PySide.QtGui import QWidget,QApplication
    

    これがモジュール

    class Sample_Win(QWidget):
      """Main Window"""
    
      def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("THe First Program")
        self.setGeometry(400,400,400,400)
        self.setMinimumHeight(100)
        self.setMinimumWidth(250)
        self.setMaximumHeight(200)
        self.setMaximumWidth(800)
    

    QWidgetっていうのが、
    The widget is the center of the user interface. It receives the user inputs from mouse, keyboard, and other events, of the window system, and paints a representation of itself on the screen.


    if __name__ == '__main__':
    
      try:
        myApp = QApplication(sys.argv)
        myWindow = Sample_Win()
        myWindow.show()
        print("A") 
    #resize the window
        
        time.sleep(2)
        myApp.exec_()
        
        myApp = QApplication(sys.argv)
        myWindow = Sample_Win()
        myWindow.show()
        myWindow.resize(200,200)
        myWindow.setWindowTitle("THE THIRD Prog")
        myWindow.repaint()
        print("C") 
        
        sys.exit(0)
    
    

    ちなみにこれ、Linuxだと、2個出てこない。
    On executing the program, you will be shown a window as shown in the following image. This window will get resized after 3 seconds. Also, try to resize the window by dragging its corners. You may notice that the window cannot be shrunk or expanded beyond the minimum and maximum metrics set in our earlier code. You might not initially see a window when executing this program on an XWindow based system such as Linux, because the main application loop has not been called yet, so none of the objects has been really constructed and buffered out to the underlying XWindow system.

    が理由.

      try
      ...
      except NameError:
        print("Name Error: {0}".format(sys.exc_info()[1]))
      except SystemExit:
        print("Closing Window...")
      except Exception:
        print("{0}".format(sys.exc_info()[1]))
    

    のNameError知らん。
    SystemExitはCtrl+cでプロセスを終了させたときに "Closing Window "
    って出力される
    最後も知らん。