blog を書くということ

このブログは2006年の7/30に開始したようです。

WordPressへ | cocoa*life

それ以前は他のところで書いていたと思いますが isweb だったかな?忘れちゃったけど。こちらに移ってきたのでした。

ちょっと前にこのサーバに使っているさくらインターネットから、更新のお知らせが来て、1年間で5,000円の請求が来ました。

このときちょっと迷いました。最近書いていないし、年間5,000円というのは今の自分には決して軽い金額ではないと。でも続けることにしました。

話は飛びますが、友達と昨日話していたときに、昔、ねじまき鳥クロニクルを読んで自分を救わなければならないと思い、そこから人生が少しずつ変わっていったという話をしました。

ねじまき鳥クロニクルのどこかに、そのような自分を救うことが書いてあったかなと思い、調べてみたところ、自分のこの blog がヒットするだけでした。

人生のパスを変える | cocoa*life

懐かしいなと思いつつも、他の部分を読み返してみたところ、当時の自分はこんなことを考えていたのかとちょっと新鮮で、驚きでした。
読み返してみると、当時の自分が何をしようとしていたのかよくわかります。本を読み、いろいろと客観視をしようとしていたこと。それをさらに文章にすることが手助けしてくれる。そうして自分の内面と闘っていたということがよくわかりました。

このように思考の変遷が残っているというのは自分にとってはとても大事なことなのではないかと感じました。日常生活ではどうしても見返すことが少なくなり、多くの大切なことを忘れてしまいます。

こんなことを考えていたら、また blog を書こうと思いました。ただし、内面を書くことがある程度ありそうなので、ここに書くかどうかは迷っています。

2013年に寄せて

明けましておめでとうございます。
本当にあっという間に1年が経ってしまうと危機感ばかり募ります。

昨年を少し振り返ってみると、激動だった様な気もするのですが、一方で、3年前と比べたら本当にたいしたことはないなぁとも感じます。

嬉しいことに、年末ぐらいから、いろいろと考え続けてきたことに対して少し答えが出てきたような感触があります。

6月ぐらいにとある方に、今までいろんなことに挑戦したみたいだけれど、それはほとんどが劣等感によるものからだよねという指摘をいただいてから、その言葉がずっといい意味で引っかかっていました。別の方からもなにか苦しそうに見えたという意見をもらっていたので、指摘をいただいた時すぐに、劣等感からだったということは腑に落ちたものの、では果たしてそれに変わるエネルギー源はあるのか?ということがずっとわかりませんでした。自分が求めていたものはコミットメントのためのエネルギー源でした。

それが12月のある晩、ふと心の中に成長したいという漠然とした、でもそれがなぜなのかまったくわからない気持ちというのかエネルギーの状態で浮き上がってきました。少し考えてもこの理由はわからなかったので、いつも自分がするように無意識を信頼し任せ、放っておくことにしました。その翌日、親友が読みたいと言っていたので自分も読もうと思いたまたま手に取った、伊賀泰代さんの「採用基準」を読んだ後、自分の中でその理由も解けたような気がしました。

この本のタイトルは、採用基準で、そのまま読むとマッキンゼーの採用基準となります。その基準は「リーダーシップ能力」、「地頭の良さ」「英語力」という3つの要素であって、中でも一番求められるものはリーダーシップの能力であるということで、ほとんどが日本人にはあまりなじみのないリーダーシップ能力について書かれています。

採用基準

採用基準
著者: 伊賀泰代
ページ数: 248ページ
出版社: ダイヤモンド社
発売日: 2012年11月8日

この本の最後に、リーダーシップ能力を磨けば磨くほど、より大きな問題を解決していけるようになるということが書かれています。自分にとってのポイントはここでした。先ほどのなぜ成長したいかと思ったかの自分としての答えは、あまりに無邪気すぎる答えなのかもしれませんが、成長すればするほど、多くの人を倖せにできる可能性が増えるかもしれないということでした。でも、この答えにたどり着いたときに、ああ自分の一人だけのためではないんだと、なにか安心することができました。

前置きが長くなりました。

2013年に寄せてとタイトルを書きました。成長するというのは、おそらく生きていて、意識がある限り、永遠のテーマになるのだと思いますが、それでも今年はいくつかの点で、目に見える形で成長したと実感できる年にしたい。そのためにはまず時間の使い方を根本から変えていかなければならないわけですが、たぶんいきなりいっぺんにやろうとすると、失敗します。ので、まずは上に書いた多くの人を倖せにできる可能性が増えるということを何度も意識するということから始めたいと考えています。

そのようなわけで、自分の中ではいつもとちょっと違う年明けのような気がしています。これからもよろしくお願いいたします。

Fade-in animation at UIView’s drawRect

Although UIView’s animateWithDuration:animations: method is quite useful, if you want a view to animate a drawing code written in drawRect method, you can’t use this method.

CABasicAnimation class is suitable for solving this problem like this.

- (void)drawRect:(CGRect)rect
{
    CABasicAnimation *animation;

    animation = [CABasicAnimation animation];
    [animation setDuration:0.5];

    [[self layer] addAnimation:animation
                        forKey:@"contents"];

    // drawing code
}

Reference

nginx Upload Progress Module with MacPorts

I needed use nginx Upload Progress Module to create a progress bar.

HttpUploadProgressModule

In local development, I use MacPorts to install nginx, but MacPorts does not have variant for that module.
So, I edited Portfile which is suitable for it.

I uploaded it to Gist.

Then, I installed nginx with the following command.

$ sudo port install nginx +ssl +uplaod_progress

You can see “–add-module” directive in this command, if the module is installed properly.

$ nginx -V

Upgrading VMWare vSphere Hypervisor (ESXi) 4.1 to 4.1 Update 1 through SSH

I upgraded VMWare vSphere Hypervisor (ESXi) 4.1 to 4.1 Update 1 through ssh, and here’s the way.

First, you must enable SSH by the console or vSphere Client. The following web page shows the detail process for it, but I have not set up the non-root user yet.

ESXi (ESX 4i) Enable SSH

After that, you can login as root user (if you’ve set up non-root user, use it).

$ ssh root@esxi-server-ip

To enter the maintenance mode, shutdown all virtual machines. I don’t know the way of shutting down all at once, and execute the command many times.

# vim-cmd vmsvc/power.shutdown <vmid>

You can use this command in order to know the vmid.

# vim-cmd vmsvc/getallvms

Enter the maintenance mode.

# vim-cmd hostsvc/maintenance_mode_enter

Download the update file (update-from-esxi4.1-4.1_update01.zip), and send it by SCP. Since ESXi server, however, doesn’t have ‘unzip’ program, I unzipped the files on my Mac and send the directory.

$ scp -r update-from-esxi4 root@esxi-server-ip:/vmfs/volumes/Your-Data-Storage-Name

You can check the data storage name by the command `ls /vmfs/volumes/`.

The preparation step is done, and go!

# cd /vmfs/volumes/Your-Data-Storage-Name/update-from-esxi4
# esxupdate update -m metadata.zip

After updated, you must exit maintenance mode and reboot the machine.

# vim-cmd hostsvc/maintenance_mode_exit
# reboot

Finally, you can check the current version of Hypervisor by the following command.

# vmware -v
VMware ESXi 4.1.0 build-348481

References

How to use Xcode 3 color themes in Xcode 4

I’m using either MyBlackboard (In Japanese) or Railscasts color themes in Xcode 3, these color themes, however, couldn’t be used in Xcode 4.

I want to convert 3’s xccolortheme files into 4’s dvtcolortheme files, and found the just script which converted it.
mrevilme’s gist: 488120 — Gist

The usage of this tiny python script is very simple like the following command.

$ xcode3_theme_to_xcode4.py MyBlackBoard.xcolortheme

This step is very quick, and finally, I moved the dvtcolortheme file to the directory.

mkdir -p ~/Library/Developer/Xcode/UserData/FontAndColorThemes/
mv MyBlackBoard.dvtcolortheme ~/Library/Developer/Xcode/UserData/FontAndColorThemes/

If you’ve already started Xcode, restart it and you’ll find the theme at the preference of Xcode.

References

Plantronics Discovery 975 Bluetooth Headset の Tips

Plantronics Discovery 975 Bluetooth Headset という Bluetooth で使うヘッドセットを購入しました。
Plantronics Discovery 975 Bluetooth Headset

微妙にいくつかの点ではまったので、備忘録を残しておくことにします。

  • 2010年のマニュアルは一部情報が削除されている。MyHeadset.jp | Bluetooth イヤーピース Discovery 975で見られるマニュアルを参照する。
  • デフォルトではオフになっているマルチポイント接続機能をオンにしないと2台で使えない。
  • ペアリングは電源を切ってから。コントロールボタンを長押しすれば、赤白に点滅してペアリングモードに入れる。
  • Amazon.com で購入した方が安い。

ヘッドセットを購入したのはこれが初めてですが、普通のイヤホンであれば落ちてしまう自分の耳からも落ちずにクリアな音で使えるのがとてもいいと思いました。

参考文献

How to create OAuth / xAuth Service Provider in Ruby on Rails with devise

At previous entiry I wrote a sample how to support xAuth in Ruby Application.

In this entry, I write how to create the OAuth/xAuth Service Provider in Ruby on Rails project which uses devise plugin for authentication.

OAuth support when you use devise plugin

Installation

First of all, I’m about to write the way of supporting OAuth using OAuth plugin.
pelle/oauth-plugin – GitHub

OAuth plugin supports Rails 3 after version 0.4.0.pre1, and add Gemfile the following line.

gem "oauth-plugin", ">=0.4.0.pre1"

The installation tutorials are written in the github plugin page.

devise plugin support

In addition, to use OAuth plugin in the project which utilize devise, you need to support two methods “login_required” and “logged_in?” Devise uses such helper methods as “authenticate_#{model_name}” and “#{model_name}_signed_in?”, I wrote two helper methods.

[lib/lindoc/oauth_helpers.rb]

module Lindoc
  module OauthHelpers
    def self.included(recipient)
      recipient.extend(ClassMethods)
      recipient.class_eval do
        include InstanceMethods
      end
    end

    module InstanceMethods
      def login_required
        authenticate_user!
      end

      def logged_in?
        user_signed_in?
      end
    end
  end
end

At the controllers associated with OAuth, add this helper methods like the this.

[$RAILS_ROOT/app/oauth_clients_controller.rb]

class OauthClientsController < ApplicationController
  include Lindoc::OauthHelpers
  ...
end

[$RAILS_ROOT/app/oauth_controller.rb]

require 'oauth/controllers/provider_controller'

class OauthController < ApplicationController
  include OAuth::Controllers::ProviderController
  include Lindoc::OauthHelpers
  ...
end

Since I want to use OAuth / xAuth authentication at API of our service, also added :oauth_required filter.

[app/controllers/api/v1/api_controller.rb]

class Api::V1::ApiController < ApplicationController
  include Lindoc::OauthHelpers

  before_filter :oauth_required
  ...
end

Rails nested parameters support

Client applications often post data in nested parameters like “foo[bar]=baz” to Rails application, but OAuth plugin doesn’t currently support this type of parameters. The reason why OAuth plugin doesn’t, is that this plugin doesn’t consider this type when it calculates a signature the way of which is written in the specification of OAuth, and answers a bad/invalid signature. So, you need to add support by overriding the method which helps calculate it.

This solution is written at Issue page of OAuth plugin.
parameter normalisation issues Nesting parameters causes problems.

[config/initializers/oauth.rb]

module OAuth
  module Helper
    # see https://github.com/pelle/oauth/issues#issue/8
    def normalize(params)
      params.sort.map do |k, values|
        if values.is_a?(Array)
          # multiple values were provided for a single key
          values.sort.collect do |v|
            [escape(k),escape(v)] * "="
          end
        elsif values.is_a?(Hash)
          key = k
          values.sort.collect do |k, v|
            [escape("#{key}[#{k}]"),escape(v)] * "="
          end
        else
          [escape(k),escape(values)] * "="
        end
      end * "&"
    end
  end
end]

xAuth support

xAuth is the authentication method which is used in twitter to support desktop/mobile applications. If you want to know how to use xAuth in your applications, you should read this document.
Using xAuth | dev.twitter.com

client application restriction

Like twitter, I want to restrict client applications which can use xAuth authentication, and I add column to decide it.

[db/migrate/xxx_create_oauth_table.rb]

class CreateOauthTables < ActiveRecord::Migration
  def self.up
    create_table :client_applications do |t|
      ...
      t.boolean :xauth_enabled, :default => false

      t.timestamps
    end
    ...
  end
end

/oauth/access_token signature verification method change

In OAuth 1.0 specification, service provider must verify a signature which consists of both Authentication header and GET or POST parameters called “Signature Base String”, and signed by both Consumer Secret and Access Token Secret. This verification step is implemented as filter “two_legged” or “oauth10_request_token” in OAuth plugin, OAuth::Controllers::ProviderController.

[oauth-plugin/lib/oauth/controllers/provider_controller.rb]

module OAuth
  module Controllers
   
    module ProviderController
      def self.included(controller)
        controller.class_eval do
          ...
          oauthenticate :strategies => :two_legged, :interactive => false, :only => [:request_token]
          oauthenticate :strategies => :oauth10_request_token, :interactive => false, :only => [:access_token]
          ...

The simplified difference of these two methods is to use or not to use request token. You need to change signature verification method of /oauth/access_token when you request Access Token by xAuth, because unlike OAuth clients, xAuth clients don’t have request token.

For that reason, to support xAuth, if request has “x_auth_mode=client_auth” in POST parametes which indicate client applications want to authenticate by xAuth, “two_legged” filter should be applied. I used “alias_method_chain” to seperate xAuth and OAuth authentication.

[config/initializers/oauth.rb]

module OAuth
  module Controllers
    module ApplicationControllerMethods
      class Authenticator
        def oauth10_request_token_with_xauth
          if params[:x_auth_mode] == 'client_auth'
            # xAuth authentication
            two_legged
          else
            # OAuth authentication
            oauth10_request_token_without_xauth
          end
        end

        alias_method_chain :oauth10_request_token, :xauth
      end
    end
  end
end

/oauth/access_token user verification

In /oauth/access_token request, you also verify the user using his username and password. If there is a “x_auth_mode=client_auth” POST parameter in request, verify the user and response Access Token.

[$RAILS_ROOT/app/oauth_controller.rb]

require 'oauth/controllers/provider_controller'

class OauthController < ApplicationController
  include OAuth::Controllers::ProviderController
  include Lindoc::OauthHelpers
  ....

  private
  def access_token_with_xauth
    # To use custom failure response with devise, you need the following line.
    # see https://github.com/plataformatec/devise/wiki/How-To:-Provide-a-custom-failure-response-with-Warden
    warden.custom_failure!

    if params[:x_auth_mode] == 'client_auth'
      render_unauthorized = Proc.new do
        render :nothing => true, :status => 401
      end

      # We support screen name and email to login
      user = User.find_for_database_authentication({ :screen_name_or_email => params[:x_auth_username] })
      if user &&
        user.valid_password?(params[:x_auth_password]) &&
        current_client_application.xauth_enabled

        @token = AccessToken.where(:user_id.eq => user,
                                   :client_application_id.eq => current_client_application,
                                   :invalidated_at.eq => nil).limit(1).first
        @token = AccessToken.create(:user => user, :client_application => current_client_application) if @token.blank?

        if @token
          render :text => @token.to_query
        else
          render_unauthorized.call
        end
      else
        render_unauthorized.call
      end
    else
      access_token_without_xauth
    end
  end

  alias_method_chain :access_token, :xauth
end

References

How to support OAuth in ASIHTTPRequest

ASIHTTPRequest is a brilliant library, when you want to handle HTTP requests.
At this time, however, this library doesn’t support OAuth.

You can support it easily with OAuthCore library which is developed by atebits who is the developer of Tweetie a.k.a. Twitter for Mac/iPhone.
atebits / OAuthCore / overview – Bitbucket

A sample code is following.

#import "OAuthCore.h"

NSString * const CONSUMER_KEY = @"YOUR_CONSUMER_KEY";
NSString * const CONSUMER_SECRET = @"YOUR_CONSUMER_SECRET";
NSString * const ACCESS_TOKEN = @"YOUR_ACCESS_TOKEN";
NSString * const ACCESS_TOKEN_SECRET = @"YOUR_ACCESS_TOKEN_SECRET";

NSURL *URL = [NSURL URLWithString:@"http://example.com/api"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:URL];

[request setPostValue:@"test" forKey:@"test_value"];
[request buildPostBody];

NSString *header = OAuthorizationHeader([request url],
                                        [request requestMethod],
                                        [request postBody],
                                        CONSUMER_KEY,
                                        CONSUMER_SECRET,
                                        ACCESS_TOKEN,
                                        ACCESS_TOKEN_SECRET);


[request addRequestHeader:@"Authorization" value:header];

If you want to get “Access Token” and “Access Toke Secret”, such as you authorize with xAuth, you should set both ACCESS_TOKEN and ACCESS_TOKEN_SECRET, not nil but @””.

References