text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.BotService.Models;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.BotService
{
    /// <summary>
    /// A Class representing a Bot along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="BotResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetBotResource method.
    /// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetBot method.
    /// </summary>
    public partial class BotResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="BotResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string resourceName)
        {
            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _botClientDiagnostics;
        private readonly BotsRestOperations _botRestClient;
        private readonly ClientDiagnostics _directLineClientDiagnostics;
        private readonly DirectLineRestOperations _directLineRestClient;
        private readonly ClientDiagnostics _emailClientDiagnostics;
        private readonly EmailRestOperations _emailRestClient;
        private readonly ClientDiagnostics _privateLinkResourcesClientDiagnostics;
        private readonly PrivateLinkResourcesRestOperations _privateLinkResourcesRestClient;
        private readonly BotData _data;

        /// <summary> Initializes a new instance of the <see cref="BotResource"/> class for mocking. </summary>
        protected BotResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "BotResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal BotResource(ArmClient client, BotData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="BotResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal BotResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _botClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.BotService", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string botApiVersion);
            _botRestClient = new BotsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, botApiVersion);
            _directLineClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.BotService", ProviderConstants.DefaultProviderNamespace, Diagnostics);
            _directLineRestClient = new DirectLineRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
            _emailClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.BotService", ProviderConstants.DefaultProviderNamespace, Diagnostics);
            _emailRestClient = new EmailRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
            _privateLinkResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.BotService", ProviderConstants.DefaultProviderNamespace, Diagnostics);
            _privateLinkResourcesRestClient = new PrivateLinkResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.BotService/botServices";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual BotData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary> Gets a collection of BotChannelResources in the Bot. </summary>
        /// <returns> An object representing collection of BotChannelResources and their operations over a BotChannelResource. </returns>
        public virtual BotChannelCollection GetBotChannels()
        {
            return GetCachedClient(Client => new BotChannelCollection(Client, Id));
        }

        /// <summary>
        /// Returns a BotService Channel registration specified by the parameters.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}
        /// Operation Id: Channels_Get
        /// </summary>
        /// <param name="channelName"> The name of the Channel resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        [ForwardsClientCalls]
        public virtual async Task<Response<BotChannelResource>> GetBotChannelAsync(ChannelName channelName, CancellationToken cancellationToken = default)
        {
            return await GetBotChannels().GetAsync(channelName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Returns a BotService Channel registration specified by the parameters.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}
        /// Operation Id: Channels_Get
        /// </summary>
        /// <param name="channelName"> The name of the Channel resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        [ForwardsClientCalls]
        public virtual Response<BotChannelResource> GetBotChannel(ChannelName channelName, CancellationToken cancellationToken = default)
        {
            return GetBotChannels().Get(channelName, cancellationToken);
        }

        /// <summary> Gets a collection of ConnectionSettingResources in the Bot. </summary>
        /// <returns> An object representing collection of ConnectionSettingResources and their operations over a ConnectionSettingResource. </returns>
        public virtual ConnectionSettingCollection GetConnectionSettings()
        {
            return GetCachedClient(Client => new ConnectionSettingCollection(Client, Id));
        }

        /// <summary>
        /// Get a Connection Setting registration for a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}
        /// Operation Id: BotConnection_Get
        /// </summary>
        /// <param name="connectionName"> The name of the Bot Service Connection Setting resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="connectionName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="connectionName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual async Task<Response<ConnectionSettingResource>> GetConnectionSettingAsync(string connectionName, CancellationToken cancellationToken = default)
        {
            return await GetConnectionSettings().GetAsync(connectionName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Get a Connection Setting registration for a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}
        /// Operation Id: BotConnection_Get
        /// </summary>
        /// <param name="connectionName"> The name of the Bot Service Connection Setting resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="connectionName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="connectionName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual Response<ConnectionSettingResource> GetConnectionSetting(string connectionName, CancellationToken cancellationToken = default)
        {
            return GetConnectionSettings().Get(connectionName, cancellationToken);
        }

        /// <summary> Gets a collection of BotServicePrivateEndpointConnectionResources in the Bot. </summary>
        /// <returns> An object representing collection of BotServicePrivateEndpointConnectionResources and their operations over a BotServicePrivateEndpointConnectionResource. </returns>
        public virtual BotServicePrivateEndpointConnectionCollection GetBotServicePrivateEndpointConnections()
        {
            return GetCachedClient(Client => new BotServicePrivateEndpointConnectionCollection(Client, Id));
        }

        /// <summary>
        /// Gets the specified private endpoint connection associated with the Bot.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}
        /// Operation Id: PrivateEndpointConnections_Get
        /// </summary>
        /// <param name="privateEndpointConnectionName"> The name of the private endpoint connection associated with the Azure resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual async Task<Response<BotServicePrivateEndpointConnectionResource>> GetBotServicePrivateEndpointConnectionAsync(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
        {
            return await GetBotServicePrivateEndpointConnections().GetAsync(privateEndpointConnectionName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets the specified private endpoint connection associated with the Bot.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}
        /// Operation Id: PrivateEndpointConnections_Get
        /// </summary>
        /// <param name="privateEndpointConnectionName"> The name of the private endpoint connection associated with the Azure resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual Response<BotServicePrivateEndpointConnectionResource> GetBotServicePrivateEndpointConnection(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
        {
            return GetBotServicePrivateEndpointConnections().Get(privateEndpointConnectionName, cancellationToken);
        }

        /// <summary>
        /// Returns a BotService specified by the parameters.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<BotResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _botClientDiagnostics.CreateScope("BotResource.Get");
            scope.Start();
            try
            {
                var response = await _botRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new BotResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Returns a BotService specified by the parameters.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<BotResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _botClientDiagnostics.CreateScope("BotResource.Get");
            scope.Start();
            try
            {
                var response = _botRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new BotResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Deletes a Bot Service from the resource group.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _botClientDiagnostics.CreateScope("BotResource.Delete");
            scope.Start();
            try
            {
                var response = await _botRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                var operation = new BotServiceArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Deletes a Bot Service from the resource group.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _botClientDiagnostics.CreateScope("BotResource.Delete");
            scope.Start();
            try
            {
                var response = _botRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                var operation = new BotServiceArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletionResponse(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Update
        /// </summary>
        /// <param name="data"> The parameters to provide for the created bot. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<Response<BotResource>> UpdateAsync(BotData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.Update");
            scope.Start();
            try
            {
                var response = await _botRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data, cancellationToken).ConfigureAwait(false);
                return Response.FromValue(new BotResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Update
        /// </summary>
        /// <param name="data"> The parameters to provide for the created bot. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual Response<BotResource> Update(BotData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.Update");
            scope.Start();
            try
            {
                var response = _botRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data, cancellationToken);
                return Response.FromValue(new BotResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService resource
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys
        /// Operation Id: DirectLine_RegenerateKeys
        /// </summary>
        /// <param name="channelName"> The name of the Channel resource for which keys are to be regenerated. </param>
        /// <param name="content"> The parameters to provide for the created bot. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual async Task<Response<BotChannelResource>> RegenerateKeysDirectLineAsync(RegenerateKeysChannelName channelName, SiteContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _directLineClientDiagnostics.CreateScope("BotResource.RegenerateKeysDirectLine");
            scope.Start();
            try
            {
                var response = await _directLineRestClient.RegenerateKeysAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, channelName, content, cancellationToken).ConfigureAwait(false);
                return Response.FromValue(new BotChannelResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService resource
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys
        /// Operation Id: DirectLine_RegenerateKeys
        /// </summary>
        /// <param name="channelName"> The name of the Channel resource for which keys are to be regenerated. </param>
        /// <param name="content"> The parameters to provide for the created bot. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual Response<BotChannelResource> RegenerateKeysDirectLine(RegenerateKeysChannelName channelName, SiteContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _directLineClientDiagnostics.CreateScope("BotResource.RegenerateKeysDirectLine");
            scope.Start();
            try
            {
                var response = _directLineRestClient.RegenerateKeys(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, channelName, content, cancellationToken);
                return Response.FromValue(new BotChannelResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates an email channel sign in url for a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/createEmailSignInUrl
        /// Operation Id: Email_CreateSignInUrl
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<CreateEmailSignInUrlResponse>> CreateSignInUrlEmailAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _emailClientDiagnostics.CreateScope("BotResource.CreateSignInUrlEmail");
            scope.Start();
            try
            {
                var response = await _emailRestClient.CreateSignInUrlAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates an email channel sign in url for a Bot Service
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/createEmailSignInUrl
        /// Operation Id: Email_CreateSignInUrl
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<CreateEmailSignInUrlResponse> CreateSignInUrlEmail(CancellationToken cancellationToken = default)
        {
            using var scope = _emailClientDiagnostics.CreateScope("BotResource.CreateSignInUrlEmail");
            scope.Start();
            try
            {
                var response = _emailRestClient.CreateSignInUrl(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Gets the private link resources that need to be created for a Bot.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources
        /// Operation Id: PrivateLinkResources_ListByBotResource
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="BotServicePrivateLinkResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual AsyncPageable<BotServicePrivateLinkResource> GetPrivateLinkResourcesByBotResourceAsync(CancellationToken cancellationToken = default)
        {
            async Task<Page<BotServicePrivateLinkResource>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _privateLinkResourcesClientDiagnostics.CreateScope("BotResource.GetPrivateLinkResourcesByBotResource");
                scope.Start();
                try
                {
                    var response = await _privateLinkResourcesRestClient.ListByBotResourceAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
        }

        /// <summary>
        /// Gets the private link resources that need to be created for a Bot.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources
        /// Operation Id: PrivateLinkResources_ListByBotResource
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="BotServicePrivateLinkResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual Pageable<BotServicePrivateLinkResource> GetPrivateLinkResourcesByBotResource(CancellationToken cancellationToken = default)
        {
            Page<BotServicePrivateLinkResource> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _privateLinkResourcesClientDiagnostics.CreateScope("BotResource.GetPrivateLinkResourcesByBotResource");
                scope.Start();
                try
                {
                    var response = _privateLinkResourcesRestClient.ListByBotResource(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
        }

        /// <summary>
        /// Add a tag to the current resource.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="key"> The key for the tag. </param>
        /// <param name="value"> The value for the tag. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
        public virtual async Task<Response<BotResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(key, nameof(key));
            Argument.AssertNotNull(value, nameof(value));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.AddTag");
            scope.Start();
            try
            {
                if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
                    originalTags.Value.Data.TagValues[key] = value;
                    await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
                    var originalResponse = await _botRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data;
                    var patch = new BotData(current.Location);
                    foreach (var tag in current.Tags)
                    {
                        patch.Tags.Add(tag);
                    }
                    patch.Tags[key] = value;
                    var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Add a tag to the current resource.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="key"> The key for the tag. </param>
        /// <param name="value"> The value for the tag. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
        public virtual Response<BotResource> AddTag(string key, string value, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(key, nameof(key));
            Argument.AssertNotNull(value, nameof(value));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.AddTag");
            scope.Start();
            try
            {
                if (CanUseTagResource(cancellationToken: cancellationToken))
                {
                    var originalTags = GetTagResource().Get(cancellationToken);
                    originalTags.Value.Data.TagValues[key] = value;
                    GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
                    var originalResponse = _botRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = Get(cancellationToken: cancellationToken).Value.Data;
                    var patch = new BotData(current.Location);
                    foreach (var tag in current.Tags)
                    {
                        patch.Tags.Add(tag);
                    }
                    patch.Tags[key] = value;
                    var result = Update(patch, cancellationToken: cancellationToken);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Replace the tags on the resource with the given set.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="tags"> The set of tags to use as replacement. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
        public virtual async Task<Response<BotResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(tags, nameof(tags));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.SetTags");
            scope.Start();
            try
            {
                if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false);
                    var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
                    originalTags.Value.Data.TagValues.ReplaceWith(tags);
                    await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
                    var originalResponse = await _botRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data;
                    var patch = new BotData(current.Location);
                    patch.Tags.ReplaceWith(tags);
                    var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Replace the tags on the resource with the given set.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="tags"> The set of tags to use as replacement. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
        public virtual Response<BotResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(tags, nameof(tags));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.SetTags");
            scope.Start();
            try
            {
                if (CanUseTagResource(cancellationToken: cancellationToken))
                {
                    GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken);
                    var originalTags = GetTagResource().Get(cancellationToken);
                    originalTags.Value.Data.TagValues.ReplaceWith(tags);
                    GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
                    var originalResponse = _botRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = Get(cancellationToken: cancellationToken).Value.Data;
                    var patch = new BotData(current.Location);
                    patch.Tags.ReplaceWith(tags);
                    var result = Update(patch, cancellationToken: cancellationToken);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Removes a tag by key from the resource.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="key"> The key for the tag. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
        public virtual async Task<Response<BotResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(key, nameof(key));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.RemoveTag");
            scope.Start();
            try
            {
                if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
                    originalTags.Value.Data.TagValues.Remove(key);
                    await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
                    var originalResponse = await _botRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data;
                    var patch = new BotData(current.Location);
                    foreach (var tag in current.Tags)
                    {
                        patch.Tags.Add(tag);
                    }
                    patch.Tags.Remove(key);
                    var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Removes a tag by key from the resource.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}
        /// Operation Id: Bots_Get
        /// </summary>
        /// <param name="key"> The key for the tag. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
        public virtual Response<BotResource> RemoveTag(string key, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(key, nameof(key));

            using var scope = _botClientDiagnostics.CreateScope("BotResource.RemoveTag");
            scope.Start();
            try
            {
                if (CanUseTagResource(cancellationToken: cancellationToken))
                {
                    var originalTags = GetTagResource().Get(cancellationToken);
                    originalTags.Value.Data.TagValues.Remove(key);
                    GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
                    var originalResponse = _botRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
                    return Response.FromValue(new BotResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
                }
                else
                {
                    var current = Get(cancellationToken: cancellationToken).Value.Data;
                    var patch = new BotData(current.Location);
                    foreach (var tag in current.Tags)
                    {
                        patch.Tags.Add(tag);
                    }
                    patch.Tags.Remove(key);
                    var result = Update(patch, cancellationToken: cancellationToken);
                    return result;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/slab.h>
#include <net/ip.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("iptables filter table");

#define FILTER_VALID_HOOKS ((1 << NF_INET_LOCAL_IN) | \
			    (1 << NF_INET_FORWARD) | \
			    (1 << NF_INET_LOCAL_OUT))

static const struct xt_table packet_filter = {
	.name		= "filter",
	.valid_hooks	= FILTER_VALID_HOOKS,
	.me		= THIS_MODULE,
	.af		= NFPROTO_IPV4,
	.priority	= NF_IP_PRI_FILTER,
};

static unsigned int
iptable_filter_hook(unsigned int hook, struct sk_buff *skb,
		    const struct net_device *in, const struct net_device *out,
		    int (*okfn)(struct sk_buff *))
{
	const struct net *net;

	if (hook == NF_INET_LOCAL_OUT &&
	    (skb->len < sizeof(struct iphdr) ||
	     ip_hdrlen(skb) < sizeof(struct iphdr)))
		/* root is playing with raw sockets. */
		return NF_ACCEPT;

	net = dev_net((in != NULL) ? in : out);
	return ipt_do_table(skb, hook, in, out, net->ipv4.iptable_filter);
}

static struct nf_hook_ops *filter_ops __read_mostly;

/* Default to forward because I got too much mail already. */
static bool forward = true;
module_param(forward, bool, 0000);

static int __net_init iptable_filter_net_init(struct net *net)
{
	struct ipt_replace *repl;

	repl = ipt_alloc_initial_table(&packet_filter);
	if (repl == NULL)
		return -ENOMEM;
	/* Entry 1 is the FORWARD hook */
	((struct ipt_standard *)repl->entries)[1].target.verdict =
		forward ? -NF_ACCEPT - 1 : -NF_DROP - 1;

	net->ipv4.iptable_filter =
		ipt_register_table(net, &packet_filter, repl);
	kfree(repl);
	return PTR_RET(net->ipv4.iptable_filter);
}

static void __net_exit iptable_filter_net_exit(struct net *net)
{
	ipt_unregister_table(net, net->ipv4.iptable_filter);
}

static struct pernet_operations iptable_filter_net_ops = {
	.init = iptable_filter_net_init,
	.exit = iptable_filter_net_exit,
};

static int __init iptable_filter_init(void)
{
	int ret;

	ret = register_pernet_subsys(&iptable_filter_net_ops);
	if (ret < 0)
		return ret;

	/* Register hooks */
	filter_ops = xt_hook_link(&packet_filter, iptable_filter_hook);
	if (IS_ERR(filter_ops)) {
		ret = PTR_ERR(filter_ops);
		unregister_pernet_subsys(&iptable_filter_net_ops);
	}

	return ret;
}

static void __exit iptable_filter_fini(void)
{
	xt_hook_unlink(&packet_filter, filter_ops);
	unregister_pernet_subsys(&iptable_filter_net_ops);
}

module_init(iptable_filter_init);
module_exit(iptable_filter_fini);

redpajama_set_name: RedPajamaGithub


text:
package org.apache.atlas.web.setup;

import com.google.common.base.Charsets;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.atlas.AtlasConstants;
import org.apache.atlas.AtlasException;
import org.apache.atlas.ha.AtlasServerIdSelector;
import org.apache.atlas.ha.HAConfiguration;
import org.apache.atlas.setup.SetupException;
import org.apache.atlas.setup.SetupStep;
import org.apache.atlas.web.service.AtlasZookeeperSecurityProperties;
import org.apache.atlas.web.service.CuratorFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Singleton
public class SetupSteps {
    private static final Logger LOG = LoggerFactory.getLogger(SetupSteps.class);
    public static final String SETUP_IN_PROGRESS_NODE = "/setup_in_progress";

    private final Set<SetupStep> setupSteps;
    private CuratorFactory curatorFactory;

    @Inject
    public SetupSteps(Set<SetupStep> steps, CuratorFactory curatorFactory) {
        setupSteps = steps;
        this.curatorFactory = curatorFactory;
    }

    /**
     * Call each registered {@link SetupStep} one after the other.
     * @throws SetupException Thrown with any error during running setup, including Zookeeper interactions, and
     *                          individual failures in the {@link SetupStep}.
     * @param configuration Configuration for Atlas server.
     */
    public void runSetup(Configuration configuration) throws SetupException {
        HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration);
        InterProcessMutex lock = curatorFactory.lockInstance(zookeeperProperties.getZkRoot());
        try {
            LOG.info("Trying to acquire lock for running setup.");
            lock.acquire();
            LOG.info("Acquired lock for running setup.");
            handleSetupInProgress(configuration, zookeeperProperties);
            for (SetupStep step : setupSteps) {
                LOG.info("Running setup step: " + step);
                step.run();
            }
            clearSetupInProgress(zookeeperProperties);
        } catch (SetupException se) {
            LOG.error("Got setup exception while trying to setup", se);
            throw se;
        } catch (Exception e) {
            LOG.error("Error running setup steps", e);
            throw new SetupException("Error running setup steps", e);
        } finally {
            releaseLock(lock);
            curatorFactory.close();
        }
    }

    private void handleSetupInProgress(Configuration configuration, HAConfiguration.ZookeeperProperties zookeeperProperties) throws SetupException {
        if (setupInProgress(zookeeperProperties)) {
            throw new SetupException("A previous setup run may not have completed cleanly. " +
                    "Ensure setup can run and retry after clearing the zookeeper node at " +
                    lockPath(zookeeperProperties));
        }
        createSetupInProgressNode(configuration, zookeeperProperties);
    }

    private void releaseLock(InterProcessMutex lock) {
        try {
            lock.release();
            LOG.info("Released lock after running setup.");
        } catch (Exception e) {
            LOG.error("Error releasing acquired lock.", e);
        }
    }

    private boolean setupInProgress(HAConfiguration.ZookeeperProperties zookeeperProperties) {
        CuratorFramework client = curatorFactory.clientInstance();
        Stat lockInProgressStat;
        String path = lockPath(zookeeperProperties);
        try {
            lockInProgressStat = client.checkExists().forPath(path);
            return lockInProgressStat != null;
        } catch (Exception e) {
            LOG.error("Error checking if path {} exists.", path, e);
            return true;
        }
    }

    private void clearSetupInProgress(HAConfiguration.ZookeeperProperties zookeeperProperties)
            throws Exception {
        CuratorFramework client = curatorFactory.clientInstance();
        String path = lockPath(zookeeperProperties);
        client.delete().forPath(path);
        LOG.info("Deleted lock path after completing setup {}", path);
    }

    private String lockPath(HAConfiguration.ZookeeperProperties zookeeperProperties) {
        return zookeeperProperties.getZkRoot()+ SETUP_IN_PROGRESS_NODE;
    }

    private String getServerId(Configuration configuration) {
        String serverId = configuration.getString(AtlasConstants.ATLAS_REST_ADDRESS_KEY,
                AtlasConstants.DEFAULT_ATLAS_REST_ADDRESS);
        try {
            serverId = AtlasServerIdSelector.selectServerId(configuration);
        } catch (AtlasException e) {
            LOG.error("Could not select server id, defaulting to {}", serverId, e);
        }
        return serverId;
    }

    private void createSetupInProgressNode(Configuration configuration,
                                           HAConfiguration.ZookeeperProperties zookeeperProperties)
            throws SetupException {
        String serverId = getServerId(configuration);
        ACL acl = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0));
        List<ACL> acls = Arrays.asList(new ACL[]{acl});

        CuratorFramework client = curatorFactory.clientInstance();
        try {
            String path = lockPath(zookeeperProperties);
            client.create().withACL(acls).forPath(path, serverId.getBytes(Charsets.UTF_8));
            LOG.info("Created lock node {}", path);
        } catch (Exception e) {
            throw new SetupException("Could not create lock node before running setup.", e);
        }
    }
}


text: Static site for myself and my fiancee


text:
PEGASUS_NAMESPACE_BEGIN

String ConfigFileSyntaxError::_formatMessage(
    const String& file,
    Uint32 line)
{
    char buffer[32];
    sprintf(buffer, "%u", line);

    MessageLoaderParms parms(
        "Config.ConfigExceptions.CONFIG_FILE_SYNTAX_ERR",
        "Syntax error in configuration file: ");
    String result = MessageLoader::getMessage(parms);
    result.append(file);
    result.append("(");
    result.append(buffer);
    result.append(")");
    return result;
}

PEGASUS_NAMESPACE_END


text:
from setuptools import setup, find_packages
from grove import __version__

setup(
    name="quantum-grove",
    version=__version__,
    author="Rigetti Computing",
    author_email="softapps@rigetti.com",
    description="A collection of quantum algorithms built using pyQuil and Forest",
    url="https://github.com/rigetticomputing/grove.git",
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    install_requires=[
        'numpy',
        'scipy',
        'pyquil >= 2.0.0',
        'funcsigs',
        'mock',
        'networkx',
        'matplotlib'
    ],
    extras_require={
        'tomography': [
            'cython',
            'cvxpy',
            'scs',
            'qutip'
        ]
    },
    setup_requires=[
        'pytest-runner',
        'numpy'
    ],
    tests_require=[
        'tox',
        'pytest >= 3.0.0',
    ],
    license='LICENSE',
    keywords='quantum quil programming hybrid'
)


text:
/** Contient la classe {@link Boutons.Bouton} et ses sous-classes
 * @author julien
 *
 */
package Boutons;


text:
Handle Client
=============

This is a very thin client for the [Handle Server Web API](https://github.com/cordmata/handle-service).
There's really not much to it, it's basically an educational reference implementation for the service,
but [we're using it](http://repository.asu.edu/), so feel free.

Installation
------------

`pip install -e git+https://github.com/cordmata/handle-client.git#egg=handle`

Usage
-----

```python
from handle import Client

client = Client("http://your.server.org/handle-service/", "handleAdmin", "yourPass")

client.create("2286.9/test", "http://example.org")
#>>> http://hdl.handle.net/2286.9/test

client.read("2286.9/test")
#>>> http://example.org

client.update("2286.9/test", "http://new.example.org")
#>>> http://hdl.handle.net/2286.9/test

client.delete("2286.9/test")
```

Told you...not much to it.


text:
<?xml version="1.0" encoding="utf-8"?>
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
	<identity>
		<version number="20200127.0919"/>
		<language type="dji"/>
		<special>
			<sil:identity defaultRegion="AU" script="Latn" draft="generated"/>
		</special>
	</identity>
	<localeDisplayNames>
		<special>
			<sil:names>
				<sil:name xml:lang="en">Djinang</sil:name>
			</sil:names>
		</special>
	</localeDisplayNames>
	<layout>
		<orientation>
			<characterOrder>left-to-right</characterOrder>
		</orientation>
	</layout>
	<characters>
		<exemplarCharacters>[a b c d ḏ e g h i j k l ḻ m n ṉ o p q r s t ṯ u v w y z ŋ]</exemplarCharacters>
		<exemplarCharacters type="punctuation">[! ' ( ) , \- . \: ; ? ' ' " "]</exemplarCharacters>
		<exemplarCharacters type="index">[A B C D Ḏ E G H I J K L Ḻ M N Ṉ O P Q R S T Ṯ U V W Y Z Ŋ]</exemplarCharacters>
	</characters>
	<special>
		<sil:external-resources>
			<sil:font name="Charis SIL" types="default">
				<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Sans"><!--types="ui"-->
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Serif">
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
			</sil:font>
		</sil:external-resources>
	</special>
</ldml>


text:
package com.jivesoftware.os.routing.bird.server.oauth;

/**
 *
 */
public class AuthValidationException extends Exception {

    public AuthValidationException(String message) {
        super(message);
    }

    public AuthValidationException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
'use strict';

import React        from 'react'
import objectAssign from 'object-assign'
import resources    from '../constants/resources.react'

const context = {
  getChildContext() {
    return $.extend({}, this.context, resources);
  },
  childContextTypes: {
    router: React.PropTypes.func,
    locales: React.PropTypes.string,
    messages: React.PropTypes.object,
    formats: React.PropTypes.object,
    lang: React.PropTypes.string
  },
  contextTypes: {
    router: React.PropTypes.func,
    locales: React.PropTypes.string,
    messages: React.PropTypes.object,
    formats: React.PropTypes.object,
    lang: React.PropTypes.string
  }
};

export default function(obj) {
  obj.childContextTypes = context.childContextTypes;
  obj.contextTypes = context.contextTypes;

  obj.prototype.getChildContext = context.getChildContext;
}


text:
from models.base import db
from models.user import User

from modules.sqlalchemy.uuid import GUID
from modules.sqlalchemy.rrule import RRule

class CalendarRubric(db.Model):
    """ Рубрики событий календаря

    """
    __tablename__ = "crm_calendar_rubrics"

    id = db.Column(db.Integer, primary_key=True)

    caption = db.Column(db.String(255), nullable=False)

    def __init__(self, caption):
        """

        :param caption:
        """
        self.caption = caption

class CalendarEventRubrics(db.Model):
    """

    """
    __tablename__ = "crm_calendar_event_rubrics"

    event_id = db.Column(GUID, db.ForeignKey("crm_calendar_event.id", ondelete="CASCADE"), primary_key=True)
    rubric_id = db.Column(db.Integer, db.ForeignKey("crm_calendar_rubrics.id", ondelete="CASCADE"), primary_key=True)

class CalendarEvent(db.Model):
    """ Событие календаря

    """
    __tablename__ = "crm_calendar_event"

    id = db.Column(GUID, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey("crm_users.id", ondelete="SET NULL"), nullable=False)

    caption = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text, nullable=True)
    start_date = db.Column(db.DateTime, nullable=False)
    rules = db.Column(RRule, nullable=True)

    author = db.relationship(User, uselist=False, backref=db.backref("events", uselist=True))
    rubrics = db.relationship(CalendarRubric, uselist=True, lazy="joined", secondary="crm_calendar_event_rubrics")

    def __init__(self, caption, start_date):
        """

        :param caption:
        :param start_date:
        """
        self.caption = caption
        self.start_date = start_date


text:
namespace Portal.Web.ViewModels.Authentication
{
    public class LogoutRequest
    {
        public int AccountKey { get; set; }

        public string Username { get; set; }
    }
}


text:
namespace upywrap
{
  void Throw( const std::string& what )
  {
    throw std::runtime_error( what.data() );
  }
}

#endif //#ifndef MICROPYTHON_WRAP_TESTS_EXCEPTION_H


text:
'use strict';

const models = require('./index');

/**
 * Specifies a configuration for Widevine licenses.
 *
 * @extends models['ContentKeyPolicyConfiguration']
 */
class ContentKeyPolicyWidevineConfiguration extends models['ContentKeyPolicyConfiguration'] {
  /**
   * Create a ContentKeyPolicyWidevineConfiguration.
   * @property {string} widevineTemplate The Widevine template.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ContentKeyPolicyWidevineConfiguration
   *
   * @returns {object} metadata of ContentKeyPolicyWidevineConfiguration
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: '#Microsoft.Media.ContentKeyPolicyWidevineConfiguration',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: '@odata.type',
          clientName: 'odatatype'
        },
        uberParent: 'ContentKeyPolicyConfiguration',
        className: 'ContentKeyPolicyWidevineConfiguration',
        modelProperties: {
          odatatype: {
            required: true,
            serializedName: '@odata\\.type',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          },
          widevineTemplate: {
            required: true,
            serializedName: 'widevineTemplate',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ContentKeyPolicyWidevineConfiguration;


text:
@interface MWMMobileInternetViewController ()

@property(weak, nonatomic) IBOutlet SettingsTableViewSelectableCell * always;
@property(weak, nonatomic) IBOutlet SettingsTableViewSelectableCell * ask;
@property(weak, nonatomic) IBOutlet SettingsTableViewSelectableCell * never;
@property(weak, nonatomic) SettingsTableViewSelectableCell * selected;

@end

@implementation MWMMobileInternetViewController

- (void)viewDidLoad
{
  [super viewDidLoad];
  self.title = L(@"mobile_data");

  SettingsTableViewSelectableCell * selected;
  switch ([MWMNetworkPolicy sharedPolicy].permission) {
    case MWMNetworkPolicyPermissionAlways:
      selected = self.always;
      break;
    case MWMNetworkPolicyPermissionNever:
      selected = self.never;
      break;
    case MWMNetworkPolicyPermissionToday:
    case MWMNetworkPolicyPermissionNotToday:
    case MWMNetworkPolicyPermissionAsk:
      selected = self.ask;
      break;
  }
  selected.accessoryType = UITableViewCellAccessoryCheckmark;
  self.selected = selected;
}

- (void)setSelected:(SettingsTableViewSelectableCell *)selected
{
  if ([_selected isEqual:selected])
    return;

  _selected = selected;
  NSString * statValue = @"";
  if ([selected isEqual:self.always])
  {
    statValue = kStatAlways;
    [MWMNetworkPolicy sharedPolicy].permission = MWMNetworkPolicyPermissionAlways;
  }
  else if ([selected isEqual:self.ask])
  {
    statValue = kStatAsk;
    [MWMNetworkPolicy sharedPolicy].permission = MWMNetworkPolicyPermissionAsk;
  }
  else if ([selected isEqual:self.never])
  {
    statValue = kStatNever;
    [MWMNetworkPolicy sharedPolicy].permission = MWMNetworkPolicyPermissionNever;
  }

  [Statistics logEvent:kStatSettingsMobileInternetChange withParameters:@{kStatValue : statValue}];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  SettingsTableViewSelectableCell * selected = self.selected;
  selected.accessoryType = UITableViewCellAccessoryNone;
  selected = [tableView cellForRowAtIndexPath:indexPath];
  selected.accessoryType = UITableViewCellAccessoryCheckmark;
  selected.selected = NO;
  self.selected = selected;
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
  return L(@"mobile_data_description");
}

@end


text:
package io.reflectoring.coderadar.projectadministration.service.analyzerconfig;

import io.reflectoring.coderadar.analyzer.domain.AnalyzerConfiguration;
import io.reflectoring.coderadar.analyzer.service.ListAnalyzersService;
import io.reflectoring.coderadar.plugin.api.AnalyzerConfigurationException;
import io.reflectoring.coderadar.projectadministration.AnalyzerNotFoundException;
import io.reflectoring.coderadar.projectadministration.ProjectNotFoundException;
import io.reflectoring.coderadar.projectadministration.port.driven.analyzerconfig.CreateAnalyzerConfigurationPort;
import io.reflectoring.coderadar.projectadministration.port.driven.project.GetProjectPort;
import io.reflectoring.coderadar.projectadministration.port.driver.analyzerconfig.create.CreateAnalyzerConfigurationCommand;
import io.reflectoring.coderadar.projectadministration.port.driver.analyzerconfig.create.CreateAnalyzerConfigurationUseCase;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CreateAnalyzerConfigurationService implements CreateAnalyzerConfigurationUseCase {

  private final CreateAnalyzerConfigurationPort createAnalyzerConfigurationPort;
  private final ListAnalyzersService listAnalyzerService;
  private final ListAnalyzerConfigurationsService listAnalyzerConfigurationsFromProjectService;
  private final GetProjectPort getProjectPort;
  private static final Logger logger =
      LoggerFactory.getLogger(CreateAnalyzerConfigurationService.class);

  @Override
  public Long create(CreateAnalyzerConfigurationCommand command, long projectId) {
    if (!getProjectPort.existsById(projectId)) {
      throw new ProjectNotFoundException(projectId);
    }

    List<String> analyzers = listAnalyzerService.listAvailableAnalyzers();
    if (analyzers.contains(command.getAnalyzerName())) {
      if (listAnalyzerConfigurationsFromProjectService.get(projectId).stream()
          .noneMatch(a -> a.getAnalyzerName().equals(command.getAnalyzerName()))) {
        AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration();
        analyzerConfiguration.setEnabled(command.isEnabled());
        analyzerConfiguration.setAnalyzerName(command.getAnalyzerName());
        Long id = createAnalyzerConfigurationPort.create(analyzerConfiguration, projectId);
        logger.info(
            "Added analyzerConfiguration {} for project with id {}",
            analyzerConfiguration.getAnalyzerName(),
            projectId);
        return id;
      } else {
        throw new AnalyzerConfigurationException(
            "An analyzer with this name is already configured for the project!");
      }
    } else {
      throw new AnalyzerNotFoundException(command.getAnalyzerName());
    }
  }
}


text:
'use strict';

goog.require('grrUi.core.module');
goog.require('grrUi.core.versionDropdownDirective.VersionDropdownDirective');
goog.require('grrUi.tests.module');

describe('version dropdown directive', function () {
  var $compile, $rootScope, $scope, $q, grrApiService;

  var REFRESH_VERSIONS_EVENT =
      grrUi.core.versionDropdownDirective.VersionDropdownDirective.REFRESH_VERSIONS_EVENT;

  beforeEach(module('/static/angular-components/core/version-dropdown.html'));
  beforeEach(module(grrUi.core.module.name));
  beforeEach(module(grrUi.tests.module.name));

  beforeEach(inject(function ($injector) {
    $compile = $injector.get('$compile');
    $rootScope = $injector.get('$rootScope');
    $q = $injector.get('$q');
    grrApiService = $injector.get('grrApiService');
    $scope = $rootScope.$new();
  }));

  var render = function (url, version) {
    $scope.url = url;
    $scope.version = { // We need to pass an object to see changes.
      data: version
    };

    var template = '<grr-version-dropdown url="url" version="version.data" />';
    var element = $compile(template)($scope);
    $scope.$apply();

    return element;
  };

  var mockApiService = function(responses) {
    spyOn(grrApiService, 'get').and.callFake(function(path) {
      var response = { times: responses[path] }; // Wrap return value in type structure.
      return $q.when({ data: response });
    });
  };

  it('shows HEAD as the first element in the versions list', function() {
    mockApiService({
      'some/url': [{value: 10}]
    });

    var element = render('some/url');
    expect(element.find('option').length).toBe(2);
    expect(element.find('option:nth(0)').val()).toBe('HEAD');
  });

  it('selects HEAD if not version specified', function() {
    mockApiService({
      'some/url': [{value: 10}]
    });

    var element = render('some/url');
    expect(element.find('option[selected]').val()).toBe('HEAD');
  });

  it('should show all versions from server and select the passed one', function () {
    mockApiService({
      'some/url': [{value: 10}, {value: 42}, {value: 50}]
    });

    var element = render('some/url', 42);
    expect(element.find('option').length).toBe(4);  // 3 versions + HEAD
    expect(element.find('option[selected]').val()).toBe('42');
    expect($scope.version.data).toBe(42);
  });

  it('should show add current version to the server versions list', function () {
    mockApiService({
      'some/url': [{value: 10}, {value: 41}, {value: 50}]
    });

    var element = render('some/url', 42);

    // 3 versions from server + selected version + HEAD
    expect(element.find('option').length).toBe(5);

    expect(element.find('option[selected]').val()).toBe('42');
    expect($scope.version.data).toBe(42);
  });

  it('shows hint when a version other than the latest is shown', function () {
    mockApiService({
      'some/url': [{value: 10}, {value: 42}, {value: 50}]
    });

    var element = render('some/url', 42);
    expect(element.find('.newer-version-hint').length).toBe(1);
  });

  it('does not show a hint when a newest version  is shown', function () {
    mockApiService({
      'some/url': [{value: 10}, {value: 42}, {value: 50}]
    });

    var element = render('some/url', 50);
    expect(element.find('.newer-version-hint').length).toBe(0);
  });

  it('should update the selected option on scope value change', function () {
    mockApiService({
      'some/url': [{value: 10}, {value: 42}, {value: 50}]
    });

    var element = render('some/url', 42);
    expect(element.find('option').length).toBe(4);
    expect(element.find('option[selected]').val()).toBe('42');
    expect($scope.version.data).toBe(42);

    $scope.version.data = 50;
    $scope.$apply();
    expect(element.find('option').length).toBe(4);
    expect(element.find('option[selected]').val()).toBe('50');

    $scope.version.data = 99;
    $scope.$apply();
    // This version is not in the server-provided list, so the list should be
    // extended.
    expect(element.find('option').length).toBe(5);
    expect(element.find('option[selected]').val()).toBe('99');
  });

  it('should be disabled when no options are available', function () {
    mockApiService({
      'some/url': []
    });

    var element = render('some/url', 42);
    expect(element.find('select[disabled]').length).toBe(1);
    expect(element.find('option[selected]').text().trim()).toBe('No versions available.');
    expect($scope.version.data).toBe(42); // It does not change the model.
  });

  it('should fetch versions again when a REFRESH_VERSIONS_EVENT is broadcasted', function () {
    var items = [];
    mockApiService({
      'some/url': items
    });

    var element = render('some/url');
    expect(element.find('select[disabled]').length).toBe(1);
    expect(element.find('option[selected]').text().trim()).toBe('No versions available.');

    // Broadcast REFRESH_VERSIONS_EVENT and check that there are options now.
    items.push({value: 10});
    items.push({value: 42});
    $rootScope.$broadcast(REFRESH_VERSIONS_EVENT, {});
    $rootScope.$apply();

    expect(element.find('select[disabled]').length).toBe(0);
    expect(element.find('option').length).toBe(3);
    expect(element.find('option[selected]').val()).toBe('HEAD');
    expect($scope.version.data).toBeUndefined(); // It does not change the model.
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value ="cool_weather"/>
    <version value ="1"/>

    <list>
        <mapping class="com.example.mycoolweather.db.Province"/>
        <mapping class="com.example.mycoolweather.db.City"/>
        <mapping class="com.example.mycoolweather.db.County"/>
    </list>

</litepal>


text:
package io.spring.presentations.jcmm.yourown;

import io.spring.presentations.jcmm.CustomService;
import io.spring.presentations.jcmm.yourown.v3.EnableMyConfigV3;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

@Configuration
// @EnableMyConfigV1
// @EnableMyConfigV2(showCopyright=true)
@EnableMyConfigV3("Well Hello")
public class YouOwnConfigApplication {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
				YouOwnConfigApplication.class);
		CustomService service = context.getBean("myCustomService", CustomService.class);
		service.run();
		context.close();
	}

}


text:
class Test::Unit::TestCase
  share :valid_comment_params do
    before do
      @params = { :comment => { :commentable_id => @article.id,
                                :commentable_type => 'Article',
                                :body => 'the comment body' } }
    end
  end

  share :invalid_comment_params do
    before do
      @params = { :comment => { :commentable_id => @article.id,
                                :commentable_type => 'Article',
                                :body => nil } }
    end
  end

  share :an_approved_comment do
    before do
      @comment = @section.approved_comments.first
    end
  end

  share :an_unapproved_comment do
    before do
      @comment = @section.unapproved_comments.first
    end
  end
end