text:
<properties
	pageTitle="Add Mobile Services to an existing universal Windows Store app | Microsoft Azure"
	description="Learn how to get started using Mobile Services to leverage data in your Windows Store app."
	services="mobile-services"
	documentationCenter="windows"
	authors="ggailey777"
	manager="dwrede"
	editor=""/>

<tags
	ms.service="mobile-services"
	ms.workload="mobile"
	ms.tgt_pltfrm="mobile-windows"
	ms.devlang="dotnet"
	ms.topic="article"
	ms.date="07/21/2016"
	ms.author="glenga"/>

# Add Mobile Services to an existing app

> [AZURE.SELECTOR-LIST (Platform | Backend )]
- [(Windows Runtime 8.1 universal C# | .NET)](mobile-services-dotnet-backend-windows-universal-dotnet-get-started-data.md)
- [(Windows Phone Silverlight 8.x | Javascript)](mobile-services-windows-phone-get-started-data.md)
- [(Android | Javascript)](mobile-services-android-get-started-data.md)

>[AZURE.WARNING] This is an **Azure Mobile Services** topic.  This service has been superseded by Azure App Service Mobile Apps and is scheduled for removal from Azure.  We recommend using Azure Mobile Apps for all new mobile backend deployments.  Read [this announcement](https://azure.microsoft.com/blog/transition-of-azure-mobile-services/) to learn more about the pending deprecation of this service.
>
> Learn about [migrating your site to Azure App Service](https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-migrating-from-mobile-services/).
>
> Get started with Azure Mobile Apps, see the [Azure Mobile Apps documentation center](https://azure.microsoft.com/documentation/learning-paths/appservice-mobileapps/).

## Overview

This topic shows you how to use Azure Mobile Services as a backend data source for a Windows Store app. In this tutorial, you will download a Visual Studio 2013 project for an app that stores data in memory, create a new mobile service, integrate the mobile service with the app, and view the changes to data made when running the app.

The mobile service that you will create in this tutorial is a .NET backend mobile service. .NET backend enables you to use .NET languages and Visual Studio for server-side business logic in the mobile service, and you can run and debug your mobile service on your local computer. To create a mobile service that lets you write your server-side business logic in JavaScript, see the JavaScript backend version of this topic.

>[AZURE.NOTE]This topic shows you how to use the tooling in Visual Studio Professional 2013 with Update 3 to connect a new mobile service to a universal Windows app. The same steps can be used to connect a mobile service to a Windows Store or Windows Phone Store 8.1 app. To connect a mobile service to a Windows Phone 8.0 or Windows Phone Silverlight 8.1 app, see [Get started with data for Windows Phone](mobile-services-windows-phone-get-started-data.md).

## Prerequisites

To complete this tutorial, you need the following:

* An active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial](https://azure.microsoft.com/pricing/free-trial/?WT.mc_id=A0E0E5C02&returnurl=http%3A%2F%2Fazure.microsoft.com%2Fdocumentation%2Farticles%2Fmobile-services-dotnet-backend-windows-universal-dotnet-get-started-data%2F).
* Visual Studio 2013 (Update 3 or a later version).

## Download the GetStartedWithData project

This tutorial is built on the [GetStartedWithMobileServices app](http://go.microsoft.com/fwlink/p/?LinkID=510826), which is a universal Windows app project in Visual Studio 2013. The UI for this app is identical to the app generated by the Mobile Services quickstart, except that added items are stored locally in memory.

1. Download the C# version of the GetStartedWithMobileServices sample app from the [Developer Code Samples site].

2. In Visual Studio 2013, open the downloaded project and examine the MainPage.xaml.cs file found in the GetStartedWithData.Shared project folder.

   	Notice that added **TodoItem** objects are stored in an in-memory **ObservableCollection<TodoItem>**.

3. Press the **F5** key to rebuild the project and start the app.

4. In the app, type some text in **Insert a TodoItem**, then click **Save**.

   	![](./media/mobile-services-windows-universal-dotnet-download-project/mobile-quickstart-startup.png)

   	Notice that the saved text is displayed.

5. Right-click the Windows Phone 8.1 project, click **Set as Start-up Project**, then press **F5** to start the Windows Phone Store app.

	![](./media/mobile-services-windows-universal-dotnet-download-project/mobile-quickstart-startup-wp8.png)

6. Repeat steps 3 and 4 to verify that the sample behaves the same way.

## Create a new mobile service from Visual Studio

The following steps create a new mobile service in Azure and add code to your project that connects your app to this new service. Visual Studio 2013 connects to Azure on your behalf to create the new mobile service by using the credentials that you provide. When you create a new mobile service, you must specify an Azure SQL Database that is used by the mobile service to store app data.

1. In Visual Studio 2013, open Solution Explorer, right-click the Windows Store app project, click **Add**, and then click **Connected Service...**.

2. In the Services Manager dialog, click **Create service...**, then select **<Manage...>** from  **Subscription** in the Create Mobile Service dialog.

	![create service manage subscriptions](./media/mobile-services-dotnet-backend-create-new-service-vs2013/mobile-create-service-from-vs2013.png)

3. In Manage Microsoft Azure Subscriptions, click **Sign In...** to sign in to your Azure account (if required), select an available subscription, then click **Close**.

	When your subscription already has one or more existing mobile services, the service names are displayed.

5. Back in the **Create Mobile Service** dialog, select your **Subscription**, the **.NET Framework** backend  in **Runtime** and a **Region** for your mobile service, then type a **Name** for your mobile service.

	>[AZURE.NOTE]Mobile service names must be unique. A red X is displayed next to **Name** when the name you supplied is not available.

6. In **Database**, select **<Create a free SQL Database>**, supply the **Server user name**, **Server password**, and **Server password confirmation** then click **Create**.

  	![create new mobile service in VS 2013](./media/mobile-services-dotnet-backend-create-new-service-vs2013/mobile-create-service-from-vs2013-2.png)

	> [AZURE.NOTE]
	> As part of this tutorial, you create a new free SQL Database instance and server. You can reuse this new database and administer it as you would any other SQL Database instance. You can only have one free database instance. If you already have a database in the same region as the new mobile service, you can instead choose the existing database. When you choose an existing database, make sure that you supply correct login credentials. If you supply incorrect login credentials, the mobile service is created in an unhealthy state.

7. After the mobile service is created, select the newly created mobile service from the list in Service Manager and click **OK**.

   	After the wizard completes, the mobile service project is added to your solution, the required NuGet packages are installed, a reference to the Mobile Services client library is added to the project, and your project source code is updated.

  7. In Solution Explorer, open the App.xaml.cs code file in the GetStartedWithData.Shared project folder, and notice the new static field that was added to the **App** class inside a Windows Store app conditional compilation block, which looks like the following example:

	public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient
	    todolistClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
	        "https://todolist.azure-mobile.net/",
	        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

  This code provides access to your new mobile service in your app by using an instance of the [MobileServiceClient](http://go.microsoft.com/fwlink/p/?LinkId=302030) class. The client is created by supplying the URI and the application key of the new mobile service. This static field is available to all pages in your app.

  8. Right-click the Windows Phone app project, click **Add**, click **Connected Service...**, select the mobile service that you just created, and then click **OK**. The same code is added to the shared App.xaml.cs file, but this time within a Windows Phone app conditional compilation block.

At this point, both the Windows Store and Windows Phone Store apps are connected to the new mobile service. The next step is to test the new mobile service project.

## Test the mobile service project locally

1. In Visual Studio in Solution Explorer, right click the service project and click **Start new instance** under the **Debug** context menu.

    ![start mobile service project locally](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/vs-start-debug-service-project.png)

    Visual Studio opens the default web page for your service. By default, Visual Studio hosts your mobile service locally in IIS Express.

2. Right-click the tray icon for IIS Express on the Windows taskbar and verify that your mobile service has started.

	 ![verify the mobile service in the taskbar](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/iis-express-tray.png)

3. On the start page of your .NET backend, click **try it out**.

    ![mobile service start up page](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/service-welcome-page.png)

    This displays the API documentation page, which you can use to test the mobile service.

	>[AZURE.NOTE]Authentication is not required to access this page when running locally. When running in Azure, you must supply the application key as the password (with no username) to access this page.

4. Click the **GET tables/TodoItem** link.

	![](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/service-api-documentation-page.png)

	This displays the GET response page for the API.

5. Click **try this out** and then click **send**.

	![](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/service-try-this-out-get-todoitems.png)

	This sends a GET request to the local mobile service to return all rows in the TodoItem table. Because the table is seeded by the initializer, two TodoItem objects are returned in the body of the response message. For more information about initializers, see [How to make data model changes to a .NET backend mobile service](mobile-services-dotnet-backend-how-to-use-code-first-migrations.md).

	![](./media/mobile-services-dotnet-backend-test-local-service-api-documentation/service-try-this-out-get-response.png)

## Update the app to use the mobile service

In this section you will update the universal Windows app to use the mobile service as a backend service for the application. You only need to make changes to the MainPage.cs project file in the GetStartedWithData.Shared project folder.

2. Replace the TodoItem class definition with the following code:

	    public class TodoItem
	    {
	        public string Id { get; set; }

	        [Newtonsoft.Json.JsonProperty(PropertyName = "text")]
	        public string Text { get; set; }

	        [Newtonsoft.Json.JsonProperty(PropertyName = "complete")]
	        public bool Complete { get; set; }
	    }

	The **JsonPropertyAttribute** is used to define the mapping between property names in the client type to column names in the underlying data table.

	>[AZURE.NOTE] In a universal Windows app project, the TodoItem class is defined in the seperate code file in the shared DataModel folder.

1. In the file MainPage.cs, add or uncomment the following using statements:

		using Microsoft.WindowsAzure.MobileServices;

4. Comment-out or delete the line that defines the existing items collection, then uncomment or add the following lines, replacing _<yourClient>_ with the `MobileServiceClient` field added to the App.xaml.cs file when you connected your project to the mobile service:

		private MobileServiceCollection<TodoItem, TodoItem> items;
		private IMobileServiceTable<TodoItem> todoTable =
		    App.<yourClient>.GetTable<TodoItem>();

	This code creates a mobile services-aware binding collection (items) and a proxy class for the database table (todoTable).

4. In the **InsertTodoItem** method, remove the line of code that sets the **TodoItem.Id** property, add the **async** modifier to the method, and uncomment the following line of code:

		await todoTable.InsertAsync(todoItem);

	This code inserts a new item into the table.

5. Replace the **RefreshTodoItems** method with the following code:

		private async void RefreshTodoItems()
        {
            MobileServiceInvalidOperationException exception = null;
            try
            {
                // Query that returns all items.
                items = await todoTable.ToCollectionAsync();
            }
            catch (MobileServiceInvalidOperationException e)
            {
                exception = e;
            }
            if (exception != null)
            {
                await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
            }
            else
            {
                ListItems.ItemsSource = items;
                this.ButtonSave.IsEnabled = true;
            }
        }

	This sets the binding to the collection of items in `todoTable`, which contains all of the **TodoItem** objects returned from the mobile service. If there is a problem executing the query, a message box is raised to display the errors.

6. In the **UpdateCheckedTodoItem** method, add the **async** modifier to the method, and uncomment the following line of code:

		await todoTable.UpdateAsync(item);

	This sends an item update to the mobile service.

Now that the app has been updated to use Mobile Services for backend storage, it's time to test the app against Mobile Services.

## Publish the mobile service to Azure

1. In Visual Studio, right-click the project, click **Publish** > **Microsoft Azure Mobile Services**. Instead of using Visual Studio, [you may also use Git](./
mobile-services-dotnet-backend-store-code-source-control.md).

2. Sign in with Azure credentials and select your service from **Existing Mobile Services**. Visual Studio downloads your publish settings directly from Azure. Finally, click **Publish**.

## Test the mobile service hosted in Azure

Now we can test both versions of the universal Windows app against the mobile service hosted in Azure.

1. Press the F5 key to rebuild the project and start the Windows Store app.

2. In the app, type meaningful text, such as *Complete the tutorial*, in **Insert a TodoItem**, and then click **Save**.

	![](./media/mobile-services-windows-universal-test-app/mobile-quickstart-startup.png)

	This sends a POST request to the new mobile service hosted in Azure.

3. Stop debugging and change the default start up project in the universal Windows solution to the Windows Phone Store app and press F5 again.

	![](./media/mobile-services-windows-universal-test-app/mobile-quickstart-completed-wp8.png)

	Notice that data saved from the previous step is loaded from the mobile service after the app starts.

## View the data stored in the SQL Database

The final optional step of this tutorial is to check in the SQL Database associated with the mobile service an review the stored data.

1. In the [Azure classic portal](https://manage.windowsazure.com/), click manage for the database associated with your mobile service.

	![sign-in to manage SQL Database](./media/mobile-services-dotnet-backend-view-sql-data/manage-sql-azure-database.png)

2. In the portal execute a query to view the changes made by the Windows Store app. Your query will be similar to the following query but use your database name instead of todolist.

        SELECT * FROM [todolist].[todoitems]

    ![query SQL Database for stored items](./media/mobile-services-dotnet-backend-view-sql-data/sql-azure-query.png)

	Note that the table includes Id, __createdAt, __updatedAt, and __version columns. These columns support offline data sync and are implemented in the [EntityData](http://msdn.microsoft.com/library/microsoft.windowsazure.mobile.service.entitydata.aspx) base class. For more information, see [Get started with offline data sync].

This concludes the tutorial.

## Next steps

This tutorial demonstrated the basics of enabling a universal Windows app project to work with data in Mobile Services. Next, consider reading up on one of these other topics:

* [Get started with authentication]

Learn how to authenticate users of your app.

* [Get started with push notifications]

Learn how to send a very basic push notification to your app.

* [Mobile Services C# How-to Conceptual Reference](mobile-services-dotnet-how-to-use-client-library.md)

Learn more about how to use Mobile Services with .NET.

[Validate and modify data with scripts]: https://azure.microsoft.com/develop/mobile/tutorials/validate-modify-and-augment-data-dotnet
[Refine queries with paging]: https://azure.microsoft.com/develop/mobile/tutorials/add-paging-to-data-dotnet
[Get started with Mobile Services]: mobile-services-dotnet-backend-windows-store-dotnet-get-started.md
[Get started with authentication]: mobile-services-dotnet-backend-windows-store-dotnet-get-started-users.md
[Get started with push notifications]: mobile-services-dotnet-backend-windows-store-dotnet-get-started-push.md

[Get started with offline data sync]: mobile-services-windows-store-dotnet-get-started-offline-data.md

[Mobile Services SDK]: http://go.microsoft.com/fwlink/p/?LinkId=257545
[Developer Code Samples site]:  http://go.microsoft.com/fwlink/p/?LinkID=510826
[Mobile Services .NET How-to Conceptual Reference]: mobile-services-windows-dotnet-how-to-use-client-library.md
[MobileServiceClient class]: http://go.microsoft.com/fwlink/p/?LinkId=302030


text:
module TokyoMetro::ClassNameLibrary::Api::StationFacility

  extend ::ActiveSupport::Concern

  module ClassMethods

    # @!group クラスメソッド (1) - メタデータ

    # クラス指定 - odpt:StationFacility
    # @return [String]
    def rdf_type
      "odpt:StationFacility"
    end

    # JSON-LD 仕様に基づく context のURL - URL
    # @return [String]
    def context
      "http://vocab.tokyometroapp.jp/context_odpt_StationFacility.jsonld"
    end

    # @!group 生成するクラスの情報

    # トップレベルのクラス
    # @return [Const ( ::TokyoMetro::Api::StationFacility )]
    def toplevel_namespace
      ::TokyoMetro::Api::StationFacility
    end

    # 配列のクラス
    # @return [Const ( ::TokyoMetro::Api::StationFacility::List )]
    def list_class
      ::TokyoMetro::Api::StationFacility::List
    end

    # 配列の要素となるインスタンスのクラス
    # @return [Const ( ::TokyoMetro::Api::StationFacility::Info )]
    def info_class
      ::TokyoMetro::Api::StationFacility::Info
    end

    def barrier_free_top_level_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree
    end

    def barrier_free_list_class
      TokyoMetro::Api::StationFacility::Info::BarrierFree::List
    end

    def barrier_free_meta_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Info
    end

    def barrier_free_elevator_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Elevator::Info
    end

    def barrier_free_escalator_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Escalator::Info
    end

    def barrier_free_link_for_mobility_scooter_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::LinkForMobilityScooter::Info
    end

    def barrier_free_stairlift_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Stairlift::Info
    end

    def barrier_free_toilet_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Toilet::Info
    end

    def barrier_free_toilet_assinstant_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Toilet::Assistant
    end

    def barrier_free_service_detail_list_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::ServiceDetail::List
    end

    def barrier_free_service_detail_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::ServiceDetail::Info
    end

    def escalator_service_detail_list_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Escalator::ServiceDetail::List
    end

    def escalator_service_detail_info_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Escalator::ServiceDetail::Info
    end

    def escalator_service_detail_direction_class
      ::TokyoMetro::Api::StationFacility::Info::BarrierFree::Facility::Escalator::ServiceDetail::Direction
    end

    def platform_list_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::List
    end

    def platform_info_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info
    end

    def platform_transfer_list_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::Transfer::List
    end

    def platform_transfer_info_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::Transfer::Info
    end

    def platform_barrier_free_list_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::BarrierFree::List
    end

    def platform_barrier_free_info_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::BarrierFree::Info
    end

    def platform_surrounding_area_list_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::SurroundingArea::List
    end

    def platform_surrounding_area_info_class
      ::TokyoMetro::Api::StationFacility::Info::Platform::Info::SurroundingArea::Info
    end

    # @!group Factory Pattern のクラスの情報

    # API からデータを取得するための Factory Pattern クラス
    # @return [Const ( ::TokyoMetro::Factory::Get::Api::DataSearch::StationFacility )]
    def factory_for_getting
      ::TokyoMetro::Factory::Get::Api::DataSearch::StationFacility
    end

    # API から取得したデータを保存するための Factory Pattern クラス
    # @return [Const ( ::TokyoMetro::Factory::Save::Api::StationFacility::EachFile )]
    def factory_for_saving_to_each_file
      ::TokyoMetro::Factory::Save::Api::StationFacility::EachFile
    end

    # グループ化されたデータを保存するための Factory Pattern クラス
    # @return [Const ( ::TokyoMetro::Factory::Save::Api::StationFacility::Group )]
    def factory_for_saving_datas_of_each_group
      ::TokyoMetro::Factory::Save::Api::StationFacility::Group
    end

    def list_class_for_saving_grouped_infos
      ::TokyoMetro::Factory::Save::Api::StationFacility::Group::List
    end

    def file_info_class_for_saving
      ::TokyoMetro::Factory::Save::Api::StationFacility::Group::FileInfo
    end

    # JSON をパースして得られた配列の要素である Hash からインスタンスを作成するメソッドための Factory Pattern クラス
    # @return [Const ( ::TokyoMetro::Factory::Generate::Api::StationFacility::Info )]
    def factory_for_generating_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info
    end

    # @note {::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Info} でないことに注意
    def factory_for_generating_barrier_free_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info
    end

    def factory_for_generating_barrier_free_service_detail_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::ServiceDetail::Info
    end

    def factory_for_generating_barrier_free_elevator_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Elevator
    end

    def factory_for_generating_barrier_free_escalator_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Escalator
    end

    def factory_for_generating_barrier_free_escalator_service_detail_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Escalator::ServiceDetail::Info
    end

    def factory_for_generating_barrier_free_escalator_service_detail_direction
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Escalator::ServiceDetail::Direction
    end

    def factory_for_generating_barrier_free_link_for_mobility_scooter_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::LinkForMobilityScooter
    end

    def factory_for_generating_barrier_free_stairlift_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Stairlift
    end

    def factory_for_generating_barrier_free_toilet_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Toilet
    end

    def factory_for_generating_barrier_free_toilet_assistant_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::BarrierFree::Info::Facility::Toilet::Assistant
    end

    def factory_for_generating_platform_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::Platform::Info
    end

    def factory_for_generating_platform_barrier_free_info_from_string
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::Platform::Info::BarrierFree::Info
    end

    def factory_for_generating_platform_transfer_info_from_hash
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::Platform::Info::Transfer::Info
    end

    def factory_for_generating_platform_surrounding_area_info_from_string
      ::TokyoMetro::Factory::Generate::Api::StationFacility::Info::Platform::Info::SurroundingArea::Info
    end

    # 保存済みの情報を処理しインスタンスを復元するための Factory Pattern クラス
    # @return [Const ( ::TokyoMetro::Factory::Generate::Api::StationFacility::List )]
    def factory_for_generating_from_saved_file
      ::TokyoMetro::Factory::Generate::Api::StationFacility::List
    end

    # @!group DB

    def factory_for_seeding_list
      ::TokyoMetro::Factory::Seed::Api::StationFacility::List
    end

    def factory_for_seeding_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info
    end

    def factory_for_seeding_barrier_free_facilities
      ::TokyoMetro::Factory::Seed::Api::StationFacility::List::BarrierFree
    end

    def factory_for_seeding_barrier_free_facilities_of_each_station
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::List
    end

    def factory_for_seeding_barrier_free_facility_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Info
    end

    def factory_for_seeding_barrier_free_facility_escalator_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Facility::Escalator::Info
    end

    def factory_for_seeding_barrier_free_facility_toilet_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Facility::Toilet::Info
    end

    def factory_for_seeding_barrier_free_facility_service_detail_list
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::ServiceDetail::List
    end

    def factory_for_seeding_barrier_free_facility_service_detail_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::ServiceDetail::Info
    end

    def factory_for_seeding_escalator_service_detail_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Facility::Escalator::ServiceDetail::Info
    end

    def factory_for_seeding_escalator_service_detail_direction
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Facility::Escalator::ServiceDetail::Direction
    end

    def factory_for_seeding_toilet_service_detail_assistant_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::BarrierFree::Facility::Toilet::Assistant
    end

    def factory_for_seeding_platform_infos
      ::TokyoMetro::Factory::Seed::Api::StationFacility::List::Platform
    end

    def factory_for_seeding_platform_infos_of_each_station
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::List
    end

    def factory_for_seeding_platform_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info
    end

    def factory_for_seeding_platform_info_transfer_list
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::Transfer::List
    end

    def factory_for_seeding_platform_info_transfer_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::Transfer::Info
    end

    def factory_for_seeding_platform_info_barrier_free_list
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::BarrierFree::List
    end

    def factory_for_seeding_platform_info_barrier_free_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::BarrierFree::Info
    end

    def factory_for_seeding_platform_info_surrounding_area_list
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::SurroundingArea::List
    end

    def factory_for_seeding_platform_info_surrounding_area_info
      ::TokyoMetro::Factory::Seed::Api::StationFacility::Info::Platform::Info::SurroundingArea::Info
    end

    # API の情報(generate_instance が true のときの、インスタンスの配列)の各成分をディレクトリ分けするときに使用するキーの設定
    # @return [String or Symbol]
    def method_name_for_determining_dir_when_saving_grouped_infos_and_instance_is_generated
      :same_as
    end

    # API の情報(ハッシュの配列)の各成分をディレクトリ分けするときに使用するキーの設定
    # @return [String or Symbol]
    def key_name_for_determining_dir_when_saving_grouped_infos_and_instance_is_not_generated
      "owl:sameAs"
    end

    # ファイル名を作成する際に削除する部分を示す正規表現
    # @return [Regexp]
    def regexp_indicating_deleted_part_of_value_and_used_when_determine_saved_file_name
      /\Aodpt\.StationFacility\:/
    end

    def db_instance_class
      ::Station::Facility::Info
    end

    def db_instance_class_of_barrier_free_facility_info
      ::BarrierFreeFacility::Info
    end

    def db_instance_class_of_barrier_free_service_detail
      ::BarrierFreeFacility::ServiceDetail::Info
    end

    def db_instance_class_of_barrier_free_service_detail_pattern
      ::BarrierFreeFacility::ServiceDetail::Pattern
    end

    def db_instance_class_of_escalator_direction
      ::BarrierFreeFacility::EscalatorDirection::Info
    end

    def db_instance_class_of_escalator_direction_pattern
      ::BarrierFreeFacility::EscalatorDirection::Pattern
    end

    def db_instance_class_of_toilet_assistant
      ::BarrierFreeFacility::ToiletAssistant::Info
    end

    def db_instance_class_of_platform_info
      ::Station::Facility::Platform::Info
    end

    def db_instance_class_of_platform_transfer_info
      ::Station::Facility::Platform::TransferInfo
    end

    def db_instance_class_of_platform_barrier_free_facility
      ::Station::Facility::Platform::BarrierFreeFacilityInfo
    end

    def db_instance_class_of_platform_surrounding_area
      ::Station::Facility::Platform::SurroundingArea
    end

    # @!endgroup

    private

    # @!group クラスメソッド - データの取得・保存

    # データを保存するディレクトリ
    # @return [String]
    def db_dirname_sub
      "station_facility"
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>

<Product xmlns='http://code.google.com/p/open-zwave/'>

	<!-- COMMAND_CLASS_ALARM AlarmCmd_Get not supported -->
	<!-- CommandClass id="113" action="remove" /> -->

	<!-- COMMAND_CLASS_SENSOR_ALARM not supported -->
	<!-- CommandClass id="156" action="remove" /> -->

	<!-- COMMAND_CLASS_SWITCH_ALL not supported -->
	<!-- CommandClass id="39" action="remove" /> -->

	<!-- Configuration -->
	<CommandClass id="112">

		<Value type="list" genre="config" instance="1" index="1" label="Always on function" value="0" size="1">
			<Help>Once activated, Wall Plug will keep a connected device constantly ON, will stop reacting to alarm frames and B-button push. "Always on" function turns the Plug into a power and energy meter. Also, connected device will not be turned off upon receiving an alarm frame from another Z-Wave device (parameter 31 will be ignored). In "Always on" mode, connected device may be turned off only after user defined power has been exceeded (parameter 3). In such a case, connected device can be turned on again by pushing the B-button or sending a control frame. By default, overload protection is inactive. Default setting: 0</Help>
			<Item label="Inactive" value="0" />
			<Item label="Active" value="1" />
		</Value>

		<Value type="list" genre="config" instance="1" index="2" label="Remember device status after a power failure" value="1" size="1">
			<Help>This parameter determines how the Wall Plug will react in the event of power supply failure (e.g. taking out from the electrical outlet). After the power supply is back on, the Wall Plug can be restored to previous state or remain switched off. This parameter is ignored in Always On mode - the device automatically turns ON after plugging it into the socket. Default setting: 1</Help>
			<Item label="Wall Plug does not memorize its state after a power failure" value="0" />
			<Item label="Wall Plug memorizes its state after a power failure" value="1" />
		</Value>

		<Value type="short" genre="config" instance="1" index="3" label="Overload safety switch" value="0" min="0" max="30000" size="2">
			<Help>This function allows for turning off the controlled device in case of exceeding the defined power. Controlled device will be turned off even if "always on" function is active (parameter 1). Controlled device can be turned back on via B-button or sending a control frame. Available settings: 10 - 30000 (1,0W - 3000,0W step 0,1W). Default setting: 0 (function inactive)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="10" label="High priority power report" value="80" min="1" max="100" size="1">
			<Help>This parameter determines the minimum percentage change in active power that will result in sending power report to the main controller with the highest priority in the Z-Wave network. By default, the Wall Plug immediately sends the power report if the power load changes by 80%. Available settings: 1-99:power change in percent, 100:reports are disabled. Default setting: 80 (80%)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="11" label="Standard power load reporting" value="15" min="1" max="100" size="1">
			<Help>This parameter determines the minimum percentage change in active power that will result in sending power report to the main controller Compared to parameter 10, the maximum number of reports sent is reduced (parameter 12) to 5 in a specified time interval. In addition, the frames are not sent in EXPLORE mode, which prevents overloading the Z-Wave network. By default changes in power load may be reported up to 5 times per 30 seconds, when power load changes by 15%. Available settings: 1-99:power change in percent, 100:reports are disabled. Default setting: 15 (15%)</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="12" label="Power reporting interval" value="30" min="5" max="600" size="2">
			<Help>This parameter defines how frequently standard power reports (parameter 11) will be sent. By default Wall Plug sends up to 5 reports each 30 seconds, provided the power load changes by 15%.  Available setttings: 5-600 (in seconds). Default setting: 30 (s)</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="13" label="Energy reporting threshold" value="10" min="0" max="500" size="2">
			<Help>This parameter specifies the minimum change in energy consumption (in relation to the previously reported), that will result in sending a new report. Available settings: 1-500 (0,01kWh - 5kWh).   0 - energy reports inactive. Default Setting: 10 (0,1 kWh)</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="14" label="Power and energy periodic reports" min="0" max="32400" value="3600" size="2">
			<Help>This parameter defines time period between reports sent when changes in power load have not been recorded or if changes are insignificant (not exceeding values of parameters 20, 21 and 23). By default reports are sent every hour. Available settings: 5 - 32400 (s). 0 - periodic reports inactive. Reports will be sent only in case of power load / energy consumption changes (parameters 20,21,23) or in case of polling. Default setting: 3600</Help>
		</Value>

		<Value type="list" genre="config" instance="1" index="15" label="Measuring energy consumed by the Wall Plug itself" value="0" size="1">
			<Help>This parameter determines whether energy metering should include the amount of energy consumed by the Wall Plug itself. Results are being added to energy consumed by controlled device. Default setting: 0</Help>
			<Item label="Inactive" value="0" />
			<Item label="Active" value="1" />
		</Value>

		<Value type="list" genre="config" instance="1" index="20" label="Control of On/Off (button) association group(2) devices" value="0" size="1">
			<Help>Controlling devices with the B-Button. Control as the Wall Plug:  switching the Wall Plug on  switch the devices on (parameter 24) switching the Wall Plug off  switch the devices off (parameter 24)    This parameter is inactive in Always On mode (parameter 1). Default setting: 0</Help>
			<Item label="Control as the wallplug" value="0" />
			<Item label="Control opposite of wallplug" value="1" />
		</Value>

		<Value type="short" genre="config" instance="1" index="21" label="DOWN value- On/Off(power) association group(3)" value="300" min="0" max="24900" size="2">
			<Help>Lower power threshold, used in parameter 23. Available settings: 0 - 24900 (0,0W - 2490,0W step 0,1W) DOWN value cannot be higher than a value specified in parameter 22. Default setting: 300 (30W)</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="22" label="UP value- On/Off(power) association group(3)" value="500" min="100" max="25000" size="2">
			<Help>Upper power threshold, used in parameter 23. Available settings: 100 - 25000 (10,0W - 2500,0W) UP value cannot be lower than a value specified in parameter 21. Default setting: 500 (50W)</Help>
		</Value>

		<Value type="list" genre="config" instance="1" index="23" label="The response after exceeding defined power values" value="6" size="1">
			<Help>Parameter defines the way 3th association group devices are controlled, depending on the actual measured power(as parameter 21 and 22 settings). Available settings: 1 - turn the associated devices ON, once the power drops below DOWN value (parameter 21), 2 - turn the associated devices OFF, once the power drops below DOWN value (parameter 21),       3 - turn the associated devices ON, once the power rises above UP value (parameter 22), 4 - turn the associated devices OFF, once the power rises above UP value (parameter 22), 5 - combination of 1 and 4. Turn the associated devices ON, once the power drops below DOWN value (parameter 21). Turn the associated devices OFF, once the power rises above UP value (parameter 22).  6 - combination of 2 and 3. Turn the associated devices OFF, once the power drops below DOWN value (parameter 21). Turn the associated devices ON, once the power rises above UP value (parameter 22). Default setting: 6</Help>
			<Item label="Turn the associated devices on,Power below DOWN" value="1" />
			<Item label="Turn the associated devices off,Power below DOWN" value="2" />
			<Item label="Turn the associated devices on,Power above UP" value="3" />
			<Item label="Turn the associated devices off,Power above UP" value="4" />
			<Item label="1 and 4 combine" value="5" />
			<Item label="2 and 3 combined" value="6" />
		</Value>

		<Value type="short" genre="config" instance="1" index="24" label="Switch ON value - On/Off association groups" value="255" min="0" max="255" size="2">
			<Help>The value of BASIC SET command frame sent to the devices associated in On/Off association groups (2, 3). On/Off (Button) association group - in accordance with parameter 20. On/Off (Power) association group - in accordance with parameter 23. Available settings: 0-99 and 255. Default setting: 255</Help>
		</Value>

		<Value type="list" genre="config" instance="1" index="30" label="Active Alarms" value="63" min="1" max="63" size="1">
			<Help>Define Z-Wave network alarms to which the Wall Plug will respond.</Help>
			<Item label="General alarm" value="1" />
			<Item label="Smoke alarm" value="2" />
			<Item label="CO alarm" value="4" />
			<Item label="CO2 alarm" value="8" />
			<Item label="High temperature alarm" value="16" />
			<Item label="Flood alarm" value="32" />
			<Item label="All alarms" value="63" />
		</Value>

		<Value type="short" genre="config" instance="1" index="31" label="Response to alarm frames" value="0" min="0" max="50" size="2">
			<Help>This parameter defines how the Wall Plug will respond to alarms (device's status change). In case of values 1 or 2 the Wall Plug is operating normally and LED ring signals an alarm through time defined in parameter 32 or until the alarm is cancelled. In case of values 5 to 50 the Wall Plug does not report status change, power changes, ignores BASIC SET command frames. After time defined in parameter 32 or after the alarm cancellation, connected device is set to the previous state.. 0- no reaction 1-turn connected device on 2-turn connected device off 5-50(0,5-50,0s step 0,1s)-cyclically change device state with set period. Default setting:0-no reaction</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="32" label="Alarm state duration" value="600" min="1" max="32400" size="2">
			<Help>This parameter specifies the duration of alarm state. If a device sending an alarm frame through the Z-Wave network sets alarm duration as well, this settings are ignored. Available settings 1-32400(s) Default setting: 600</Help>
		</Value>

		<Value type="short" genre="config" instance="1" index="40" label="Power load, which when exceeded, makes the LED ring flash violet." value="25000" min="1000" max="30000" size="2">
			<Help>Function is active only when parameter 41 is set to 0 or 1. Available settings: 1000 - 30000 (100,0W - 3000,0W, step 0,1W). Default setting: 25000 (2500W)</Help>
		</Value>

		<Value type="list" genre="config" instance="1" index="41" label="LED ring illumination colour when controlled device is on" value="1" size="1">
			<Help>0 - Illumination turned off completely, 1 - LED ring illumination colour changes continuously depending on active power, 2 - LED ring illumination colour changes in steps, depending on active power,  3 - White illumination, 4 - Red illumination, 5 - Green illumination, 6 - Blue illumination, 7 - Yellow illumination, 8 - Cyan illumination, 9 - Magenta illumination. Default setting: 1</Help>
			<Item label="illumination turned off completely" value="0" />
			<Item label="Colour changes continuously depending on active power" value="1" />
			<Item label="Colour changes in steps depending on active power" value="2" />
			<Item label="White illumination" value="3" />
			<Item label="Red illumination" value="4" />
			<Item label="Green illumination" value="5" />
			<Item label="Blue illumination" value="6" />
			<Item label="Yellow illumination" value="7" />
			<Item label="Cyan illumination" value="8" />
			<Item label="Magenta illumination" value="9" />
		</Value>

		<Value type="list" genre="config" instance="1" index="42" label="LED ring illumination colour when controlled device is off" value="0" size="1">
			<Help>0 - Illumination turned off completely, 1 - LED ring is illuminated with a colour corresponding to the last measured power, before the controlled device was turned off, 3 - White illumination, 4 - Red illumination, 5 - Green illumination, 6 - Blue illumination, 7 - Yellow illumination, 8 - Cyan illumination, 9 - Magenta illumination. Default setting: 0</Help>
			<Item label="illumination turned off completely" value="0" />
			<Item label="LED ring is illuminated with a colour corresponding to the last measured power" value="1" />
			<Item label="White illumination" value="3" />
			<Item label="Red illumination" value="4" />
			<Item label="Green illumination" value="5" />
			<Item label="Blue illumination" value="6" />
			<Item label="Yellow illumination" value="7" />
			<Item label="Cyan illumination" value="8" />
			<Item label="Magenta illumination" value="9" />

		</Value>

		<Value type="list" genre="config" instance="1" index="43" label="LED ring illumination colour at the Z-Wave network alarm detection" value="2" size="1">
			<Help>0 - illumination turned off completely, 1 - No change in colour. LED ring illumination colour determined by parameters 41 or 42 settings, 2 - LED ring flashes red/blue/white (default), 3 - White illumination, 4 - Red illumination, 5 - Green illumination, 6 - Blue illumination, 7 - Yellow illumination, 8 - Cyan illumination, 9 - Magenta illumination. Default setting: 2</Help>
			<Item label="illumination turned off completely" value="0" />
			<Item label="No change in colour" value="1" />
			<Item label="LED ring flashes red / blue / white" value="2" />
			<Item label="White illumination" value="3" />
			<Item label="Red illumination" value="4" />
			<Item label="Green illumination" value="5" />
			<Item label="Blue illumination" value="6" />
			<Item label="Yellow illumination" value="7" />
			<Item label="Cyan illumination" value="8" />
			<Item label="Magenta illumination" value="9" />
		</Value>

		<Value type="list" genre="config" instance="1" index="50" label="Associations in Z-Wave network security mode" size="1" value="3">
			<Help>This parameter defines how commands are sent in specified association groups: as secure or non-secure. Parameter is active only in Z-Wave network security mode. This parameter does not apply to 1st Lifeline group. Available settings: 0-3: 0 - none of the groups are  sent as secure; 1 - 2nd group sent as secure; 2 - 3rd group sent as secure; 3 - 2nd and 3rd group sent as secure; Default setting: 3</Help>
			<Item label="none of the groups sent as secure" value="0" />
			<Item label="2nd group send as secure" value="1" />
			<Item label="3rd group send as secure" value="2" />
			<Item label="2nd and 3rd group send as secure" value="3" />
		</Value>

	</CommandClass>

	<!-- Association Groups -->
	<CommandClass id="133">
		<Associations num_groups="3">
			<Group index="1" max_associations="1" label="Lifeline"/>
			<Group index="2" max_associations="10" label="On/Off (button)"  />
			<Group index="3" max_associations="10" label="On/Off (power)"/>
		</Associations>
	</CommandClass>

	<!-- COMMAND_CLASS_BASIC supported -->
	<CommandClass id="32" action="add" request_flags="5" />

</Product>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
            "http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>enable_if</TITLE>

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="Microsoft FrontPage 5.0">

enable_if

Copyright 2003 Jaakko Järvi, Jeremiah Willcock, Andrew Lumsdaine.

Copyright 2011 Matt Calabrese.

1  Introduction

The <TT>enable_if</TT> family of templates is a set of tools to allow a function template or a class template specialization
to include or exclude itself from a set of matching functions or specializations
based on properties of its template arguments.
For example, one can define function templates that
are only enabled for, and thus only match, an arbitrary set of types
defined by a traits class. The <TT>enable_if</TT> templates can also be
applied to enable class template specializations. Applications of
<TT>enable_if</TT> are discussed in length
in [1] and [2].

1.1  Synopsis

namespace boost {
  template <class Cond, class T = void> struct enable_if;
  template <class Cond, class T = void> struct disable_if;
  template <class Cond, class T> struct lazy_enable_if;
  template <class Cond, class T> struct lazy_disable_if;

  template <bool B, class T = void> struct enable_if_c;
  template <bool B, class T = void> struct disable_if_c;
  template <bool B, class T> struct lazy_enable_if_c;
  template <bool B, class T> struct lazy_disable_if_c;
}

1.2  Background

Sensible operation of template function overloading in C++ relies
on the SFINAE (substitution-failure-is-not-an-error)
principle [3]: if an invalid argument
or return type is formed during the instantiation of a function
template, the instantiation is removed from the overload resolution
set instead of causing a compilation error. The following example,
taken from [1],
demonstrates why this is important:

int negate(int i) { return -i; }

template <class F>
typename F::result_type negate(const F& f) { return -f(); }

Suppose the compiler encounters the call <TT>negate(1)</TT>. The first
definition is obviously a better match, but the compiler must
nevertheless consider (and instantiate the prototypes) of both
definitions to find this out. Instantiating the latter definition with
<TT>F</TT> as <TT>int</TT> would result in:

int::result_type negate(const int&);

where the return type is invalid. If this were an error, adding an unrelated function template
(that was never called) could break otherwise valid code.
Due to the SFINAE principle the above example is not, however, erroneous.
The latter definition of <TT>negate</TT> is simply removed from the overload resolution set.

The <TT>enable_if</TT> templates are tools for controlled creation of the SFINAE
conditions.

2  The <TT>enable_if</TT> templates

The names of the <TT>enable_if</TT> templates have three parts: an optional <TT>lazy_</TT> tag,
either <TT>enable_if</TT> or <TT>disable_if</TT>, and an optional <TT>_c</TT> tag.
All eight combinations of these parts are supported.
The meaning of the <TT>lazy_</TT> tag is described in Section 3.3.
The second part of the name indicates whether a true condition argument should
enable or disable the current overload.
The third part of the name indicates whether the condition argument is a <TT>bool</TT> value
(<TT>_c</TT> suffix), or a type containing a static <TT>bool</TT> constant named <TT>value</TT> (no suffix).
The latter version interoperates with Boost.MPL.

The definitions of <TT>enable_if_c</TT> and <TT>enable_if</TT> are as follows (we use <TT>enable_if</TT> templates
unqualified but they are in the <TT>boost</TT> namespace).

template <bool B, class T = void>
struct enable_if_c {
  typedef T type;
};

template <class T>
struct enable_if_c<false, T> {};

template <class Cond, class T = void>
struct enable_if : public enable_if_c<Cond::value, T> {};

An instantiation of the <TT>enable_if_c</TT> template with the parameter
<TT>B</TT> as <TT>true</TT> contains a member type <TT>type</TT>, defined
to be <TT>T</TT>. If <TT>B</TT> is
<TT>false</TT>, no such member is defined. Thus
<TT>enable_if_c<B, T>::type</TT> is either a valid or an invalid type
expression, depending on the value of <TT>B</TT>.
When valid, <TT>enable_if_c<B, T>::type</TT> equals <TT>T</TT>.
The <TT>enable_if_c</TT> template can thus be used for controlling when functions are considered for
overload resolution and when they are not.
For example, the following function is defined for all arithmetic types (according to the
classification of the Boost type_traits library):

template <class T>
typename enable_if_c<boost::is_arithmetic<T>::value, T>::type
foo(T t) { return t; }

The <TT>disable_if_c</TT> template is provided as well, and has the
same functionality as <TT>enable_if_c</TT> except for the negated condition. The following
function is enabled for all non-arithmetic types.

template <class T>
typename disable_if_c<boost::is_arithmetic<T>::value, T>::type
bar(T t) { return t; }

For easier syntax in some cases and interoperation with Boost.MPL we provide versions of
the <TT>enable_if</TT> templates taking any type with a <TT>bool</TT> member constant named
<TT>value</TT> as the condition argument.
The MPL <TT>bool_</TT>, <TT>and_</TT>, <TT>or_</TT>, and <TT>not_</TT> templates are likely to be
useful for creating such types. Also, the traits classes in the Boost.Type_traits library
follow this convention.
For example, the above example function <TT>foo</TT> can be alternatively written as:

template <class T>
typename enable_if<boost::is_arithmetic<T>, T>::type
foo(T t) { return t; }

3  Using <TT>enable_if</TT>

The <TT>enable_if</TT> templates are defined in
<TT>boost/utility/enable_if.hpp</TT>, which is included by <TT>boost/utility.hpp</TT>.

With respect to function templates, <TT>enable_if</TT> can be used in multiple different ways:

As the return type of an instantiatied function

As an extra parameter of an instantiated function

As an extra template parameter (useful only in a compiler that supports C++0x default
arguments for function template parameters, see Enabling function
templates in C++0x for details)

In the previous section, the return type form of <TT>enable_if</TT> was shown. As an example
of using the form of <TT>enable_if</TT> that works via an extra function parameter, the
<TT>foo</TT> function in the previous section could also be written
as:

template <class T>
T foo(T t, typename enable_if<boost::is_arithmetic<T> >::type* dummy = 0);

Hence, an extra parameter of type <TT>void*</TT> is added, but it is given
a default value to keep the parameter hidden from client code.
Note that the second template argument was not given to <TT>enable_if</TT>, as the default
<TT>void</TT> gives the desired behavior.

Which way to write the enabler is largely a matter of taste, but for certain functions, only a
subset of the options is possible:

Many operators have a fixed number of arguments, thus <TT>enable_if</TT> must be used either in the
return type or in an extra template parameter.

Functions that have a variadic parameter list must use either the return type form or an extra
template parameter.

Constructors do not have a return type so you must use either an extra function parameter or an
extra template parameter.

Constructors that have a variadic parameter list must an extra template parameter.

Conversion operators can only be written with an extra template parameter.

3.1  Enabling function templates in C++0x

In a compiler which supports C++0x default arguments for function template parameters, you can
enable and disable function templates by adding an additional template parameter. This approach
works in all situations where you would use either the return type form of <TT>enable_if</TT> or
the function parameter form, including operators, constructors, variadic function templates, and
even overloaded conversion operations.

As an example:

#include <boost/type_traits/is_arithmetic.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/utility/enable_if.hpp>

class test
{
public:
  // A constructor that works for any argument list of size 10
  template< class... T
          , typename boost::enable_if_c< sizeof...( T ) == 10, int >::type = 0
          >
  test( T&&... );

  // A conversion operation that can convert to any arithmetic type
  template< class T
          , typename boost::enable_if< boost::is_arithmetic< T >, int >::type = 0
          >
  operator T() const;

  // A conversion operation that can convert to any pointer type
  template< class T
          , typename boost::enable_if< boost::is_pointer< T >, int >::type = 0
          >
  operator T() const;
};

int main()
{
  // Works
  test test_( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );

  // Fails as expected
  test fail_construction( 1, 2, 3, 4, 5 );

  // Works by calling the conversion operator enabled for arithmetic types
  int arithmetic_object = test_;

  // Works by calling the conversion operator enabled for pointer types
  int* pointer_object = test_;

  // Fails as expected
  struct {} fail_conversion = test_;
}

3.2  Enabling template class specializations

Class template specializations can be enabled or disabled with <TT>enable_if</TT>.
One extra template parameter needs to be added for the enabler expressions.
This parameter has the default value <TT>void</TT>.
For example:

template <class T, class Enable = void>
class A { ... };

template <class T>
class A<T, typename enable_if<is_integral<T> >::type> { ... };

template <class T>
class A<T, typename enable_if<is_float<T> >::type> { ... };

Instantiating <TT>A</TT> with any integral type matches the first specialization,
whereas any floating point type matches the second one. All other types
match the primary template.
The condition can be any compile-time boolean expression that depends on the
template arguments of the class.
Note that again, the second argument to <TT>enable_if</TT> is not needed; the default (<TT>void</TT>)
is the correct value.

3.3  Overlapping enabler conditions

Once the compiler has examined the enabling conditions and included the
function into the overload resolution set, normal C++ overload resolution
rules are used to select the best matching function.
In particular, there is no ordering between enabling conditions.
Function templates with enabling conditions that are not mutually exclusive can
lead to ambiguities. For example:

template <class T>
typename enable_if<boost::is_integral<T>, void>::type
foo(T t) {}

template <class T>
typename enable_if<boost::is_arithmetic<T>, void>::type
foo(T t) {}

All integral types are also arithmetic. Therefore, say, for the call <TT>foo(1)</TT>,
both conditions are true and both functions are thus in the overload resolution set.
They are both equally good matches and thus ambiguous.
Of course, more than one enabling condition can be simultaneously true as long as
other arguments disambiguate the functions.

The above discussion applies to using <TT>enable_if</TT> in class template
partial specializations as well.

3.4  Lazy <TT>enable_if</TT>

In some cases it is necessary to avoid instantiating part of a
function signature unless an enabling condition is true. For example:

template <class T, class U> class mult_traits;

template <class T, class U>
typename enable_if<is_multipliable<T, U>, typename mult_traits<T, U>::type>::type
operator*(const T& t, const U& u) { ... }

Assume the class template <TT>mult_traits</TT> is a traits class defining
the resulting type of a multiplication operator. The <TT>is_multipliable</TT> traits
class specifies for which types to enable the operator. Whenever
<TT>is_multipliable<A, B>::value</TT> is <TT>true</TT> for some types <TT>A</TT> and <TT>B</TT>,
then <TT>mult_traits<A, B>::type</TT> is defined.

Now, trying to invoke (some other overload) of <TT>operator*</TT> with, say, operand types <TT>C</TT> and <TT>D</TT>
for which <TT>is_multipliable<C, D>::value</TT> is <TT>false</TT>
and <TT>mult_traits<C, D>::type</TT> is not defined is an error on some compilers.
The SFINAE principle is not applied because
the invalid type occurs as an argument to another template. The <TT>lazy_enable_if</TT>
and <TT>lazy_disable_if</TT> templates (and their <TT>_c</TT> versions) can be used in such
situations:

template<class T, class U>
typename lazy_enable_if<is_multipliable<T, U>, mult_traits<T, U> >::type
operator*(const T& t, const U& u) { ... }

The second argument of <TT>lazy_enable_if</TT> must be a class type
that defines a nested type named <TT>type</TT> whenever the first
parameter (the condition) is true.

Note

Referring to one member type or static constant in a traits class
causes all of the members (type and static constant) of that
specialization to be instantiated. Therefore, if your traits classes
can sometimes contain invalid types, you should use two distinct
templates for describing the conditions and the type mappings. In the
above example, <TT>is_multipliable<T, U>::value</TT> defines when
<TT>mult_traits<T, U>::type</TT> is valid.

3.5  Compiler workarounds

Some compilers flag functions as ambiguous if the only distinguishing factor is a different
condition in an enabler (even though the functions could never be ambiguous). For example,
some compilers (e.g. GCC 3.2) diagnose the following two functions as ambiguous:

template <class T>
typename enable_if<boost::is_arithmetic<T>, T>::type
foo(T t);

template <class T>
typename disable_if<boost::is_arithmetic<T>, T>::type
foo(T t);

Two workarounds can be applied:

Use an extra dummy parameter which disambiguates the functions. Use a default value for
it to hide the parameter from the caller. For example:

template <int> struct dummy { dummy(int) {} };

template <class T>
typename enable_if<boost::is_arithmetic<T>, T>::type
foo(T t, dummy<0> = 0);

template <class T>
typename disable_if<boost::is_arithmetic<T>, T>::type
foo(T t, dummy<1> = 0);

Define the functions in different namespaces and bring them into a common
namespace with <TT>using</TT> declarations:

namespace A {
  template <class T>
  typename enable_if<boost::is_arithmetic<T>, T>::type
  foo(T t);
}

namespace B {
  template <class T>
  typename disable_if<boost::is_arithmetic<T>, T>::type
  foo(T t);
}

using A::foo;
using B::foo;

Note that the second workaround above cannot be used for member
templates. On the other hand, operators do not accept extra arguments,
which makes the first workaround unusable. As the net effect,
neither of the workarounds are of assistance for templated operators that
need to be defined as member functions (assignment and
subscript operators).

4  Acknowledgements

We are grateful to Howard Hinnant, Jason Shirk, Paul Mensonides, and Richard
Smith whose findings have influenced the library.

References

[1]

Jaakko Järvi, Jeremiah Willcock, Howard Hinnant, and Andrew Lumsdaine.
Function overloading based on arbitrary properties of types.
C/C++ Users Journal, 21(6):25--32, June 2003.

[2]

Jaakko Järvi, Jeremiah Willcock, and Andrew Lumsdaine.
Concept-controlled polymorphism.
In Frank Pfennig and Yannis Smaragdakis, editors, Generative
 Programming and Component Engineering, volume 2830 of LNCS, pages
 228--244. Springer Verlag, September 2003.

[3]

David Vandevoorde and Nicolai M. Josuttis.
C++ Templates: The Complete Guide.
Addison-Wesley, 2002.

Copyright Jaakko Järvi*, Jeremiah Willcock*, Andrew Lumsdaine*, Matt Calabrese

{jajarvi|jewillco|lums}@osl.iu.edu, rivorus@gmail.com

*Indiana University

Open Systems Lab

Use, modification and distribution are subject to the
Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt
or copy at
   http://www.boost.org/LICENSE_1_0.txt
).

This document was translated from LATEX by
HEVEA.


text:
import maya
maya.utils.loadStringResourcesForModule(__name__)

import maya.api.OpenMaya as OpenMaya

kNameToNodeTypeMismatch = maya.stringTable['y_utils.kNameToNodeTypeMismatch' ]
kAmbiguousName = maya.stringTable['y_utils.kAmbiguousName' ]

def _selectPlug(name):
    sl = OpenMaya.MSelectionList()
    try:
        sl.add(name)
    except RuntimeError:
        # not found
        return None
    if sl.length() > 1:
        # found multiple results (ambiguous)
        raise RuntimeError(kAmbiguousName % name.split('.',1)[0])
    plg = None
    try:
        plg = sl.getPlug(0)
    except TypeError:
        # not a plug
        return None
    if plg.isElement and name.find('[') == -1:
        # Hack because MSelectionList returns a plug over the first element of
        # a array of plug when no logical index is given
        return None
    return plg

def nodeToLongName(node):
    """Returns the full name of the node,
    i.e. the absolute path for dag nodes and name for dependency (non-dag) nodes."""
    return OpenMaya.MFnDagNode(node).fullPathName() if node.hasFn(OpenMaya.MFn.kDagNode) else \
           OpenMaya.MFnDependencyNode(node).name()

def nodeToShortName(node):
    """Returns the minimum name string necessary to uniquely identify the node."""
    return OpenMaya.MFnDagNode(node).partialPathName() if node.hasFn(OpenMaya.MFn.kDagNode) else \
           OpenMaya.MFnDependencyNode(node).name()

def nameToNode(name):
    """Returns the MObject matching given name or None if not found.
       Raises RuntimeError if name is ambiguous."""
    plg = _selectPlug(name + ".message")
    return plg.node() if plg else None

def nameToDagPath(name):
    """Returns the MDagPath matching given name or None if not found.
       Raises RuntimeError if name is ambiguous."""
    plg = _selectPlug(name + ".message")
    if not (plg and plg.node().hasFn(OpenMaya.MFn.kDagNode)):
        return None
    selection = OpenMaya.MSelectionList()
    selection.add(name)
    return selection.getDagPath(0)

def nameToPlug(name):
    """Returns the MPlug matching given name or None if not found.
       Raises RuntimeError if name is ambiguous."""
    plg = _selectPlug(name)
    if plg is None:
        return None
    # This final check is a hack to detect false positive returned by the selection list
    # because maya "helps" us for example by returning a plug to pSphereShape1.smoothLevel (shape)
    # when we ask for pSphere1.smoothLevel (group) (which doesn't exist in the group...)
    endName1 = name.split('.',1)[0].split('|')[-1]
    endName2 = OpenMaya.MFnDependencyNode(plg.node()).name().split('|')[-1]
    return plg if endName1 == endName2 else None

def findPlug(node, attr):
    """ Return the MPlug corresponding to attr on argument node or None if not found.
    The node argument can be an MObject or a node string name.
    The attr argument can be an MObject or a attr string name.
    Raises RuntimeError if plug is ambiguous."""
    if isinstance(node, basestring):
        attrName = attr if isinstance(attr, basestring) else OpenMaya.MFnAttribute(attr).name
        return nameToPlug(node+"."+attrName)

    if isinstance(attr, OpenMaya.MObject):
        plg = OpenMaya.MPlug(node, attr)
    else:
        if attr.find('[') != -1:
            # fn.findPlug doesn't work for elements of arrays
            # use a selection list to find the plug
            return nameToPlug(nodeToLongName(node)+"."+attr)
        if attr.find('.') != -1:
            # fn.findPlug doesn't work for compound paths
            # use last name in compound path as it is unique
            attr = attr.split('.')[-1]

        fn = OpenMaya.MFnDependencyNode(node)
        plg = fn.findPlug(attr, True) if fn.hasAttribute(attr) else None

    if not plg or plg.isNull or plg.isArray:
        # an array of plug is not a plug
        return None

    if plg.isChild and plg.parent().isElement and plg.parent().logicalIndex() < 0:
        # MAYA-66726: Plugs satisfying this should not be valid plugs
        # Example: "miDefaultOptions.name" satisfies this and is said to be a valid plug
        # its parent is miDefaultOptions.stringOptions[-1] which is an element with invalid logical index...
        return None

    return plg

def removeDuplicates(seq):
    """ Removes all duplicated elements from a list.
    Note that order is not preserved."""
    return list(set(seq))

def getSubClasses(classType):
    cl  = [ classType ]
    for c in classType.__subclasses__():
        cl += getSubClasses(c)
    return cl

def isNodeInstance(node, nodeType):
    return isinstance(OpenMaya.MFnDependencyNode(node).userNode(), nodeType)
# ===========================================================================
# Copyright 2016 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license
# agreement provided at the time of installation or download, or which
# otherwise accompanies this software in either electronic or hard copy form.
# ===========================================================================


text:
namespace EntityFrameworkBenchmarks.Data
{
    public sealed class SysObject
    {
        public string Name { get; set; }
        public int ObjectId { get; set; }
        public string Type { get; set; }
        public string TypeDescription { get; set; }
    }
}


text:
animals = ['bear', 'python', 'peacock']
print(len(animals))
print(animals[0])
print(animals[len(animals)-1])


text:
post_title: dcos node log
menu_order: 5
---

# Description
Print the Mesos logs for the leading master node, agent nodes, or both.

# Usage

```bash
dcos node log [OPTION]
```

# Options

| Name, shorthand | Default | Description |
|---------|-------------|-------------|
| `--leader`   |             |  The leading master. |
| `--follow`   |             |  Dynamically update the log. |
| `--lines=N`   |     10      |  Print the last N lines. |
| `--master`   |             |  This option is deprecated and is replaced by `--leader`. |
| `--mesos-id=<mesos-id>`   |             | The agent ID of a node. |
| `--slave=<agent-id>`   |             | This option is deprecated and is replaced by `--mesos-id`. |

# Parent command

| Command | Description |
|---------|-------------|
| [dcos node](/docs/1.9/cli/command-reference/dcos-node/) | View DC/OS node information. |

<!-- # Examples -->


text:
import * as React from 'react';
import autobind from 'autobind-decorator';
import classnames from 'classnames';
import clone from 'clone';
import * as templating from '../../../templating';
import type { NunjucksParsedTag, NunjucksParsedTagArg } from '../../../templating/utils';
import * as templateUtils from '../../../templating/utils';
import * as db from '../../../common/database';
import * as models from '../../../models';
import HelpTooltip from '../help-tooltip';
import { delay, fnOrString } from '../../../common/misc';
import type { BaseModel } from '../../../models/index';
import type { Workspace } from '../../../models/workspace';
import type { PluginArgumentEnumOption } from '../../../templating/extensions/index';
import { Dropdown, DropdownButton, DropdownDivider, DropdownItem } from '../base/dropdown/index';
import FileInputButton from '../base/file-input-button';

type Props = {
  handleRender: Function,
  handleGetRenderContext: Function,
  defaultValue: string,
  onChange: Function,
  workspace: Workspace,
};

type State = {
  activeTagData: NunjucksParsedTag | null,
  activeTagDefinition: NunjucksParsedTag | null,
  tagDefinitions: Array<Object>,
  loadingDocs: boolean,
  allDocs: { [string]: Array<BaseModel> },
  rendering: boolean,
  preview: string,
  error: string,
  variables: Array<{ name: string, value: string }>,
};

@autobind
class TagEditor extends React.PureComponent<Props, State> {
  _select: ?HTMLSelectElement;

  constructor(props: Props) {
    super(props);

    this.state = {
      activeTagData: null,
      activeTagDefinition: null,
      tagDefinitions: [],
      loadingDocs: false,
      allDocs: {},
      rendering: true,
      preview: '',
      error: '',
      variables: [],
    };
  }

  async load() {
    const activeTagData = templateUtils.tokenizeTag(this.props.defaultValue);

    const tagDefinitions = await templating.getTagDefinitions();
    const activeTagDefinition: NunjucksParsedTag | null =
      tagDefinitions.find(d => d.name === activeTagData.name) || null;

    // Edit tags raw that we don't know about
    if (!activeTagDefinition) {
      activeTagData.rawValue = this.props.defaultValue;
    }

    await Promise.all([
      this._refreshModels(this.props.workspace),
      this._update(tagDefinitions, activeTagDefinition, activeTagData, true),
    ]);
  }

  async loadVariables() {
    const context = await this.props.handleGetRenderContext();
    const variables = context.keys;
    this.setState({ variables });
  }

  componentDidMount() {
    this.load();
    this.loadVariables();
  }

  componentWillReceiveProps(nextProps: Props) {
    const { workspace } = nextProps;

    if (this.props.workspace._id !== workspace._id) {
      this._refreshModels(workspace);
    }
  }

  async _handleRefresh() {
    await this._update(
      this.state.tagDefinitions,
      this.state.activeTagDefinition,
      this.state.activeTagData,
      true,
    );
  }

  async _refreshModels(workspace: Workspace) {
    this.setState({ loadingDocs: true });

    const allDocs = {};
    for (const type of models.types()) {
      allDocs[type] = [];
    }

    for (const doc of await db.withDescendants(workspace, models.request.type)) {
      allDocs[doc.type].push(doc);
    }

    this.setState({ allDocs, loadingDocs: false });
  }

  async _updateArg(
    argValue: string | number | boolean,
    argIndex: number,
    forceNewType: string | null = null,
    patch: Object = {},
  ) {
    const { tagDefinitions, activeTagData, activeTagDefinition } = this.state;

    if (!activeTagData) {
      console.warn('No active tag data to update', { state: this.state });
      return;
    }

    if (!activeTagDefinition) {
      console.warn('No active tag definition to update', { state: this.state });
      return;
    }

    // Fix strings
    if (typeof argValue === 'string') {
      argValue = argValue.replace(/\\/g, '\\\\');
    }

    // Ensure all arguments exist
    const defaultArgs = TagEditor._getDefaultTagData(activeTagDefinition).args;
    for (let i = 0; i < defaultArgs.length; i++) {
      if (activeTagData.args[i]) {
        continue;
      }
      activeTagData.args[i] = defaultArgs[i];
    }

    const tagData = clone(activeTagData);
    const argData: NunjucksParsedTagArg = tagData.args[argIndex];

    if (!argData) {
      // Should never happen
      console.warn('Could not find arg data to update', { tagData, argIndex });
      return;
    }

    // Update it
    argData.value = argValue;

    // Update type if we need to
    if (forceNewType) {
      // Ugh, what a hack (because it's enum)
      Object.assign((argData: any), { type: forceNewType }, patch);
    }

    await this._update(tagDefinitions, activeTagDefinition, tagData, false);
  }

  async _handleChangeArgVariable(options: { argIndex: number, variable: boolean }) {
    const { variable, argIndex } = options;
    const { activeTagData, activeTagDefinition, variables } = this.state;

    if (!activeTagData || !activeTagDefinition) {
      console.warn('Failed to change arg variable', { state: this.state });
      return;
    }

    const argData = activeTagData.args[argIndex];
    const argDef = activeTagDefinition.args[argIndex];
    const existingValue = argData ? argData.value : '';

    if (variable) {
      const variable = variables.find(v => v.value === existingValue);
      const firstVariable = variables.length ? variables[0].name : '';
      const value = variable ? variable.name : firstVariable;
      return this._updateArg(value || 'my_variable', argIndex, 'variable');
    } else {
      const initialType = argDef ? argDef.type : 'string';
      const variable = variables.find(v => v.name === existingValue);
      const value = variable ? variable.value : '';
      return this._updateArg(value, argIndex, initialType, { quotedBy: "'" });
    }
  }

  _handleChangeFile(path: string, argIndex: number) {
    return this._updateArg(path, argIndex);
  }

  _handleChange(e: SyntheticEvent<HTMLInputElement>) {
    const parent = e.currentTarget.parentNode;
    let argIndex = -1;
    if (parent instanceof HTMLElement) {
      const index = parent && parent.getAttribute('data-arg-index');
      argIndex = typeof index === 'string' ? parseInt(index, 10) : -1;
    }

    // Handle special types
    if (e.currentTarget.getAttribute('data-encoding') === 'base64') {
      return this._updateArg(
        templateUtils.encodeEncoding(e.currentTarget.value, 'base64'),
        argIndex,
      );
    }

    // Handle normal types
    if (e.currentTarget.type === 'number') {
      return this._updateArg(parseFloat(e.currentTarget.value), argIndex);
    } else if (e.currentTarget.type === 'checkbox') {
      return this._updateArg(e.currentTarget.checked, argIndex);
    } else {
      return this._updateArg(e.currentTarget.value, argIndex);
    }
  }

  _handleChangeCustomArg(e: SyntheticEvent<HTMLInputElement>) {
    const { tagDefinitions, activeTagData, activeTagDefinition } = this.state;

    const tagData: NunjucksParsedTag | null = clone(activeTagData);

    if (tagData) {
      tagData.rawValue = e.currentTarget.value;
    }

    this._update(tagDefinitions, activeTagDefinition, tagData, false);
  }

  async _handleChangeTag(e: SyntheticEvent<HTMLInputElement>) {
    const name = e.currentTarget.value;
    const tagDefinitions = await templating.getTagDefinitions();
    const tagDefinition = tagDefinitions.find(d => d.name === name) || null;
    this._update(this.state.tagDefinitions, tagDefinition, null, false);
  }

  _setSelectRef(n: ?HTMLSelectElement) {
    this._select = n;

    // Let it render, then focus the input
    setTimeout(() => {
      if (this._select instanceof HTMLSelectElement) {
        this._select.focus();
      }
    }, 100);
  }

  static _getDefaultTagData(tagDefinition: NunjucksParsedTag): NunjucksParsedTag {
    const defaultFill: string = templateUtils.getDefaultFill(
      tagDefinition.name,
      tagDefinition.args,
    );

    return templateUtils.tokenizeTag(defaultFill);
  }

  async _update(
    tagDefinitions: Array<NunjucksParsedTag>,
    tagDefinition: NunjucksParsedTag | null,
    tagData: NunjucksParsedTag | null,
    noCallback: boolean = false,
  ) {
    const { handleRender } = this.props;
    this.setState({ rendering: true });

    // Start render loader
    const start = Date.now();
    this.setState({ rendering: true });

    let preview = '';
    let error = '';

    let activeTagData: NunjucksParsedTag | null = tagData;
    if (!activeTagData && tagDefinition) {
      activeTagData = TagEditor._getDefaultTagData(tagDefinition);
    } else if (!activeTagData && !tagDefinition && this.state.activeTagData) {
      activeTagData = {
        name: 'custom',
        displayName: 'Custom',
        args: [],
        rawValue: templateUtils.unTokenizeTag(this.state.activeTagData),
      };
    }

    let template;
    if (activeTagData) {
      try {
        template =
          typeof activeTagData.rawValue === 'string'
            ? activeTagData.rawValue
            : templateUtils.unTokenizeTag(activeTagData);
        preview = await handleRender(template);
      } catch (err) {
        error = err.message;
      }
    }

    this.setState({
      tagDefinitions,
      activeTagData,
      error,
      activeTagDefinition: tagDefinition,
    });

    // Call the callback if we need to
    if (!noCallback) {
      this.props.onChange(template);
    }

    // Make rendering take at least this long so we can see a spinner
    await delay(300 - (Date.now() - start));
    this.setState({
      rendering: false,
      preview,
    });
  }

  renderArgVariable(path: string) {
    const { variables } = this.state;

    if (variables.length === 0) {
      return (
        <select disabled>
          <option>-- No Environment Variables Found --</option>
        </select>
      );
    }

    return (
      <select value={path || ''} onChange={this._handleChange}>
        <option key="n/a" value="NO_VARIABLE">
          -- Select Variable --
        </option>
        {variables.map((v, i) => (
          <option key={`${i}::${v.name}`} value={v.name}>
            {v.name}
          </option>
        ))}
      </select>
    );
  }

  renderArgString(value: string, placeholder: string, encoding: string) {
    return (
      <input
        type="text"
        defaultValue={value || ''}
        placeholder={placeholder}
        onChange={this._handleChange}
        data-encoding={encoding || 'utf8'}
      />
    );
  }

  renderArgNumber(value: string, placeholder: string) {
    return (
      <input
        type="number"
        defaultValue={value || '0'}
        placeholder={placeholder}
        onChange={this._handleChange}
      />
    );
  }

  renderArgBoolean(checked: boolean) {
    return <input type="checkbox" checked={checked} onChange={this._handleChange} />;
  }

  renderArgFile(
    value: string,
    argIndex: number,
    itemTypes?: Array<string>,
    extensions?: Array<string>,
  ) {
    return (
      <FileInputButton
        showFileIcon
        showFileName
        className="btn btn--clicky btn--super-compact"
        onChange={path => this._handleChangeFile(path, argIndex)}
        path={value}
        itemtypes={itemTypes}
        extensions={extensions}
      />
    );
  }

  renderArgEnum(value: string, options: Array<PluginArgumentEnumOption>) {
    const argDatas = this.state.activeTagData ? this.state.activeTagData.args : [];
    return (
      <select value={value} onChange={this._handleChange}>
        {options.map(option => {
          let label: string;
          const { description } = option;
          if (description) {
            label = `${fnOrString(option.displayName, argDatas)} – ${description}`;
          } else {
            label = fnOrString(option.displayName, argDatas);
          }

          return (
            <option key={option.value.toString()} value={option.value}>
              {label}
            </option>
          );
        })}
      </select>
    );
  }

  resolveRequestGroupPrefix(requestGroupId: string, allRequestGroups: Array<any>): string {
    let prefix = '';
    let reqGroup: any;

    do {
      // Get prefix from inner most request group.
      reqGroup = allRequestGroups.find(rg => rg._id === requestGroupId);
      if (reqGroup == null) {
        break;
      }
      let name = typeof reqGroup.name === 'string' ? reqGroup.name : '';
      prefix = `[${name}] ` + prefix;
      requestGroupId = reqGroup.parentId;
    } while (true);

    return prefix;
  }

  renderArgModel(value: string, modelType: string) {
    const { allDocs, loadingDocs } = this.state;
    const docs = allDocs[modelType] || [];
    const id = value || 'n/a';

    if (loadingDocs) {
      return (
        <select disabled={loadingDocs}>
          <option>Loading...</option>
        </select>
      );
    }

    return (
      <select value={id} onChange={this._handleChange}>
        <option value="n/a">-- Select Item --</option>
        {docs.map((doc: any) => {
          let namePrefix = null;

          // Show paren't folder with name if it's a request
          if (doc.type === models.request.type) {
            const requests = allDocs[models.request.type] || [];
            const request: any = requests.find(r => r._id === doc._id);
            const method = request && typeof request.method === 'string' ? request.method : 'GET';
            const parentId = request ? request.parentId : 'n/a';
            const allRequestGroups = allDocs[models.requestGroup.type] || [];
            const requestGroupPrefix = this.resolveRequestGroupPrefix(parentId, allRequestGroups);
            namePrefix = `${requestGroupPrefix + method} `;
          }

          const docName = typeof doc.name === 'string' ? doc.name : 'Unknown Request';
          return (
            <option key={doc._id} value={doc._id}>
              {namePrefix}
              {docName}
            </option>
          );
        })}
      </select>
    );
  }

  renderArg(
    argDefinition: NunjucksParsedTagArg,
    argDatas: Array<NunjucksParsedTagArg>,
    argIndex: number,
  ) {
    // Decide whether or not to show it
    if (typeof argDefinition.hide === 'function' && argDefinition.hide(argDatas)) {
      return null;
    }

    let argData: NunjucksParsedTagArg;
    if (argIndex < argDatas.length) {
      argData = argDatas[argIndex];
    } else if (this.state.activeTagDefinition) {
      const defaultTagData = TagEditor._getDefaultTagData(this.state.activeTagDefinition);
      argData = defaultTagData.args[argIndex];
    } else {
      return null;
    }

    if (!argData) {
      console.error('Failed to find argument to set default', {
        argDefinition,
        argDatas,
        argIndex,
      });
      return null;
    }

    const strValue = templateUtils.decodeEncoding(argData.value.toString());
    const isVariable = argData.type === 'variable';
    const argInputVariable = isVariable ? this.renderArgVariable(strValue) : null;

    let argInput;
    let isVariableAllowed = true;
    if (argDefinition.type === 'string') {
      const placeholder =
        typeof argDefinition.placeholder === 'string' ? argDefinition.placeholder : '';
      const encoding = argDefinition.encoding || 'utf8';
      argInput = this.renderArgString(strValue, placeholder, encoding);
    } else if (argDefinition.type === 'enum') {
      const { options } = argDefinition;
      argInput = this.renderArgEnum(strValue, options || []);
    } else if (argDefinition.type === 'file') {
      argInput = this.renderArgFile(
        strValue,
        argIndex,
        argDefinition.itemTypes,
        argDefinition.extensions,
      );
    } else if (argDefinition.type === 'model') {
      isVariableAllowed = false;
      const model = typeof argDefinition.model === 'string' ? argDefinition.model : 'unknown';
      const modelId = typeof strValue === 'string' ? strValue : 'unknown';
      argInput = this.renderArgModel(modelId, model);
    } else if (argDefinition.type === 'boolean') {
      argInput = this.renderArgBoolean(strValue.toLowerCase() === 'true');
    } else if (argDefinition.type === 'number') {
      const placeholder =
        typeof argDefinition.placeholder === 'string' ? argDefinition.placeholder : '';
      argInput = this.renderArgNumber(strValue, placeholder || '');
    } else {
      return null;
    }

    const help =
      typeof argDefinition.help === 'string' || typeof argDefinition.help === 'function'
        ? fnOrString(argDefinition.help, argDatas)
        : '';

    const displayName =
      typeof argDefinition.displayName === 'string' ||
      typeof argDefinition.displayName === 'function'
        ? fnOrString(argDefinition.displayName, argDatas)
        : '';

    let validationError = '';
    const canValidate = argDefinition.type === 'string' || argDefinition.type === 'number';
    if (canValidate && typeof argDefinition.validate === 'function') {
      validationError = argDefinition.validate(strValue) || '';
    }

    const formControlClasses = classnames({
      'form-control': true,
      'form-control--thin': argDefinition.type === 'boolean',
      'form-control--outlined': argDefinition.type !== 'boolean',
    });

    return (

            {fnOrString(displayName, argDatas)}
            {isVariable && (Variable)}
            {help && <HelpTooltip className="space-left">{help}</HelpTooltip>}
            {validationError && {validationError}}
            {argInputVariable || argInput}

        {isVariableAllowed ? (

            <Dropdown right>
              <DropdownButton className="btn btn--clicky">

              </DropdownButton>
              <DropdownDivider>Input Type</DropdownDivider>
              <DropdownItem
                value={{ variable: false, argIndex }}
                onClick={this._handleChangeArgVariable}>
                 Static Value
              </DropdownItem>
              <DropdownItem
                value={{ variable: true, argIndex }}
                onClick={this._handleChangeArgVariable}>
                 Environment Variable
              </DropdownItem>
            </Dropdown>

        ) : null}

    );
  }

  render() {
    const { error, preview, activeTagDefinition, activeTagData, rendering } = this.state;

    if (!activeTagData) {
      return null;
    }

    let finalPreview = preview;
    if (activeTagDefinition && activeTagDefinition.disablePreview) {
      finalPreview = activeTagDefinition.disablePreview(activeTagData.args)
        ? preview.replace(/./g, '*')
        : preview;
    }

    let previewElement;
    if (error) {
      previewElement = <textarea className="danger" value={error || 'Error'} readOnly rows={5} />;
    } else if (rendering) {
      previewElement = <textarea value="rendering..." readOnly rows={5} />;
    } else {
      previewElement = <textarea value={finalPreview || 'error'} readOnly rows={5} />;
    }

    return (

            Function to Perform
            <select
              ref={this._setSelectRef}
              onChange={this._handleChangeTag}
              value={activeTagDefinition ? activeTagDefinition.name : ''}>
              {this.state.tagDefinitions.map((tagDefinition, i) => (
                <option key={`${i}::${tagDefinition.name}`} value={tagDefinition.name}>
                  {tagDefinition.displayName} – {tagDefinition.description}
                </option>
              ))}
              <option value="custom">-- Custom --</option>
            </select>

        {activeTagDefinition &&
          activeTagDefinition.args.map((argDefinition: NunjucksParsedTagArg, index) =>
            this.renderArg(argDefinition, activeTagData.args, index),
          )}
        {!activeTagDefinition && (

              Custom
              <input
                type="text"
                defaultValue={activeTagData.rawValue}
                onChange={this._handleChangeCustomArg}
              />

        )}

            <button
              type="button"
              style={{ zIndex: 10, position: 'relative' }}
              className="txt-sm pull-right icon inline-block"
              onClick={this._handleRefresh}>
              refresh{' '}

            </button>

              Live Preview
              {previewElement}

    );
  }
}

export default TagEditor;


text: /usr/bin/defaults write /Library/Preferences/com.apple.screensaver loginWindowIdleTime 0


text:
#include <iostream>
#include <cassert>
#include <msgpack.h>
#include <stdlib.h>
#include "core/logging.h"
#include "transport/server.h"
#include "transport/client.h"
#include "transport/response.h"
#include "transport/command/ping.h"
#include "transport/command/dsnew.h"
#include "transport/command/dsappend.h"
#include "transport/command/dslist.h"
#include "transport/command/modnew.h"
#include "transport/command/modbuild.h"
#include "transport/command/modpredict.h"
#include "transport/command/shutdown.h"

namespace chimp {
namespace transport {

void _close_cb(uv_handle_t *client_handle)
{
    chimp::transport::Client *client = static_cast<chimp::transport::Client*>(client_handle->data);
    delete client;
}

static uv_buf_t _alloc_cb(uv_handle_t* client_handle, size_t suggested_size)
{
    uv_buf_t buf;

    CH_LOG_DEBUG("alloc_cb: allocating " << suggested_size << " bytes");
    buf.base = (char*)malloc(suggested_size);
    buf.len = suggested_size;

    return buf;
}

static void _read_cb(uv_stream_t *client_handle, ssize_t nread, uv_buf_t buf)
{
    chimp::transport::Client *client = static_cast<chimp::transport::Client*>(client_handle->data);

    if (nread >= 0) {
        msgpack_unpacked msg;
        msgpack_unpacked_init(&msg);

        if (!msgpack_unpack_next(&msg, buf.base, buf.len, NULL)) {
            CH_LOG_ERROR("read: failed to unpack message");
            std::shared_ptr<AbstractResponse> response(new chimp::transport::response::ErrorResponse(
                                                        chimp::transport::response::RESPONSE_CODE_USER_ERROR,
                                                        "invalid message"));
            client->Write(response);
        } else if (msg.data.type != MSGPACK_OBJECT_ARRAY ||
            msg.data.via.array.size < 1 ||
            msg.data.via.array.ptr[0].type != MSGPACK_OBJECT_RAW) {
            std::shared_ptr<AbstractResponse> response(new chimp::transport::response::ErrorResponse(
                                                        chimp::transport::response::RESPONSE_CODE_USER_ERROR,
                                                        "invalid message"));
            client->Write(response);
        } else {
            std::string command_name(msg.data.via.array.ptr[0].via.raw.ptr,
                                     msg.data.via.array.ptr[0].via.raw.size);
            std::map<std::string, chimp::transport::Server::Command>::iterator iter = client->server->commands.find(command_name);
            if (iter == client->server->commands.end()) {
                std::shared_ptr<AbstractResponse> response(new chimp::transport::response::ErrorResponse(
                                                            chimp::transport::response::RESPONSE_CODE_SERVER_ERROR,
                                                            "unsupported command"));
                client->Write(response);
            } else {
                chimp::transport::Server::Command command = iter->second;
                chimp::transport::command::AbstractCommand *cmd = NULL;

                switch (command) {
                    case chimp::transport::Server::PING:
                        cmd = new chimp::transport::command::Ping(client);
                        break;
                    case chimp::transport::Server::DSNEW:
                        cmd = new chimp::transport::command::DatasetNew(client);
                        break;
                    case chimp::transport::Server::DSLIST:
                        cmd = new chimp::transport::command::DatasetList(client);
                        break;
                    case chimp::transport::Server::DSAPPEND:
                        cmd = new chimp::transport::command::DatasetAppend(client);
                        break;
                    case chimp::transport::Server::MODNEW:
                        cmd = new chimp::transport::command::ModelNew(client);
                        break;
                    case chimp::transport::Server::MODBUILD:
                        cmd = new chimp::transport::command::ModelBuild(client);
                        break;
                    case chimp::transport::Server::MODPREDICT:
                        cmd = new chimp::transport::command::ModelPredict(client);
                        break;
                    case chimp::transport::Server::SHUTDOWN:
                        cmd = new chimp::transport::command::Shutdown(client);
                        break;
                    default:
                        {
                        std::shared_ptr<AbstractResponse> response(new chimp::transport::response::ErrorResponse(
                                                                    chimp::transport::response::RESPONSE_CODE_SERVER_ERROR,
                                                                    "command not implemented"));
                        client->Write(response);
                        }
                        break;
                }

                if (cmd) {
                    if (cmd->FromMessagePack(&msg) == 0) {
                        cmd->Execute();
                    } else {
                        CH_LOG_ERROR("failed to unpack message");
                        std::shared_ptr<AbstractResponse> response(new chimp::transport::response::ErrorResponse(
                                                                    chimp::transport::response::RESPONSE_CODE_USER_ERROR,
                                                                    "failed to unpack message"));
                        client->Write(response);
                    }
                    delete cmd;
                }
            }
            msgpack_unpacked_destroy(&msg);
        }
    } else {
        if (nread != UV_EOF) {
            CH_LOG_ERROR("read: " << uv_strerror(uv_last_error(client_handle->loop)));
        }
        uv_close((uv_handle_t*)client_handle, _close_cb);
    }

    free(buf.base);
}

static void _connection_cb(uv_stream_t *server_handle, int status)
{
    chimp::transport::Server *server = static_cast<chimp::transport::Server*>(server_handle->data);
    // this is a lean on shutdown, but it does not matter much since OS
    // will clean up the rest
    chimp::transport::Client *client = new chimp::transport::Client(server);

    if (client->Init() != 0) {
        delete client;
        return;
    }

    CH_LOG_INFO("new connection");

    uv_read_start((uv_stream_t*)&client->handle, _alloc_cb, _read_cb);
}

Server::Server(ServerSettings settings, uv_loop_t *loop)
{
    this->loop = loop;
    this->settings_ = settings;
    this->commands["PING"] = chimp::transport::Server::PING;
    this->commands["DSNEW"] = chimp::transport::Server::DSNEW;
    this->commands["DSAPPEND"] = chimp::transport::Server::DSAPPEND;
    this->commands["DSLIST"] = chimp::transport::Server::DSLIST;
    this->commands["MODNEW"] = chimp::transport::Server::MODNEW;
    this->commands["MODBUILD"] = chimp::transport::Server::MODBUILD;
    this->commands["MODPREDICT"] = chimp::transport::Server::MODPREDICT;
    this->commands["SHUTDOWN"] = chimp::transport::Server::SHUTDOWN;
    uv_tcp_init(this->loop, &this->handle);
    this->handle.data = this;
}

int Server::Start()
{
    int r;

    r = uv_tcp_bind(&this->handle, uv_ip4_addr("0.0.0.0", this->settings_.port));
    if (r) {
        CH_LOG_ERROR("bind: " << uv_strerror(uv_last_error(this->loop)));
        return -1;
    }

    r = uv_listen((uv_stream_t*)&this->handle,
                  this->settings_.socket_backlog,
                  _connection_cb);
    if (r) {
        CH_LOG_ERROR("listen: " << uv_strerror(uv_last_error(this->loop)));
        return -1;
    }

    CH_LOG_INFO("starting server on 0.0.0.0:" << this->settings_.port);

    return 0;

}

int Server::Stop()
{
    uv_stop(this->loop);
    return 0;
}

}
}