2015年4月7日火曜日

Function to define a namespace in JavaScript (namespace.js)

Sample Code:

// Define a namespace 'aaa.bbb.ccc' and add a function 'hello'
// under the namespace which prints 'Hello, world.'.
namespace('aaa.bbb.ccc').hello = function() {
    print('Hello, world.');
};

// Execute the function.
aaa.bbb.ccc.hello(); 


Source Code:

2015年3月21日土曜日

iBeacon as a kind of AD structures

First of all, iBeacon should be parsed as a kind of AD structures. Any library that is not implemented that way is just "usable" at best.

The AD structure format is described in "11 ADVERTISING AND SCAN RESPONSE DATA FORMAT" of "Bluetooth Core Specification 4.2". You can find the document at Specification Adopted Documents.

nv-bluetooth is a utility library written in Java and it contains ADPayloadParser class that parses a payload of an advertising packet (byte[]) and returns a list of AD structures (List<ADStructure>). With the library, an implementation of onLeScan method (of android.bluetooth.BluetoothAdapter.LeScanCallback interface) can be written like the following.


public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    // Parse the payload of the advertising packet.
    List<ADStructure> structures =
        ADPayloadParser.getInstance().parse(scanRecord);

    // For each AD structure contained in the advertising packet.
    for (ADStructure structure : structures)
    {
        if (structure instanceof IBeacon)
        {
            // An iBeacon packet was found.
            handleIBeacon((IBeacon)structure);
        }
        ........


ADPayloadParser class holds implementations of ADStructureBuilder interface and ADManufacturerSpecificBuilder interface. ADStructureBuilder interface has a method to build an instance of ADStructure from a byte array, and ADManufacturerSpecificBuilder interface has a method to build an instance of ADManufacturerSpecific from a byte array. As you guess, you can parse AD structures in special formats by registering implementations of these interfaces into ADPayloadParser.

nv-bluetooth supports some other AD structures in addition to iBeacon. Especially, ucode (ITU-T H.642) is supported. See README.md and JavaDoc of nv-bluetooth for details.




まず初めに、iBeacon は AD structure の一種としてパースすべきです。そのように実装されていないライブラリは、せいぜい「使える」程度に過ぎません。

AD structure のフォーマットは Bluetooth Core Specification 4.2 の 11 ADVERTISING AND SCAN RESPONSE DATA FORMAT に記載されています。この文書は Specification Adopted Documents にリストされています。

nv-bluetooth は Java で書かれたユーティリティーライブラリで、アドバータイジングパケットのペイロード (byte[]) をパースして AD structure のリスト (List<ADStructure>) を返す ADPayloadParser というクラスを含んでいます。このライブラリを使うと、(android.bluetooth.BluetoothAdapter.LeScanCallback インターフェースの) onLeScan メソッドの実装は次のように書くことができます。


public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    // アドバータイジングパケットのペイロードをパースする。
    List<ADStructure> structures =
        ADPayloadParser.getInstance().parse(scanRecord);

    // アドバータイジングパケットに含まれる各 AD structure ごとに
    for (ADStructure structure : structures)
    {
        if (structure instanceof IBeacon)
        {
            // iBeacon パケット発見。
            handleIBeacon((IBeacon)structure);
        }
        ........


ADPayloadParser クラスは ADStructureBuilder インターフェースと ADManufacturerSpecificBuilder インターフェースの実装を保持しています。ADStructureBuilder インターフェースは、バイト配列から ADStructure のインスタンスを生成するためのメソッドを持ち、ADManufacturerSpecificBuilder インターフェースは、バイト配列から ADManufacturerSpecific のインスタンスを生成するためのメソッドを持っています。ご想像のとおり、これらのインターフェースの実装を ADPayloadParser に登録することにより、特殊なフォーマットの AD structure をパースすることができます。

nv-bluetooth は iBeacon 以外にも幾つか AD structure をサポートしています。特に、ucode (ITU-T H.642) をサポートしています。詳細は nv-bluetooth の README.md と JavaDoc を参照してください。

2015年2月20日金曜日

Redshift の文字列型はバイト単位!?


私の勘違いでなければ、

通常の PostgreSQL の場合、character varying(N) などの N は「文字数単位」ですが、PostgreSQL 8.0.2 から派生した Amazon Redshift の場合は「バイト単位」になるようです。

PostgreSQL ドキュメント 「Character Types」 より抜粋

SQL defines two primary character types: character varying(n) and character(n), where n is a positive integer. Both of these types can store strings up to n characters (not bytes) in length.

Redshift ドキュメント 「Character Types」 より抜粋

CHAR and VARCHAR data types are defined in terms of bytes, not characters.

ですので、UTF-8 で文字データを格納するとした場合、UTF-8 では一文字のバイト数が最大 4 バイトになることを考慮して、「最大文字数 × 4」でカラムを定義しないといけないでしょうね。例えば、最大 100 文字を格納したいのであれば、character varying(400) というカラム定義になります。Unicode や UTF-8 については、「Unicode 理解度簡易チェック」や「文字数、UTF-8 でのバイト数、サロゲートペアの数を数える」も参照してください。

Redshift には、その他にも驚くような PostgreSQL との差異があるので、例えば Primary Key や Unique 制約が無視されたり Index を作れなかったりするので、「Redshift を単なる PostgreSQL の派生物」だと思ってスキーマ設計していると、はまりますね。

2014年12月16日火曜日

Sinatra + SSL

Found a better way to enable SSL in Sinatra than "Sinatra+Thin+SSL". This is a generic way and does not require Thin.

2014年10月1日水曜日

Sinatra + Thin + SSL

Finally found a way to enable SSL in Sinatra + Thin.

# [2014/12/16]
# Found a better way.
# See "Sinatra + SSL".


Start this script (sinatra+thin+ssl.rb) then type:
curl -k https://localhost/
and you will see "Hello, SSL."

2014年9月20日土曜日

MissingTableException on Google Cloud SQL

If you are using JDO to access Google Cloud SQL and suffering from MissingTableException like below:

org.datanucleus.store.rdbms.exceptions.MissingTableException: Required table missing : "`TABLE NAME`" in Catalog "" Schema "". DataNucleus requires this table to perform its persistence operations. Either your MetaData is incorrect, or you need to enable "datanucleus.autoCreateTables"

and if your table names contain lowercase letters, probably the issue can be solved by setting "datanucleus.identifier.case" properly.

"JDO : Datastore Identifiers" says "By default, DataNucleus will capitalise names". Therefore, if your table names contain lowercase letters, "datanucleus.identifier.case" should be set explicitly.

The valid values for "datanucleus.identifier.case" are UpperCase, LowerCase or PreserveCase (or MixedCase; See Change "datanucleus.identifier.case" 'PreserveCase' to be 'MixedCase' to be match internal namings). So, for example, your jdoconfig.xml will have to have the entry like the following.

<property name="datanucleus.identifier.case" value="LowerCase"/>

If you are developing your GAE application on Windows or Mac OS X, you may not encounter this case sensitivity problem until you deploy your application onto GAE. See "9.2.2 Identifier Case Sensitivity" (MySQL Reference Manual) for details.

2014年7月19日土曜日

JDO:カラムサイズは十分大きいのにデータが保存できないという問題を解消する方法

  JDO を使っているときに表示される次のようなエラーメッセージは、

Attempt to store value "{DATA}" in column "`{COLUMN-NAME}`" that has maximum length of 255. Please correct your data!

保存しようとしているデータのサイズが、対応するデータベーステーブルのカラムのデータサイズよりも大きいということを意味している。しかし、カラムサイズが十分大きくてもこのエラーが起きることがある。例えば、対応するカラムの型を TEXT で定義しているにもかかわらず(MySQL 的には TEXT は 65535 まで OK であるにもかかわらず)、上記のようなエラーが出てしまうことがある。

  この問題は、@Column アノテーションに length を追加して、最大長を指定すれば解消するようだ。具体的には、

@Persistent
@Column(name = "comment")
private String comment;

となっているところを、

@Persistent
@Column(name = "comment", length = 65535)
private String comment;

というような具合に変更する。