備忘録の最近のブログ記事

1、Frameworkを追加
#import <AssetsLibrary/AssetsLibrary.h>
#import <ImageIO/ImageIO.h>

2、サンプルコード
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {

    [picker dismissModalViewControllerAnimated:NO];

    // カメラロールからiPhoneカメラで撮った場合、GPSなど取得可能
    NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary *lib = [[[ALAssetsLibrary alloc] init] autorelease];
    NSLog(@">>>>>> %@", url);
   
    [lib assetForURL:url
        resultBlock:^(ALAsset *asset){
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            NSUInteger size = [representation size];
            uint8_t *buff = (uint8_t *)malloc(sizeof(uint8_t)*size);
            if(buff != nil){
                NSError *error = nil;
                NSUInteger bytesRead = [representation getBytes:buff fromOffset:0 length:size error:&error];
                if (bytesRead && !error) {
                    NSData *photo = [NSData dataWithBytesNoCopy:buff length:bytesRead freeWhenDone:YES];


                    CGImageSourceRef cgImage = CGImageSourceCreateWithData((CFDataRef)photo, nil);
                    NSMutableDictionary *imageMetadata = (NSMutableDictionary *)CGImageSourceCopyPropertiesAtIndex(cgImage, 0, nil);
                    if (imageMetadata) {
                        NSLog(@"%@", [imageMetadata description]);
                       // GPSはこんなかんじで取得
                        if ([imageMetadata valueForKey:@"{GPS}"]) {
                              CLLocationDegrees lat = (CLLocationDegrees)[[[imageMetadata objectForKey:@"{GPS}"] objectForKey:@"Latitude"] doubleValue];
                              CLLocationDegrees lng = (CLLocationDegrees)[[[imageMetadata objectForKey:@"{GPS}"] objectForKey:@"Longitude"] doubleValue];
                        }

                    } else {
                        NSLog(@"no metadata");
                    }
                    CFRelease(cgImage);
                }
                if (error) {
                    NSLog(@"error:%@", error);
                    [error release];
                    free(buff);
                }
            }
        }
        failureBlock:^(NSError *error){
                 NSLog(@"error:%@", error);
             }];

}
--- どこかで、---
queue = [[NSOperationQueue alloc] init];
---

ASIHTTPRequest で setDelegate:self をしていた場合、
かつqueueを利用する場合、
queueのオペレーションから requestを引っぱり、
queueをリリースする。
queue以下にdelegateがあるオブジェクトがあるときは、
末端までたどり、何らかの方法でキャンセルする。
queueは最小単位で使う方がよい。
元のオブジェクトをリリースしたらちゃんと末端も処理できるような感じで、
かつ、わかりやすくやならないと、いけないみたい。(反省、、、)
ベースのqueue管理を作るより、最小単位で組み込みその大本をリリースするが良さげ。


 if (queue) {
        for (ASIHTTPRequest *request in queue.operations) {
            [request clearDelegatesAndCancel];
        
        }
        [queue cancelAllOperations];
       // 例 [queue waitUntilAllOperationsAreFinished];
       // waitUntilAllOperationsAreFinished だと処理が終わるまで待つ。

        [queue release];
        queue = nil;
}

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];

ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];
[cache setStoragePath:[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ASIHTTPRequestCache"]];
[cache removeCachedDataForRequest:request];

これで行けた。
ASIDownloadCacheのremoveCachedDataForRequestを使う。
storagePathを指定してあげないと行けないようだったので上記のNSSearchで取得。
これは、ASIDownloadCache.mを眺めてたら分かった。



メモ
# self は tornado の HTTP Handler
import json
import bson.json_util

def dump(self, arg):
    self.set_header("Content-Type", "application/json")
    self.finish(string_dump(arg))

def dumps(self, obj, root='root'):
    self.set_header("Content-Type", "application/json")
    self.finish(string_dumps(obj, root))

def string_dump(arg):
    return json.dumps(arg, default=bson.json_util.default)
       
def string_dumps(obj, root='root'):
    lst = []
    for x in obj:
        lst.append(x)
    return string_dump({root:lst})



node.js  dato korega iranai na...
python dato server gawa no shoriga ooitoki ni rakunanokana.

iphone + opencv をmacへ

| コメント(0)
久々ブログ。
burtn風に写真がとれるようになったので、
撮った写真のエフェクト加工にはいります。

備忘録メモ、

参照サイト:
http://niw.at/articles/2009/03/14/using-opencv-on-iphone/ja
http://bassabsoft.blogspot.com/2010/03/opencv-with-iphone-2.html

もちろんxcodeも入れておきます。

$ sudo port selfupdate
checksumエラーは selfupdate を使う。
apt系のapt-get updateと同等。

cmake をインストール、
$ sudo port install cmake
しておく。

あとは、上記の参照サイトの手順で、
$ git clone git://github.com/niw/iphone_opencv_test.git
twitterではたらくniwaさんのgitからダウンロード
niwaさんのブログ git git://になっていますが、git cloneが正解です。
git も入れておく必要がある。

http://www.atinfinity.info/wiki/index.php?OpenCV%2FUsing%20OpenCV%202.2%20on%20iOS%20SDK%204.2

に ios sdk 4.2 + opencv-2.2.0のがあった。



記憶がだんだん、、、

(sudo tar vzcf - ./) | ssh user@domain.com "(cat > filename.tar.gz)"
mongosが安定してきたので一安心。

==
ディレクトリ作る(ec2の場合とりあえず、/mnt以下へ)
==

$ sudo mkdir /mnt/data/shards
$ sudo mkdir /mnt/data/shards/0 /mnt/data/shards/1 /mnt/data/shards/2
$ sudo mkdir /mnt/data/shards/config
$ sudo chown mongodb:mongodb -R /mnt/data/shards

==
mongosの設定
==

$ sudo -u mongodb -H mongo
> use admin
> db.runCommand( {addshard : "localhost:27020", allowLocal : true} );
> db.runCommand( {addshard : "localhost:27021", allowLocal : true} );
> db.runCommand( {addshard : "localhost:27022", allowLocal : true} );

# Listing shards
> db.runCommand( { listshards : 1 } );

#Enabling Sharding on a Database
> db.runCommand( { enablesharding : "dbname" } );

#Sharding a Collection
> db.runCommand( { shardcollection : "dbname.collection_name" , key : { "_id" : 1 } , unique : true } );

==
簡易スタートスクリプト
==

#!/bin/bash

sudo -u mongodb -H mongod \
--configsvr \
--dbpath /mnt/data/shards/config \
--fork \
--port 27019 \
--logpath /var/log/mongodb/mongodb.config.log  &

sleep 2

sudo mongos \
-vvv \
--port 27017 \
--fork \
--configdb localhost:27019 \
--logpath /var/log/mongodb/mongos.log  &

sleep 2

sudo -u mongodb -H mongod \
--shardsvr \
--port 27020 \
--fork \
--dbpath /mnt/data/shards/0 \
--logpath /var/log/mongodb/mongodb.shard.log &

sudo -u mongodb -H mongod \
--shardsvr \
--port 27021 \
--fork \
--dbpath /mnt/data/shards/1 \
--logpath /var/log/mongodb/mongodb.shard.log &

sudo -u mongodb -H mongod \
--shardsvr \
--port 27022 \
--fork \
--dbpath /mnt/data/shards/2 \
--logpath /var/log/mongodb/mongodb.shard.log  &

print '-------------------------------------'
ps -o pid,command ax | grep mongos | grep -v grep |cut -d' ' -f1
print '-------------------------------------'

ps -o pid,command ax | grep mongos | grep -v grep |cut -d' ' -f1 > /tmp/mongo.pid

久々に設定、

$ sudo apt-get install fetchmail

後、

$ vi $HOME/.fetchmailrc

==中身==

poll imap.gmail.com proto imap port 993
    user "アカウント名@gmail.com" password "パスワード"
    keep
    ssl
    mda "/usr/bin/procmail"

========

$ chmod 600 .fetchmailrc

そして、

$ sudo apt-get install procmail

後、

$ vi .procmailrc

==中身==

PATH=$HOME/bin:/usr/bin:/usr/local/bin
MAILDIR=$HOME/Maildir
DEFAULT=$MAILDIR/inbox/.
LOGFILE=$MAILDIR/procmail.log
LOCKFILE=$HOME/.lockmail

========

$ fetchmail -v

これで定期的にメールを取得して、メールを軸に何らかの処理可能。

2 servers results

Web Sever: Nginx 0.7* + Tornado 0.2
                   using nginx 5 load balancers
                  worker processes 5
                  worker connections 1024

DB Server: mongodb 1.5.1 shards

====
$ ab -n 10000 -c 25 http://****.***/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking ****.*** (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        TornadoServer/0.1
Server Hostname:        ****.***
Server Port:            80

Document Path:          /
Document Length:        4259 bytes

Concurrency Level:      25
Time taken for tests:   139.086 seconds
Complete requests:      10000
Failed requests:        1469
   (Connect: 0, Receive: 0, Length: 1469, Exceptions: 0)
Write errors:           0
Non-2xx responses:      1469
Total transferred:      38561669 bytes
HTML transferred:       36470146 bytes
Requests per second:    71.90 [#/sec] (mean)
Time per request:       347.716 [ms] (mean)
Time per request:       13.909 [ms] (mean, across all concurrent requests)
Transfer rate:          270.75 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      106  108  42.5    107    3106
Processing:   108  239 221.4    200    3539
Waiting:      108  239 221.3    200    3539
Total:        214  347 225.2    307    3646

Percentage of the requests served within a certain time (ms)
  50%    307
  66%    356
  75%    392
  80%    419
  90%    482
  95%    530
  98%    602
  99%    664
 100%   3646 (longest request)

==
mongodbが2回ほど、open fileを振り切って、connectionエラー、 ulimitをマックスまであげるが同じ。
なので、monitを使って、can not open fileになったら、サーバーリスタートで対応。
KeyRemap4MacBook インストール
system pref -> For Japanese -> Remap Space Key -> Shift+Space to KANNA/EISUU

command+spaceでの変換になれていないので、だいぶ楽になった。



このアーカイブについて

このページには、過去に書かれたブログ記事のうち備忘録カテゴリに属しているものが含まれています。

前のカテゴリはグルメです。

次のカテゴリは思うことです。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。