Pages

2015年8月11日火曜日

DFPリファレンス日本語訳 4


PQLガイド



PQL 構文と使い方

PQL はSQLに似たクエリ用の言語です. 構文もSQLそっくりですが以下のような若干の違いがあります。
PQL構文はこんな感じです。 
[WHERE <condition> {[AND | OR] <condition> ...}]
[ORDER BY <property> [ASC | DESC]]
[LIMIT {[<offset>,] <count>} | {<count> OFFSET <offset>}]

<condition> := <property> { = | != } <value>
<condition> := <property> { = | != } <bind variable>
<condition> := <property> IN <list>
<condition> := NOT <property> IN <list>
<condition> := <property> LIKE <wildcard%match>
<condition> := <property> IS NULL
<bind variable> := :<name>


Notes:
  • PQLキーワードは大文字小文字を区別しません。
  • Stringはバインド パラメータ内で記述されると自動的にエスケープされます。
  •  それを避けるためには
    • '(シングル)と一緒に使用したい場合には、' (シングル)で挟みます。
      • Example: "WHERE name = 'Company''s name'"
    • ”も同様です
      • Example: 'WHERE name = "The ""all-time best"" Company"'
PQLキーワード (大文字小文字は区別しない)
  • WHERE - 0or1つ以上の条件を指定します。AND と ORが使え、()により優先順位を指定できます。 ""(空文字)を指定すると、無条件となります。
    • 例: WHERE width = 728 ;   WHERE width = 728 AND height = 90 ;  WHERE (width = 728 AND height = 90) OR id IN (5008, 8745, 3487)
  • OR - そのまま
    • 例: WHERE width = 728 OR height = 90
  • AND - 指定する複数の条件を満たす場合
    • 例: WHERE type = 'AGENCY' AND name IN ('CompanyNameA', 'CompanyNameB')
  • ORDER BY - 並び替えを行います。(ASC where 'A' から順に) (DESC where 'A' が最後 )order.無指定のデフォルはASC.
    • 例: WHERE id IN (5008, 8745, 3487) ORDER BY id
  • LIMIT - 取得データ数の上限.<offset>,を含めることができる。
    •  (結果は同じ): WHERE type = 'AGENCY' LIMIT 50 OFFSET 50 ;   WHERE type = 'AGENCY' LIMIT 50,50
  • OFFSET - ページをめくるように、開始時からの取得数を指定
    • Example ( 51-100を返す): WHERE type = 'AGENCY' LIMIT 50 OFFSET 50.
  • <property> - 各オブジェクトが公開している各々のプロパティを指定できます。プロパティはオブジェクトにより異なります。後述のリストを参照してください。 例えば、creative のプロパティはid,namewidth,  height.のみが公開されます。
  • <value> - String は' か"で挟みます。数字はどちらでも構いません。ワイルドカードはサポートされていません。
  • IN - リスト内のプロパティを比較します。どれか1つが合致すれ条件に合致します。別の見方をすれば、たくさんの= 条件がorで連結されているのと同じです。()内でコンマで区切りリストを作成し、内のすべてが評価されます。
    •  WHERE name IN ('CompanyNameA', 'CompanyNameB')
  • NOT IN - リスト内のどれにも合致しない場合が条件に合致する。これは、 たくさんの!= が orで連結されているのと同じです。 
    •  WHERE NOT name IN ('CompanyNameA', 'CompanyNameB')
  • LIKE - ワイルドカードや一部指定のように使う
    •  WHERE name LIKE 'startswith%'
  • IS NULL - 未定義のオブジェクトを指定可能にします。例えば、parentIDがnullのオブジェクトを指定することでルートとなるAdUnit を取得できます。
    • WHERE parentId IS NULL.
  • <bind variable> - PQLで定数を定義でき、 : (コロン)の後に続けてスペース無しで名前を指定しすることで参照されます。                                    (Creates a query and enters two variables in place of hard-coded id and status property values):
    // Create two mapped parameters: id and status
    String_ValueMapEntry[] values = new String_ValueMapEntry[2];
    values[0] = new String_ValueMapEntry("id", new NumberValue(null, "123"));
    values[1] = new String_ValueMapEntry("status", new TextValue(null, "APPROVED"));
    
    // Create our statement and map our bind variables
    Statement statement = new Statement();
    statement.setQuery("WHERE id = :id AND status = :status LIMIT 500");
    statement.setValues(values);
  • DateTime fields - バインドパラメーターに日時を指定できます。 ISO 8601準拠のStringフォーマットを使用します。.
    // Create two mapped parameters: id and status
    String_ValueMapEntry[] values = new String_ValueMapEntry[1];
    values[0] = new String_ValueMapEntry("startDateTime", new DateTimeValue(null, dateTime));
    
    // Create our statement and map our bind variables
    Statement statement = new Statement();
    statement.setQuery("WHERE endDateTime < '2012-01-01T00:00:00' AND startDatetTime > :startDateTime LIMIT 500");
    statement.setValues(values);

移行ガイド: PQL 内でGeo Targetsを使用

Original Geo TableChanges
Country(国)CurrencyCode(通貨コード)は廃止 
Region(地域)RegionCode no longer exists in the combined Geo_Target table. CountryCode and CountryName can be pulled via the relationship found through the ParentIds column. What were formerly classified as Regions are listed as more granular sub-types of 'States,' 'Prefectures,' 'Provinces,' 'Cantons,' and so on.
MetroMetros map to DMA_Regions. MetroCode no longer exists in the combined Geo_Target table.
CityMetroCode, RegionCode, and CountryCode no longer exist in the combined Geo_Target table. CountryCode, CountryName, RegionCode, RegionName, MetroCode, and MetroName can be pulled via the relationship found through the ParentIds column. What were formerly classified as Cities are listed as more granular sub-types of 'Municipalities,' 'Airports,' 'Counties,' and so on.
Postal_CodeCountryCode can be pulled via the relationship found through the ParentIds column.
対象地区はまだまだ拡張をしている段階で、you will probably find new entries within the older tables that might not fit that categorization. For example, airports are far more granular than our smallest unit defined, so they'll appear in the City table. This means that while using the specific geo tables will still yield all the same object ids, they will likely be poorly classified with the new set of targetable locations.
The migration of targetable locations should be quite straightforward. If you are pulling down the various tables locally, then there should already be a simple Id/Name mapping available. You can subsequently do a one time update to look at Geo_Target table, querying the same Id field to fetch the new fields of Type / Country Code / Parent Ids. You will, in some cases, notice multiple Geo_Targets with the same name, these are not duplicates, but rather targetable location objects that exist at different type-levels, some cities share names with regions for example. To maintain the behavior currently existing with the legacy tables, matching on ids to build a new list of geo targets should yield the closest level of type approximation from the new Geo_Target table.
To replicate the parent object fields in each of the deprecated legacy tables, you can now build these columns for each respective type by using the ParentIds column. This list of ParentIds will allow you to then query for the parent geo_targets, each of which would yield a name and id.
A best practice suggestion would be to keep a singular mapping of geo_targets locally instead of having a table for each type as we might add new sub-types in the future.

マッチテーブルを PQLで取得する

マッチテーブルはdata 転送ファイル内の値で name-to-IDの参照を提供し、 ad unit や line itemなどの広告配信情報とのマッチングを可能にします。例えば、For example, a データ転送イベントが、ID 12345678の  line item が 01-6-2011 at 16:10:10に配信されたことを記録した場合、The line item match table lets you know the name of that line item, as well as its start date, end date, and other useful attributes.
You can easily create your own match table scripts that include only the fields and range of objects you need using the DFP API. An example set of Python match table scripts follows. Additionally, each of the DFP API client libraries have examples of GetAllX for each service that can be adjusted to output to files or databases to fulfill this need if you aren't using Python.


  1. 証明書のセットアップ
    Populate the templated fields in the googleads.yaml file, then callDfpClient.LoadFromStorage() to initialize the Client object.
      #  クライアントの初期化
      dfp_client = dfp.DfpClient.LoadFromStorage()
  2. DataDownloaderのコンストラクト
      #  レポートダウンローダの初期化
      report_downloader = client.GetDataDownloader(version='v201505')
  3. Set up your query statements and file handles
      create the file handles to write your match tables to as well as the query statements to filter on.
      line_items_file = tempfile.NamedTemporaryFile(
          prefix='line_items_', suffix='.csv', mode='w', delete=False)
      ad_units_file = tempfile.NamedTemporaryFile(
          prefix='ad_units_', suffix='.csv', mode='w', delete=False)
    
      line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
                              'ASC')
      ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
  4.  DownloadPqlResultToCsvにクエリとファイルの扱いを渡す
      # 指定ファイルにPQL でダウンロード
      report_downloader.DownloadPqlResultToCsv(
          line_items_pql_query, line_items_file)
      report_downloader.DownloadPqlResultToCsv(
          ad_units_pql_query, ad_units_file)

DFPリファレンス日本語訳 3

OAuth 2.0 サービスアカウントをDFPで使う。





サービスアカウントは、アプリケーションがGoogle APIに、OAuth2.0を通じてアクセスするために使われる特別なGoogleアカウントです。
サービスアカウントは、OAuth2.0により無人認証を可能とします。代わりに、あなたのアプリケーションだけがアクセスできる鍵ファイルを使います。
このガイドでは、サービスアカウントでDFP APIにアクセスする方法をお話しします。

  • 事前の準備

  • DFP ネットワークの作成.
  • 言語別のクライアントライブラリ.
  • Google API クライアントライブラリ-クライアントライブラリに含まれるため別個のダウンロードは不要. 

DFP APIにアクセスするためのサービスアカウントの準備

  1. サービスアカウントの証明書を作成するか、すでにある証明書にアクセスするには、OAuth 2.0 クライアントIDを作成して、*.p12 privateキーを取得する必要があります。
    1.  Google Developers Consoleへ行く
    2. プロジェクトを選択する。 なければCreate Projectで作成
    3. 左のスライダーからCredentialsを選択.
    4.  サービスアカウントをセットアップするには,  Create New Client IDを選択し、. application typeをサービスアカウトに指定後Create Client IDで作成します。. ダイアログで Okay, got itで完了. (すでにサービスアカウントがあれば、Generate new keyにより別のIDを新規作成できます。)

  2. 重要: サービスアカウントを通じてGoogle servicesへのアクセスを可能にする.p12 キーを保護する必要があります。一番好ましいのは、1つのサービスアカウントに1つのGoogle APIを割り当てることです。これにより攻撃者のアクセスできるデータを制限してサービスアカウントの.p12 キーが流出した場合の予防策とできます.
  3.  サービスアカウントをDFP のユーザに追加します. 
    1. DoubleClick for Publishers networkへ行く
    2. Adminタブをクリック
    3. API アクセスが有効であることを確認する
    4. サービスアカウント追加ボタンをクリックAdd service account user button screenshot.
    5. フォームを埋めますAdd service account user page screenshot.
    6. Save を押し、確認します。Add service account confirmation screenshot.
    7. 追加したいサービスアカウント分を繰り返します
    8.  Usersタブに追加されたのがわかります。View service account users screenshot.
  4. これでOAuth2.0認証によりサービスアカウントを使用して DFPネットワークにアクセスできるようになりました。 以下のサンプルでは、サービスアカウントを使用してOAuth 2.0 認証を行い、アクセストークンを取得、基本的なDFP APIを呼び出してサービスカウントに関連付けています。
  5. 
    
        // サービスアカウントの証明書を作成
        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(new NetHttpTransport())
            .setJsonFactory(new GsonFactory())
            .setServiceAccountId(SERVICE_ACCOUNT_ID)
            .setServiceAccountScopes(ImmutableList.of(SCOPE))
            .setServiceAccountPrivateKeyFromP12File(new File(P12_FILE_PATH))
            .build();
        credential.refreshToken();
    
        // DfpSession セッションを開始.
        DfpSession session = new DfpSession.Builder()
            .fromFile()
            .withOAuth2Credential(credential)
            .build();
    
        DfpServices dfpServices = new DfpServices();
    
        runExample(dfpServices, session);
    
      

よく聞かれる質問

サービスアカウントでDFPのダッシュボードにログインできますか?
サービスアカウントはGoogleアカウントではありませんので、DFPのダッシュボードにはログインできません。

サービスアカウントのトークンはどのくらいの頻度で更新すべきですか?
アクセストークンは、OAuth2.0認証後の1時間で期限が切れます。その場合、クライアントライブラリにより新たにトークンを取得する必要があります。
サービスアカウントにはどのような役割を与えるべきでしょうか?
サービスアカウントの作成時にはできるだけ少ない役割に制限すべきです。
例えば、管理者権限によりサービスアカウントを作成した場合、第三者が利用することでアカウントの乗っ取りを行うことができるようになります。

2015年8月10日月曜日

DFPリファレンス日本語訳2

ライブラリ & サンプルコード



クライアント開発を簡単にするため、ライブラリが提供されます。また、 DFP関連の共通タスクの使い方がサンプルコードにより示されます。
重要: もしも以下のライブラリのうち1つをダウンロードするならば、SOAP ライブラリもダウンロードする必要があります。どのSOAPライブラリを使用すべきかについては付属のドキュメントを参照ください。.


DFPリファレンス日本語訳 1

さあ はじめましょう




1. 新規登録

まだ持っていなければ、DFPアカウントに登録する。アカウントには以下の2種類がある。
Account Types で比較できます。

2. 認証の準備

oAuth2.0による認証の準備のため、以下を行ってください。

  • ネットワークのIDをチェックします。ネットワークにログインした時に#の前の数字がネットワークコードです。
  • Google Developers Consoleで"installed application"のクライアントIDを作成します。

  • Authentication でもっと詳しく知ることができます。

    3. APIアクセスを有効に
    APIを使うには、ネットワークごとに少なくとも1つの有効化が必要です。例えば、テスト環境では別にもう一つが必要になります。

    有効化の方法
    テスト環境用に有効化
      • テスト用にGoogleアカウントを1つ作成します。
      • 以下のいずれかでテストネットワークを作成します
        1つの Google accountに1つだけテストアカウントを作成できます
      • https://www.google.com/dfp/signin. からネットワークにサインインしてください。テストネットワークに紐付いたGoogleアカウントではAuthenticationError.GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORK エラーが出ます。
      • ステップ2で調べたネットワークコードを使用して、機能をリクエストします。NetworkService.getAllNetworks() により現在ログインしているアカウントに紐付けられたネットワークのすべてを得ることができます。
    • 製品版APIにアクセスする。
      • DFPアカウントに管理者権限でサインイン
      • Admin タブを選ぶ
      •  Network Settings タブでAPI Access右のアイコンをクリック
      • API terms and conditions が表示されたら, Acceptをクリック.
      • SaveでAPIアクセスを有効にする

    4. クライアント側をセットアップ

     DFP client librariesをダウンロード. ライブラリはアプリ実装を簡単にするためのラッパーやクラスを含みます。
    さらに  SOAP toolkitをダウンロードします。
    以下により、各言語での実装環境を整えます。


     以下がPHP client libraryを使うための基本です.
    このサンプルを動かす前に、README のステップを行ってください。
    ライブラリにはPHP 5.2.xが必要で  native SoapClientを使用、以下の PHP extensionsを要求します。
     PHP client library を以下のように使ってはじめましょう。
    1. credentials(証明書)のセットアップ
      まずは、新しい DfpUserを作成して.thesrc/Google/Api/Ads/Dfp/auth.ini ファイルから証明書をロードします。. README には他の方法を記載しています。
        // Get DfpUser from credentials in "../auth.ini"
        // relative to the DfpUser.php file's directory.
        $user = new DfpUser();
    2. InventoryServiceのためのクライアントをコンストラクトする
      各 service はその都度getService() により取り出され. getService() はそのサービスで使用するすべてのクラスを持つSOAP クライアントを返します。
        // Get the InventoryService.
        $inventoryService = $user->GetService('InventoryService', 'v201505');
    3. Perform an operation
      API接続のためのクライアント初期化が終わったら、処理をおこなえます。以下のコードはアカウントすべての広告ユニットを一度に500件返します。
        //  すべての広告をSELECTするためのstatement(声明)を作成する
        $statementBuilder = new StatementBuilder();
        $statementBuilder->OrderBy('id ASC')
            ->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT);
      
        // Default for total result set size. デフォルトのトータル結果
        $totalResultSetSize = 0;
      
        do {
          // Get ad units by statement. 広告ユニットをstatementにより取得
          $page = $inventoryService->getAdUnitsByStatement(
              $statementBuilder->ToStatement());
      
          // Display results. 結果を表示
          if (isset($page->results)) {
            $totalResultSetSize = $page->totalResultSetSize;
            $i = $page->startIndex;
            foreach ($page->results as $adUnit) {
              printf("%d) Ad unit with ID %s, name '%s', and status %s was found.\n",
                  $i++, $adUnit->id, $adUnit->name, $adUnit->status);
            }
          }
      
          $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
        } while ($statementBuilder->GetOffset() < $totalResultSetSize);
      
        printf("Number of results found: %d\n", $totalResultSetSize);
     client libraryなしでの実装は NoClientLibrary wiki articleを参照ください。

    5. 次のステップへ

    client libraryを動かしてみてください。
    お持ちのバージョンのリファレンスを読んでAPIについて学びましょう。
    ヘルプが必要なら、フォーラムに行くか、この後の詳しい解説を読んでください。 

    2012年12月6日木曜日

    Unityでストップやスローモーション・早送りを実現するには




    Time.timeScale
    の値を変更するだけです。

    Time.timeScale=0;
    なら停止

    Time.timeScale=1;
    が通常の時間の経過速度です。

    2倍速にしたければ、
    Time.timeScale=2;
    となります。

    反対にスローなら
    Time.timeScale=0.1;


    簡単すぎでしょうか。

    2012年11月19日月曜日

    NGUI:UILabel.textをコードで設定後、文字のY軸が変わる問題



     どうやら、コードでUILabel.textを設定する場合で、以前の文字列長以上の文字を設定する場合で、PivotがCenterなどの場合に発生するよう。

    対策としては、TopLeftかTopRightのPivotを設定する。以上。

    結構はまってしまうかも。


    2012年11月4日日曜日

    NGUIでイベントを取得する


    NGUIでは、ボタンタップ時やドラッグ時の挙動を独自に実装できます。

    ものすごくカンタン。
    スクリプトを用意し、以下のメソッドを実装します。
    そして、GameObjectやNGUIのウィジェットにコライダをつけてから、スクリプトを付加してやれば完成!

    以下は取得できるイベントの種類です。

    • void OnHover (bool isOver) – マウスポインタが重なったときに呼ばれます。タップは×。
    • void OnPress (bool isDown) – マウスによりクリック(押下時と離脱時の2回)が発生したときによばれます。タップも○。
    • void OnClick() — 上と同じですが、離脱時の1回だけ呼ばれるパターン。
    • void OnDoubleClick () — ダブルクリックされたとき。
    • void OnSelect (bool selected) –選択メニューで便利?OnClickと同じだけど、こっちは他のものが選択されるまでは2度目の選択時には呼ばれません。
    • void OnDrag (Vector2 delta) – OnPress(true) と OnPress(false)の間に起きた移動を取得。タップ○。
    • void OnDrop (GameObject drag) – ドロップ時(OnPress(false)のタイミング)にドロップされた(下にある)オブジェクト側で呼ばれる。引数には、ドロップした(上にある)オブジェクトが渡される。
    • void OnTooltip (bool show) – Sent after the mouse hovers over a collider without moving for longer thantooltipDelay, and when the tooltip should be hidden. Not sent on touch-based devices.
    • void OnScroll (float delta) マウスのホイールが動いた時によばれる
    • void OnKey (KeyCode key) キーボードが押されたときによばれる