text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Workloads.Models;

namespace Azure.ResourceManager.Workloads
{
    internal partial class PhpWorkloadsRestOperations
    {
        private readonly TelemetryDetails _userAgent;
        private readonly HttpPipeline _pipeline;
        private readonly Uri _endpoint;
        private readonly string _apiVersion;

        /// <summary> Initializes a new instance of PhpWorkloadsRestOperations. </summary>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="applicationId"> The application id to use for user agent. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
        public PhpWorkloadsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
        {
            _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
            _endpoint = endpoint ?? new Uri("https://management.azure.com");
            _apiVersion = apiVersion ?? "2021-12-01-preview";
            _userAgent = new TelemetryDetails(GetType().Assembly, applicationId);
        }

        internal HttpMessage CreateListBySubscriptionRequest(string subscriptionId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Lists PHP workload resources for a subscription. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceList>> ListBySubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionRequest(subscriptionId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Lists PHP workload resources for a subscription. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceList> ListBySubscription(string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionRequest(subscriptionId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Lists PHP workload resources in a resource group. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceList>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Lists PHP workload resources in a resource group. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceList> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string phpWorkloadName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads/", false);
            uri.AppendPath(phpWorkloadName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets the PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceData>> GetAsync(string subscriptionId, string resourceGroupName, string phpWorkloadName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, phpWorkloadName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceData value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceData.DeserializePhpWorkloadResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((PhpWorkloadResourceData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets the PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceData> Get(string subscriptionId, string resourceGroupName, string phpWorkloadName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, phpWorkloadName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceData value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceData.DeserializePhpWorkloadResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((PhpWorkloadResourceData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourceData data)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads/", false);
            uri.AppendPath(phpWorkloadName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(data);
            request.Content = content;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Create or updated PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="data"> Resource create or update request payload. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="phpWorkloadName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, phpWorkloadName, data);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Create or updated PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="data"> Resource create or update request payload. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="phpWorkloadName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, phpWorkloadName, data);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourcePatch patch)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Patch;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads/", false);
            uri.AppendPath(phpWorkloadName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(patch);
            request.Content = content;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Update PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="patch"> Workload resource update data. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="phpWorkloadName"/> or <paramref name="patch"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceData>> UpdateAsync(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourcePatch patch, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));
            Argument.AssertNotNull(patch, nameof(patch));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, phpWorkloadName, patch);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceData value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceData.DeserializePhpWorkloadResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Update PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="patch"> Workload resource update data. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="phpWorkloadName"/> or <paramref name="patch"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceData> Update(string subscriptionId, string resourceGroupName, string phpWorkloadName, PhpWorkloadResourcePatch patch, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));
            Argument.AssertNotNull(patch, nameof(patch));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, phpWorkloadName, patch);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceData value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceData.DeserializePhpWorkloadResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string phpWorkloadName, string deleteInfra)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Delete;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Workloads/phpWorkloads/", false);
            uri.AppendPath(phpWorkloadName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            if (deleteInfra != null)
            {
                uri.AppendQuery("delete-infra", deleteInfra, true);
            }
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Delete PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="deleteInfra"> Whether to delete infra along with workload resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string phpWorkloadName, string deleteInfra = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, phpWorkloadName, deleteInfra);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Delete PHP workload resource. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="phpWorkloadName"> Php workload name. </param>
        /// <param name="deleteInfra"> Whether to delete infra along with workload resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="phpWorkloadName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Delete(string subscriptionId, string resourceGroupName, string phpWorkloadName, string deleteInfra = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(phpWorkloadName, nameof(phpWorkloadName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, phpWorkloadName, deleteInfra);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListBySubscriptionNextPageRequest(string nextLink, string subscriptionId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Lists PHP workload resources for a subscription. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceList>> ListBySubscriptionNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Lists PHP workload resources for a subscription. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceList> ListBySubscriptionNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Lists PHP workload resources in a resource group. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<PhpWorkloadResourceList>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Lists PHP workload resources in a resource group. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<PhpWorkloadResourceList> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        PhpWorkloadResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = PhpWorkloadResourceList.DeserializePhpWorkloadResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }
    }
}


text:
import { pluck } from 'rxjs/operator/pluck';
import { map } from 'rxjs/operator/map';
import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged';
import { Observable } from 'rxjs/Observable';

export interface SelectSignature<T> {
  <R>(...paths: string[]): Observable<R>;
  <R>(mapFn: (state: T) => R): Observable<R>;
}

export function select<T, R>(pathOrMapFn: any, ...paths: string[]): Observable<R> {
  let mapped$: Observable<R>;

  if (typeof pathOrMapFn === 'string') {
    mapped$ = pluck.call(this, pathOrMapFn, ...paths);
  }
  else if (typeof pathOrMapFn === 'function') {
    mapped$ = map.call(this, pathOrMapFn);
  }
  else {
    throw new TypeError(`Unexpected type ${ typeof pathOrMapFn } in select operator,`
      + ` expected 'string' or 'function'`);
  }

  return distinctUntilChanged.call(mapped$);
}

redpajama_set_name: RedPajamaGithub


text:
package com.simplegame.server.stage.model.element.role;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.simplegame.server.bus.role.export.IRoleExportService;
import com.simplegame.server.bus.role.export.RoleWrapper;
import com.simplegame.server.stage.model.core.element.impl.attribute.AttributeFormulaSearcherFactory;
import com.simplegame.server.stage.model.core.element.impl.state.StateManager;
import com.simplegame.server.stage.model.core.stage.IStage;
import com.simplegame.server.stage.schedule.StageScheduleManager;

/**
 *
 * @Author zeusgooogle@gmail.com
 * @sine   2015年7月21日 下午5:25:53
 *
 */
@Component
public class RoleFactory {

    @Resource
    private IRoleExportService roleExportService;

    public IRole create(String roleId, IStage stage) {
        RoleWrapper roleWrapper = roleExportService.getRole(roleId);

        RoleBusinessData businessData = new RoleBusinessData(roleWrapper);

        Role role = new Role(roleWrapper.getId(), roleWrapper.getName(), "1");
        role.setBusinessData(businessData);
        role.setStateManager(new StateManager());
        role.setScheduleManager(new StageScheduleManager());
        role.setEventManager(new RoleEventManager(role));

        RoleFightAttribute fightAttribute = new RoleFightAttribute(AttributeFormulaSearcherFactory.get());
        role.setFightAttribute(fightAttribute);

        return role;
    }

}


text:
namespace Moonfish.Guerilla.Tags
{
    using Moonfish.Tags;
    using Moonfish.Model;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;

    public partial class EffectEventBlock : GuerillaBlock, IWriteQueueable
    {
        public Flags EffectEventFlags;
        public float SkipFraction;
        public Moonfish.Model.Range DelayBounds;
        public Moonfish.Model.Range DurationBounds;
        public EffectPartBlock[] Parts = new EffectPartBlock[0];
        public BeamBlock[] Beams = new BeamBlock[0];
        public EffectAccelerationsBlock[] Accelerations = new EffectAccelerationsBlock[0];
        public ParticleSystemDefinitionBlockNew[] ParticleSystems = new ParticleSystemDefinitionBlockNew[0];
        public override int SerializedSize
        {
            get
            {
                return 56;
            }
        }
        public override int Alignment
        {
            get
            {
                return 4;
            }
        }
        public override System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader)
        {
            System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader));
            this.EffectEventFlags = ((Flags)(binaryReader.ReadInt32()));
            this.SkipFraction = binaryReader.ReadSingle();
            this.DelayBounds = binaryReader.ReadRange();
            this.DurationBounds = binaryReader.ReadRange();
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(56));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(60));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(20));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(56));
            return pointerQueue;
        }
        public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue)
        {
            base.ReadInstances(binaryReader, pointerQueue);
            this.Parts = base.ReadBlockArrayData<EffectPartBlock>(binaryReader, pointerQueue.Dequeue());
            this.Beams = base.ReadBlockArrayData<BeamBlock>(binaryReader, pointerQueue.Dequeue());
            this.Accelerations = base.ReadBlockArrayData<EffectAccelerationsBlock>(binaryReader, pointerQueue.Dequeue());
            this.ParticleSystems = base.ReadBlockArrayData<ParticleSystemDefinitionBlockNew>(binaryReader, pointerQueue.Dequeue());
        }
        public override void QueueWrites(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.QueueWrites(queueableBinaryWriter);
            queueableBinaryWriter.QueueWrite(this.Parts);
            queueableBinaryWriter.QueueWrite(this.Beams);
            queueableBinaryWriter.QueueWrite(this.Accelerations);
            queueableBinaryWriter.QueueWrite(this.ParticleSystems);
        }
        public override void Write_(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.Write_(queueableBinaryWriter);
            queueableBinaryWriter.Write(((int)(this.EffectEventFlags)));
            queueableBinaryWriter.Write(this.SkipFraction);
            queueableBinaryWriter.Write(this.DelayBounds);
            queueableBinaryWriter.Write(this.DurationBounds);
            queueableBinaryWriter.WritePointer(this.Parts);
            queueableBinaryWriter.WritePointer(this.Beams);
            queueableBinaryWriter.WritePointer(this.Accelerations);
            queueableBinaryWriter.WritePointer(this.ParticleSystems);
        }
        [System.FlagsAttribute()]
        public enum Flags : int
        {
            None = 0,
            DisabledForDebugging = 1,
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }} – {{ site.description }}</title>

    <meta name="author" content="{{ site.name }}" />
    <meta name="description" content="{{ site.description }}">

    <link href='http://fonts.googleapis.com/css?family=Roboto:300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/style.css" />
    <link rel="alternate" type="application/rss+xml" title="{{ site.name }} - {{ site.description }}" href="{{ site.baseurl }}/feed.xml" />

{{ site.name }}

{{ site.description }}

          Blog
          About

      {{ content }}

          {% include svg-icons.html %}


text:
export * from './carousel';
export * from './list';
export * from './option';


text:
<?php    defined('C5_EXECUTE') or die(_("Access Denied."));
$pkg = Package::getByHandle('foundation'); ?>
<?php    $this->inc('elements/header.php'); ?>

			<?php  Loader::model('attribute/categories/collection');
			$fdnptitles = Config::get('fdnptitles');
			if($fdnptitles==0){ echo t('
'); echo $c->getCollectionName(); echo t('
'); } ?>
			<?php  Loader::model('attribute/categories/collection');
			$fdnpdesc = Config::get('fdnpdesc');
			if($fdnpdesc==0){ echo t('
'); echo $c->getCollectionDescription(); echo t('
'); } ?>
			<?php  Loader::model('attribute/categories/collection');
			$fdnbcrumbs = Config::get('fdnbcrumbs');
			if($fdnbcrumbs==0){ echo t('
');
				$bt = BlockType::getByHandle('autonav');
				$bt->controller->displayPages = 'top';
				$bt->controller->orderBy = 'display_asc';
				$bt->controller->displaySubPages = 'relevant_breadcrumb';
				$bt->controller->displaySubPageLevels = 'all';
				$bt->render('templates/breadcrumb');
				echo t('
');
			} ?>

<?php   echo t('Posted by')?> <?php   echo $c->getVersionObject()->getVersionAuthorUserName(); ?> on <?php   echo $c->getCollectionDatePublic('F j, Y'); ?>

		<?php   $a = new Area('Main'); $a->display($c); ?>

		<?php   $a = new Area('Blog Post More'); $a->display($c); ?>

			<?php
			$bt = BlockType::getByHandle('autonav');
			$bt->controller->displayPages = 'top';
			$bt->controller->orderBy = 'display_asc';
			$bt->controller->displaySubPages = 'none';
			$bt->controller->displaySubPageLevels = 'custom';
			$bt->controller->displaySubPageLevelsNum = '1';
			$bt->render('templates/main_menu');
			?>

		<?php   $a = new Area('Sidebar'); $a->display($c); ?>

		<?php   $a = new Area('Additional Content'); $a->display($c); ?>

<?php    $this->inc('elements/footer.php'); ?>


text:
package main

import (
	"database/sql"
	"flag"
	"net/http"
	"time"

	"github.com/google/keytransparency/core/mutator/entry"
	"github.com/google/keytransparency/core/sequencer"

	"github.com/google/keytransparency/impl/sql/engine"
	"github.com/google/keytransparency/impl/sql/mutations"
	"github.com/google/keytransparency/impl/transaction"

	"github.com/golang/glog"
	"github.com/google/trillian"
	_ "github.com/google/trillian/merkle/objhasher" // Register objhasher
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

var (
	metricsAddr      = flag.String("metrics-addr", ":8081", "The ip:port to publish metrics on")
	serverDBPath     = flag.String("db", "db", "Database connection string")
	minEpochDuration = flag.Duration("min-period", time.Second*60, "Minimum time between epoch creation (create epochs only if there where mutations). Expected to be smaller than max-period.")
	maxEpochDuration = flag.Duration("max-period", time.Hour*12, "Maximum time between epoch creation (independent from mutations). This value should about half the time guaranteed by the policy.")

	// Info to connect to the trillian map and log.
	mapID  = flag.Int64("map-id", 0, "ID for backend map")
	mapURL = flag.String("map-url", "", "URL of Trilian Map Server")
	logID  = flag.Int64("log-id", 0, "Trillian Log ID")
	logURL = flag.String("log-url", "", "URL of Trillian Log Server for Signed Map Heads")
)

func openDB() *sql.DB {
	db, err := sql.Open(engine.DriverName, *serverDBPath)
	if err != nil {
		glog.Exitf("sql.Open(): %v", err)
	}
	if err := db.Ping(); err != nil {
		glog.Exitf("db.Ping(): %v", err)
	}
	return db
}

func main() {
	flag.Parse()

	// Flag validation.
	if *maxEpochDuration < *minEpochDuration {
		glog.Exitf("maxEpochDuration < minEpochDuration: %v < %v, want maxEpochDuration >= minEpochDuration")
	}

	sqldb := openDB()
	defer sqldb.Close()
	factory := transaction.NewFactory(sqldb)

	// Connect to map server.
	mconn, err := grpc.Dial(*mapURL, grpc.WithInsecure())
	if err != nil {
		glog.Exitf("grpc.Dial(%v): %v", *mapURL, err)
	}
	tmap := trillian.NewTrillianMapClient(mconn)

	// Connection to append only log
	lconn, err := grpc.Dial(*logURL, grpc.WithInsecure())
	if err != nil {
		glog.Exitf("Failed to connect to %v: %v", *logURL, err)
	}
	tlog := trillian.NewTrillianLogClient(lconn)

	// TODO: add mutations and mutator to admin.
	mutations, err := mutations.New(sqldb, *mapID)
	if err != nil {
		glog.Exitf("Failed to create mutations object: %v", err)
	}
	mutator := entry.New()

	metricMux := http.NewServeMux()
	metricMux.Handle("/metrics", promhttp.Handler())
	go func() {
		if err := http.ListenAndServe(*metricsAddr, metricMux); err != nil {
			glog.Fatalf("ListenAndServeTLS(%v): %v", *metricsAddr, err)
		}
	}()

	signer := sequencer.New(*mapID, tmap, *logID, tlog, mutator, mutations, factory)
	glog.Infof("Signer starting")
	signer.StartSigning(context.Background(), *minEpochDuration, *maxEpochDuration)
	glog.Errorf("Signer exiting")
}


text:
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include <sol-mainloop.h>

#define SOL_LOG_DOMAIN &_log_domain
#include "sol-log-internal.h"
SOL_LOG_INTERNAL_DECLARE_STATIC(_log_domain, "aio");

#include "sol-aio.h"
#ifdef WORKER_THREAD
#include "sol-worker-thread.h"
#endif

#define AIO_BASE_PATH "/sys/bus/iio/devices"

#define AIO_PATH(dst, device, pin) \
    ({ \
        int _tmp = snprintf(dst, sizeof(dst), AIO_BASE_PATH "/iio:device%d/in_voltage%d_raw", \
            device, pin); \
        (_tmp > 0 && _tmp < PATH_MAX); \
    })

#define AIO_DEV_PATH(dst, device) \
    ({ \
        int _tmp = snprintf(dst, sizeof(dst), AIO_BASE_PATH "/iio:device%d", device); \
        (_tmp > 0 && _tmp < PATH_MAX); \
    })

struct sol_aio {
    FILE *fp;
    int device;
    int pin;
    unsigned int mask;
    struct {
        const void *cb_data;
#ifdef WORKER_THREAD
        struct sol_worker_thread *worker;
#else
        struct sol_timeout *timeout;
#endif
        unsigned int value;
        void (*dispatch)(struct sol_aio *aio);

        union {
            struct {
                void (*cb)(void *cb_data, struct sol_aio *aio, int32_t ret);
            } read_cb;
        };
    } async;
};

#ifdef WORKER_THREAD
#define BUSY_CHECK(aio, ret) SOL_EXP_CHECK(aio->async.worker, ret);
#else
#define BUSY_CHECK(aio, ret) SOL_EXP_CHECK(aio->async.timeout, ret);
#endif

static bool
_aio_open_fp(struct sol_aio *aio)
{
    char path[PATH_MAX];

    if (!AIO_PATH(path, aio->device, aio->pin))
        return false;

    aio->fp = fopen(path, "re");
    if (!aio->fp)
        return false;
    setvbuf(aio->fp, NULL, _IONBF, 0);

    return true;
}

SOL_API struct sol_aio *
sol_aio_open_raw(int device, int pin, unsigned int precision)
{
    char path[PATH_MAX];
    struct stat st;
    struct sol_aio *aio;

    SOL_LOG_INTERNAL_INIT_ONCE;

    if (!precision) {
        SOL_WRN("aio #%d,%d: Invalid precision value=%d. Precision needs to be different of zero.",
            device, pin, precision);
        return NULL;
    }

    aio = calloc(1, sizeof(*aio));
    if (!aio) {
        SOL_WRN("aio #%d,%d: could not allocate aio context", device, pin);
        return NULL;
    }

    aio->device = device;
    aio->pin = pin;
    aio->mask = (0x01 << precision) - 1;

    if (!_aio_open_fp((struct sol_aio *)aio)) {
        if (!AIO_DEV_PATH(path, device) || stat(path, &st))
            SOL_WRN("aio #%d,%d: aio device %d does not exist", device, pin, device);
        else
            SOL_WRN("aio #%d,%d: Couldn't open pin %d on device %d", device, pin, pin, device);

        free(aio);
        return NULL;
    }

    return aio;
}

SOL_API void
sol_aio_close(struct sol_aio *aio)
{
    SOL_NULL_CHECK(aio);

    if (aio->fp)
        fclose(aio->fp);

    free(aio);
}

static void
_aio_get_value(struct sol_aio *aio, unsigned int *val)
{
    rewind(aio->fp);

    if (fscanf(aio->fp, "%u", val) < 1) {
        SOL_WRN("AIO #%d,%d: Could not read value.", aio->device, aio->pin);
        *val = -EIO;
    }
}

#ifdef WORKER_THREAD
static bool
aio_get_value_worker_thread_iterate(void *data)
{
    struct sol_aio *aio = data;

    _aio_get_value(aio, &aio->async.value);
    return false;
}

static void
aio_worker_thread_finished(void *data)
{
    struct sol_aio *aio = data;

    aio->async.worker = NULL;
    aio->async.dispatch(aio);
}
#else
static bool
aio_get_value_timeout_cb(void *data)
{
    struct sol_aio *aio = data;

    _aio_get_value(aio, &aio->async.value);
    aio->async.timeout = NULL;
    aio->async.dispatch(aio);
    return false;
}
#endif

static void
_aio_read_dispatch(struct sol_aio *aio)
{
    int32_t ret = aio->async.value;

    if (ret >= 0)
        ret = (int32_t)(aio->async.value & aio->mask);

    if (!aio->async.read_cb.cb) return;

    aio->async.read_cb.cb((void *)aio->async.cb_data, aio, ret);
}

SOL_API struct sol_aio_pending *
sol_aio_get_value(struct sol_aio *aio,
    void (*read_cb)(void *cb_data,
    struct sol_aio *aio,
    int32_t ret),
    const void *cb_data)
{
    struct sol_aio_pending *pending;

#ifdef WORKER_THREAD
    struct sol_worker_thread_config config = {
        SOL_SET_API_VERSION(.api_version = SOL_WORKER_THREAD_CONFIG_API_VERSION, )
        .setup = NULL,
        .cleanup = NULL,
        .iterate = aio_get_value_worker_thread_iterate,
        .finished = aio_worker_thread_finished,
        .feedback = NULL,
        .data = aio
    };
#endif

    errno = EINVAL;
    SOL_NULL_CHECK(aio, NULL);
    SOL_NULL_CHECK(aio->fp, NULL);

    errno = EBUSY;
    BUSY_CHECK(aio, NULL);

    aio->async.value = 0;
    aio->async.read_cb.cb = read_cb;
    aio->async.dispatch = _aio_read_dispatch;
    aio->async.cb_data = cb_data;

#ifdef WORKER_THREAD
    aio->async.worker = sol_worker_thread_new(&config);
    SOL_NULL_CHECK_GOTO(aio->async.worker, err_no_mem);

    pending = (struct sol_aio_pending *)aio->async.worker;
#else
    aio->async.timeout = sol_timeout_add(0, aio_get_value_timeout_cb, aio);
    SOL_NULL_CHECK_GOTO(aio->async.timeout, err_no_mem);

    pending = (struct sol_aio_pending *)aio->async.timeout;
#endif

    errno = 0;
    return pending;

err_no_mem:
    errno = ENOMEM;
    return NULL;
}

SOL_API void
sol_aio_pending_cancel(struct sol_aio *aio, struct sol_aio_pending *pending)
{
    SOL_NULL_CHECK(aio);
    SOL_NULL_CHECK(pending);

#ifdef WORKER_THREAD
    if (aio->async.worker == (struct sol_worker_thread *)pending) {
        sol_worker_thread_cancel(aio->async.worker);
        aio->async.worker = NULL;
    } else {
#else
    if (aio->async.timeout == (struct sol_timeout *)pending) {
        sol_timeout_del(aio->async.timeout);
        aio->async.dispatch(aio);
        aio->async.timeout = NULL;
    } else {
#endif
        SOL_WRN("Invalid AIO pending handle.");
    }
}


text:
package spacesettlers.game;

/**
 * Abstract 2 player Game class so we can implement more than one type of game eventually
 *
 * @author amy
 *
 */
public abstract class AbstractGame {
	 public static int player1 = 1;
	 public static int player2 = 2;

	/**
	 * Is the game over?
	 *
	 * @return true if the game is over and false otherwise
	 */
	public abstract boolean isGameOver();

	/**
	 * Return true if it is the true player 1's turn and false otherwise
	 * @return
	 */
	public abstract boolean getTurn();

	/**
	 * Play the action for the current player
	 */
	public abstract void playAction(AbstractGameAction action);

	/**
	 * Return the winning player (remember players are true and false)
	 *
	 * @return
	 */
	public abstract int getWinner();

	/**
	 * Get the game board
	 * @return
	 */
	public abstract AbstractGameBoard getBoard();

	/**
	 * Return the game agent assigned as player 1.
	 * @return
	 */
	public abstract AbstractGameAgent getPlayer1();

	/**
	 * Return the game agent assigned as player 2.
	 * @return
	 */
	public abstract AbstractGameAgent getPlayer2();

	/**
	 * Return the game agent whose turn it is currently.
	 * @return
	 */
	public abstract AbstractGameAgent getCurrentPlayer();
}


text:
class DetectionBox : Saveable{
    int frame;
    std::pair<int, int> upper_left;
    std::pair<int, int> lower_right;
public:
    DetectionBox();
    DetectionBox(std::pair<int,int> upper_left, std::pair<int,int> lower_right);
    DetectionBox(std::pair<int,int> upper_left, int height, int width);
    DetectionBox(cv::Rect rect);

    void read(const QJsonObject& json);
    void write(QJsonObject& json);
    cv::Rect get_rect();
    void scale_coordinates(float scale_ratio);
};
#endif // DETECTIONBOX_H


text:
sap.ui.define(['jquery.sap.global'],
	function(jQuery) {
	"use strict";

	/**
	 * FormLayout renderer.
	 * @namespace
	 */
	var FormLayoutRenderer = {
	};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.ui.core.Control} oLayout an object representation of the control that should be rendered
	 */
	FormLayoutRenderer.render = function(oRenderManager, oLayout){
		// convenience variable
		var rm = oRenderManager;

		var oForm = oLayout.getParent();
		if (oForm && oForm instanceof sap.ui.layout.form.Form) {
			this.renderForm(rm, oLayout, oForm);
		}

	};

	/**
	 * Renders the HTML for the given form content, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} rm the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.ui.core.Control} oLayout an object representation of the Layout control that should be rendered
	 * @param {sap.ui.layout.form.Form} oForm, a form control to render its content
	 */
	FormLayoutRenderer.renderForm = function(rm, oLayout, oForm){

		rm.write("
");

		// Form header
		var sSize = sap.ui.core.theming.Parameters.get('sap.ui.layout.FormLayout:sapUiFormTitleSize');
		this.renderTitle(rm, oForm.getTitle(), undefined, false, sSize, oForm.getId());

		this.renderContainers(rm, oLayout, oForm);

		rm.write("
");
	};

	FormLayoutRenderer.getMainClass = function(){
		return "sapUiFormLayout";
	};

	FormLayoutRenderer.renderContainers = function(rm, oLayout, oForm){

		var aContainers = oForm.getFormContainers();
		for (var i = 0, il = aContainers.length; i < il; i++) {
			var oContainer = aContainers[i];
			if (oContainer.getVisible()) {
				this.renderContainer(rm, oLayout, oContainer);
			}
		}

	};

	FormLayoutRenderer.renderContainer = function(rm, oLayout, oContainer){

		var bExpandable = oContainer.getExpandable();

		rm.write("
");
		this.renderTitle(rm, oContainer.getTitle(), oContainer._oExpandButton, bExpandable, sap.ui.core.TitleLevel.H4, oContainer.getId());

		if (bExpandable) {
			rm.write("
");
		}

		var aElements = oContainer.getFormElements();
		for (var j = 0, jl = aElements.length; j < jl; j++) {

			var oElement = aElements[j];

			if (oElement.getVisible()) {
				this.renderElement(rm, oLayout, oElement);
			}

		}
		if (bExpandable) {
			rm.write("
");
		}
		rm.write("
");

	};

	FormLayoutRenderer.renderElement = function(rm, oLayout, oElement){

		var oLabel = oElement.getLabelControl();

		rm.write("
");

		if (oLabel) {
			rm.renderControl(oLabel);
		}

		var aFields = oElement.getFields();
		if (aFields && aFields.length > 0) {
			for (var k = 0, kl = aFields.length; k < kl; k++) {
				var oField = aFields[k];
				rm.renderControl(oField);
			}
		}
		rm.write("
");

	};

	/*
	 * Renders the title for a Form or a FormContainer
	 * If this function is overwritten in a Layout please use the right IDs to be sure aria-describedby works fine
	 */
	FormLayoutRenderer.renderTitle = function(rm, oTitle, oExpandButton, bExpander, sLevelDefault, sContentId){

		if (oTitle) {
			//determine title level -> if not set use H4 as default
			var sLevel = sap.ui.core.theming.Parameters.get('sap.ui.layout.FormLayout:sapUiFormSubTitleSize');
			if (sLevelDefault) {
				sLevel = sLevelDefault;
			}
			if (typeof oTitle !== "string" && oTitle.getLevel() != sap.ui.core.TitleLevel.Auto) {
				sLevel = oTitle.getLevel();
			}

			// just reuse TextView class because there font size & co. is already defined
			rm.write("<" + sLevel + " ");
			rm.addClass("sapUiFormTitle");
			rm.addClass("sapUiFormTitle" + sLevel);

			if (typeof oTitle !== "string") {
				rm.writeElementData(oTitle);
				if (oTitle.getTooltip_AsString()) {
					rm.writeAttributeEscaped('title', oTitle.getTooltip_AsString());
				}
				if (oTitle.getEmphasized()) {
					rm.addClass("sapUiFormTitleEmph");
				}
			} else {
				rm.writeAttribute("id", sContentId + "--title");
			}
			rm.writeClasses();
			rm.write(">");

			if (bExpander && oExpandButton) {
				rm.renderControl(oExpandButton);
			}
			if (typeof oTitle === "string") {
				// Title is just a string
				rm.writeEscaped(oTitle, true);
			} else {
				// title control
				var sIcon = oTitle.getIcon();

				if (sIcon) {
					var aClasses = [];
					var mAttributes = {
						"title": null // prevent default icon tooltip
					};

					mAttributes["id"] = oTitle.getId() + "-ico";
					rm.writeIcon(sIcon, aClasses, mAttributes);
				}
				rm.writeEscaped(oTitle.getText(), true);
			}

			rm.write("</" + sLevel + ">");
		}

	};

	/*
	 * Writes the accessibility attributes for FormContainers
	 */
	FormLayoutRenderer.writeAccessibilityStateContainer = function(rm, oContainer){

		var mAriaProps = {role: "form"};
		var oTitle = oContainer.getTitle();
		if (oTitle) {
			var sId = "";
			if (typeof oTitle == "string") {
				sId = oContainer.getId() + "--title";
			} else {
				sId = oTitle.getId();
			}
			mAriaProps["labelledby"] = sId;
		}

		rm.writeAccessibilityState(oContainer, mAriaProps);

	};

	return FormLayoutRenderer;

}, /* bExport= */ true);


text:
#define LOG_TAG "AudioFlinger"
//#define LOG_NDEBUG 0

#include <media/audiohal/DeviceHalInterface.h>
#include <media/audiohal/StreamHalInterface.h>
#include <system/audio.h>
#include <utils/Log.h>

#include "AudioHwDevice.h"
#include "AudioStreamOut.h"

namespace android {

// ----------------------------------------------------------------------------
AudioStreamOut::AudioStreamOut(AudioHwDevice *dev, audio_output_flags_t flags)
        : audioHwDev(dev)
        , stream(NULL)
        , flags(flags)
        , mFramesWritten(0)
        , mFramesWrittenAtStandby(0)
        , mRenderPosition(0)
        , mRateMultiplier(1)
        , mHalFormatHasProportionalFrames(false)
        , mHalFrameSize(0)
{
}

AudioStreamOut::~AudioStreamOut()
{
}

sp<DeviceHalInterface> AudioStreamOut::hwDev() const
{
    return audioHwDev->hwDevice();
}

status_t AudioStreamOut::getRenderPosition(uint64_t *frames)
{
    if (stream == 0) {
        return NO_INIT;
    }

    uint32_t halPosition = 0;
    status_t status = stream->getRenderPosition(&halPosition);
    if (status != NO_ERROR) {
        return status;
    }

    // Maintain a 64-bit render position using the 32-bit result from the HAL.
    // This delta calculation relies on the arithmetic overflow behavior
    // of integers. For example (100 - 0xFFFFFFF0) = 116.
    uint32_t truncatedPosition = (uint32_t)mRenderPosition;
    int32_t deltaHalPosition = (int32_t)(halPosition - truncatedPosition);
    if (deltaHalPosition > 0) {
        mRenderPosition += deltaHalPosition;
    }
    // Scale from HAL sample rate to application rate.
    *frames = mRenderPosition / mRateMultiplier;

    return status;
}

// return bottom 32-bits of the render position
status_t AudioStreamOut::getRenderPosition(uint32_t *frames)
{
    uint64_t position64 = 0;
    status_t status = getRenderPosition(&position64);
    if (status == NO_ERROR) {
        *frames = (uint32_t)position64;
    }
    return status;
}

status_t AudioStreamOut::getPresentationPosition(uint64_t *frames, struct timespec *timestamp)
{
    if (stream == 0) {
        return NO_INIT;
    }

    uint64_t halPosition = 0;
    status_t status = stream->getPresentationPosition(&halPosition, timestamp);
    if (status != NO_ERROR) {
        return status;
    }

    // Adjust for standby using HAL rate frames.
    // Only apply this correction if the HAL is getting PCM frames.
    if (mHalFormatHasProportionalFrames) {
        uint64_t adjustedPosition = (halPosition <= mFramesWrittenAtStandby) ?
                0 : (halPosition - mFramesWrittenAtStandby);
        // Scale from HAL sample rate to application rate.
        *frames = adjustedPosition / mRateMultiplier;
    } else {
        // For offloaded MP3 and other compressed formats.
        *frames = halPosition;
    }

    return status;
}

status_t AudioStreamOut::open(
        audio_io_handle_t handle,
        audio_devices_t devices,
        struct audio_config *config,
        const char *address)
{
    sp<StreamOutHalInterface> outStream;

    audio_output_flags_t customFlags = (config->format == AUDIO_FORMAT_IEC61937)
                ? (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
                : flags;

    int status = hwDev()->openOutputStream(
            handle,
            devices,
            customFlags,
            config,
            address,
            &outStream);
    ALOGV("AudioStreamOut::open(), HAL returned "
            " stream %p, sampleRate %d, Format %#x, "
            "channelMask %#x, status %d",
            outStream.get(),
            config->sample_rate,
            config->format,
            config->channel_mask,
            status);

    // Some HALs may not recognize AUDIO_FORMAT_IEC61937. But if we declare
    // it as PCM then it will probably work.
    if (status != NO_ERROR && config->format == AUDIO_FORMAT_IEC61937) {
        struct audio_config customConfig = *config;
        customConfig.format = AUDIO_FORMAT_PCM_16_BIT;

        status = hwDev()->openOutputStream(
                handle,
                devices,
                customFlags,
                &customConfig,
                address,
                &outStream);
        ALOGV("AudioStreamOut::open(), treat IEC61937 as PCM, status = %d", status);
    }

    if (status == NO_ERROR) {
        stream = outStream;
        mHalFormatHasProportionalFrames = audio_has_proportional_frames(config->format);
        status = stream->getFrameSize(&mHalFrameSize);
    }

    return status;
}

audio_format_t AudioStreamOut::getFormat() const
{
    audio_format_t result;
    return stream->getFormat(&result) == OK ? result : AUDIO_FORMAT_INVALID;
}

uint32_t AudioStreamOut::getSampleRate() const
{
    uint32_t result;
    return stream->getSampleRate(&result) == OK ? result : 0;
}

audio_channel_mask_t AudioStreamOut::getChannelMask() const
{
    audio_channel_mask_t result;
    return stream->getChannelMask(&result) == OK ? result : AUDIO_CHANNEL_INVALID;
}

int AudioStreamOut::flush()
{
    mRenderPosition = 0;
    mFramesWritten = 0;
    mFramesWrittenAtStandby = 0;
    status_t result = stream->flush();
    return result != INVALID_OPERATION ? result : NO_ERROR;
}

int AudioStreamOut::standby()
{
    mRenderPosition = 0;
    mFramesWrittenAtStandby = mFramesWritten;
    return stream->standby();
}

ssize_t AudioStreamOut::write(const void *buffer, size_t numBytes)
{
    size_t bytesWritten;
    status_t result = stream->write(buffer, numBytes, &bytesWritten);
    if (result == OK && bytesWritten > 0 && mHalFrameSize > 0) {
        mFramesWritten += bytesWritten / mHalFrameSize;
    }
    return result == OK ? bytesWritten : result;
}

} // namespace android


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 37(4/5): 445 (1939)

#### Original name
Ahmadia pentatropidis Syd., 1939

### Remarks
null


text:
<?php
namespace bright\core\frontend;

use bright\core\Utils;

use bright\core\content\Pages;

use bright\core\model\Model;

/**
 * Handles the conversion of urls to views
 * You can add custom routes with the addRoute method.
 * You should do that in your constants file, since that
 * is initialized before this class
 * @author Ids
 * @todo Move to frontcontroller
 *
 */
class Router {

	const SPECIAL_403 = 403;
	const SPECIAL_404 = 404;

	/**
	 * Adds a custom route. These routes take precedence over the database
	 * @param string $path The path to trigger on
	 * @param string $view The name of the view class
	 * @param mixed $data Optional data to pass to the view
	 */
	public function addRoute($path, $view, $data = null) {
		Model::GetInstance() -> routes[$path] = array($view, $data);
	}

	/**
	 * Searches the routes and the database for the given path
	 * @todo implement database search;
	 * @param unknown_type $path
	 */
	public function getRoute($path) {
		Utils::log("Requesting $path");
		// Remove start & trailing slashes
		if(Utils::endsWith($path, '/'))
			$path = substr($path, 0, -1);

		if(Utils::startsWith($path, '/'))
			$path = substr($path, 1);
		$view = null;
		if(is_array(Model::GetInstance() -> routes)) {
			if(array_key_exists($path, Model::GetInstance() -> routes)) {
				$viewname = PACKAGE . Model::GetInstance() -> routes[$path][0];
				try {
					$view = new $viewname(Model::GetInstance() -> routes[$path][1]);
				} catch(Exception $e) {
					/*Swallow it*/
				}
			}
		}
		if($view == null) {
			// Find in database
			$pages = new Pages();
			if($path == '') {
				// easy, homepage
				$data = $pages -> getHomepage();
				if($data) {
					$viewname = '\\' . PACKAGE . 'views\\'. ucfirst($data -> template) . 'View';
					$view = new $viewname($data);
				}
			}
		}
		if($view)
			$view -> render();
	}

	public function getSpecial($status) {

	}

	public function init() {
		$status = 200;
		if(isset($_SERVER['REDIRECT_STATUS'])) {
			// no need to check the url, serve a special page
			switch($_SERVER['REDIRECT_STATUS']) {
				case self::SPECIAL_403:
				case self::SPECIAL_404:
					$this -> getSpecial($_SERVER['REDIRECT_STATUS']);
					return;
			}
		}

		// Set the default language
		$this -> _setLanguage();

		if(strpos($_SERVER['REQUEST_URI'], '/index.php') === 0 && isset($_GET['pid'])) {
			$pages = new Pages();
			$path = $pages -> getPath($pid);
			if($path) {
				// IF path is valid, redirect...
				header('Location: ' . (USEPREFIX) ? BASEURL . $_SESSION[BSP]['language'] . '/' . $path : BASEURL . $path);
				exit;
			} else {
				// Else: 404
				$this -> serveSpecial(self::$SPECIAL_404);
				return;
			}
		}

		// Normal request
		if(isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/index.php') !== 0) {
			unset($_GET['path']);
			if(isset($_SERVER['REDIRECT_URL'])) {
				// easy
				$uri = $_SERVER['REDIRECT_URL'];
				$nodes = $this -> getRoute($uri);
			}
			$uri = $_SERVER['REQUEST_URI'];
		} else {
// 			// Just serve the homepage
			$nodes = $this -> getRoute('');
		}
// 		$bright_is404 = ($bright_aTreenodes && is_numeric($bright_aTreenodes[0]) && (int) $bright_aTreenodes[0] == 404);
// 		// Path not found
// 		if($bright_is404){
// 			$this -> serveSpecial(Serve::$SPECIAL_404, __LINE__);
// 			return;
// 		}

// 		$this -> servepage($bright_aTreenodes);
	}

	private function _setLanguage() {
		// Find out language
		$langs = explode(',', AVAILABLELANG);
		$bright_lang = $langs[0];
		if(!USEPREFIX) {
			if(USETLD) {
				$bright_tlda = explode('.', $_SERVER['HTTP_HOST']);
				$bright_tld = array_pop($bright_tlda);
				$bright_preferred = $bright_lang;
				// TLD Base language
				switch($bright_tld) {
					case 'uk':
					case 'com':
						$bright_preferred = 'en';
						break;
					case 'at':
						$bright_preferred = 'de';
						break;
					default:
						$bright_preferred = $bright_tld;
				}
				// Check if the preferred language is available, otherwise, fallback to default language
				if(strpos(AVAILABLELANG, $bright_preferred) !== false) {
					$_SESSION[BSP]['language'] = $bright_preferred;
				} else {
					$_SESSION[BSP]['language'] = $bright_lang;
				}
			} else {
				if(!isset($_SESSION[BSP]['language'])) {

					$_SESSION[BSP]['language'] = $bright_lang;
				}
			}

		} else {
			if(isset($_COOKIE['language'])) {
				$_SESSION[BSP]['language'] = $_COOKIE['language'];
			}
			if(!isset($_SESSION[BSP]['language'])) {
				if(USEHEADER === true && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {

					$x = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
					foreach ($x as $val) {
						#check for q-value and create associative array. No q-value means 1 by rule
						if(preg_match("/(.*);q=([0-1]{0,1}\.\d{0,4})/i",$val,$matches)) {
							$lang[$matches[1]] = (float)$matches[2];
						} else {
							$lang[$val] = 1.0;
						}
					}
					#return default language (highest q-value)
					$qval = 0.0;
					$deflang = $bright_lang;
					foreach ($lang as $key => $value) {
						if(in_array($key, $langs)) {
							if ($value > $qval) {
								$qval = (float)$value;
								$deflang = $key;
							}
						}
					}
					$_SESSION[BSP]['language'] = $deflang;
				}
				if(!isset($_SESSION[BSP]['language']))
					$_SESSION[BSP]['language'] = $bright_lang;

				setcookie('language', $_SESSION[BSP]['language'], strtotime('+1 year'), '/');
			}
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:amazon="http://schemas.android.com/apk/lib/com.amazon.device.ads" xmlns:rim="http://www.blackberry.com/ns/widgets" id="cordova-push-notifications" version="1.1.1">

  <name>Push Notifications Plugin</name>
  <author email="info@appfeel.com" href="https://github.com/appfeel/admob-google-cordova">AppFeel</author>

  <description>
    This plugin allows your application to receive push notifications on Android, iOS, WP8 and Windows8 devices. Android uses Google Cloud Messaging. iOS uses Apple APNS Notifications. WP8 uses Microsoft MPNS Notifications. Windows8 uses Microsoft WNS Notifications.
  </description>

  <license>MIT</license>

  <hook type="after_prepare" src="hooks/after_prepare/999-admobPluginNotice.js" />

  <js-module src="www/PushNotification.js" name="PushNotification">
    <clobbers target="PushNotification" />
  </js-module>

  <engines>
    <engine name="cordova" version=">=3.0.0" />
  </engines>

  <!-- ios -->
  <platform name="ios">

    <config-file target="config.xml" parent="/*">
      <feature name="PushPlugin">
        <param name="ios-package" value="PushPlugin" />
      </feature>
    </config-file>

    <source-file src="src/ios/AppDelegate+notification.m" />
    <source-file src="src/ios/PushPlugin.m" />

    <header-file src="src/ios/AppDelegate+notification.h" />
    <header-file src="src/ios/PushPlugin.h" />

  </platform>

</plugin>


text:
package fr.inra.maiage.bibliome.alvisir.core.facet;

public class CapitalizingFacetLabelFactory implements FacetLabelFactory {
	private final FacetLabelFactory facetLabelFactory;

	public CapitalizingFacetLabelFactory(FacetLabelFactory facetLabelFactory) {
		super();
		this.facetLabelFactory = facetLabelFactory;
	}

	@Override
	public String getFacetLabel(String text) throws Exception {
		String raw = facetLabelFactory.getFacetLabel(text);
		if (raw == null) {
			return null;
		}
		StringBuilder result = new StringBuilder();
		boolean sow = true;
		for (int i = 0; i < raw.length(); ++i) {
			char c = raw.charAt(i);
			if (sow) {
				c = Character.toUpperCase(c);
			}
			result.append(c);
			sow = Character.isWhitespace(c);
		}
		return result.toString();
	}
}


text:
<?php

namespace Sensio\Bundle\GeneratorBundle\Manipulator;

use Symfony\Component\DependencyInjection\Container;

/**
 * Changes the PHP code of a YAML routing file.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class RoutingManipulator extends Manipulator
{
    private $file;

    /**
     * Constructor.
     *
     * @param string $file The YAML routing file path
     */
    public function __construct($file)
    {
        $this->file = $file;
    }

    /**
     * Adds a routing resource at the top of the existing ones.
     *
     * @param string $bundle
     * @param string $format
     * @param string $prefix
     * @param string $path
     *
     * @return Boolean true if it worked, false otherwise
     *
     * @throws \RuntimeException If bundle is already imported
     */
    public function addResource($bundle, $format, $prefix = '/', $path = 'routing')
    {
        $current = '';
        if (file_exists($this->file)) {
            $current = file_get_contents($this->file);

            // Don't add same bundle twice
            if (false !== strpos($current, $bundle)) {
                throw new \RuntimeException(sprintf('Bundle "%s" is already imported.', $bundle));
            }
        } elseif (!is_dir($dir = dirname($this->file))) {
            mkdir($dir, 0777, true);
        }

        $code = sprintf("%s:\n", Container::underscore(substr($bundle, 0, -6)).('/' !== $prefix ? '_'.str_replace('/', '_', substr($prefix, 1)) : ''));
        if ('annotation' == $format) {
            $code .= sprintf("    resource: \"@%s/Controller/\"\n    type:     annotation\n", $bundle);
        } else {
            $code .= sprintf("    resource: \"@%s/Resources/config/%s.%s\"\n", $bundle, $path, $format);
        }
        $code .= sprintf("    prefix:   %s\n", $prefix);
        $code .= "\n";
        $code .= $current;

        if (false === file_put_contents($this->file, $code)) {
            return false;
        }

        return true;
    }
}