text:
using System;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;

namespace Azure.Analytics.Purview.Account
{
    /// <summary> The PurviewAccount service client. </summary>
    public partial class PurviewAccountClient
    {
        /// <summary> The HTTP pipeline for sending and receiving REST requests and responses. </summary>
        public virtual HttpPipeline Pipeline { get => _pipeline; }
        private HttpPipeline _pipeline;
        private readonly string[] AuthorizationScopes = { "https://purview.azure.net/.default" };
        private readonly TokenCredential _tokenCredential;
        private Uri endpoint;
        private readonly string apiVersion;
        private readonly ClientDiagnostics _clientDiagnostics;

        /// <summary> Initializes a new instance of PurviewAccountClient for mocking. </summary>
        protected PurviewAccountClient()
        {
        }

        /// <summary> Initializes a new instance of PurviewAccountClient. </summary>
        /// <param name="endpoint"> The account endpoint of your Purview account. Example: https://{accountName}.purview.azure.com/account/. </param>
        /// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
        /// <param name="options"> The options for configuring the client. </param>
        public PurviewAccountClient(Uri endpoint, TokenCredential credential, PurviewAccountClientOptions options = null)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            options ??= new PurviewAccountClientOptions();
            _clientDiagnostics = new ClientDiagnostics(options);
            _tokenCredential = credential;
            var authPolicy = new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes);
            _pipeline = HttpPipelineBuilder.Build(options, new HttpPipelinePolicy[] { new LowLevelCallbackPolicy() }, new HttpPipelinePolicy[] { authPolicy }, new ResponseClassifier());
            this.endpoint = endpoint;
            apiVersion = options.Version;
        }

        /// <summary> Get an account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   id: string,
        ///   identity: {
        ///     principalId: string,
        ///     tenantId: string,
        ///     type: "SystemAssigned"
        ///   },
        ///   location: string,
        ///   name: string,
        ///   properties: {
        ///     cloudConnectors: {
        ///       awsExternalId: string
        ///     },
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByObjectId: string,
        ///     endpoints: {
        ///       catalog: string,
        ///       guardian: string,
        ///       scan: string
        ///     },
        ///     friendlyName: string,
        ///     managedResourceGroupName: string,
        ///     managedResources: {
        ///       eventHubNamespace: string,
        ///       resourceGroup: string,
        ///       storageAccount: string
        ///     },
        ///     privateEndpointConnections: [
        ///       {
        ///         id: string,
        ///         name: string,
        ///         properties: {
        ///           privateEndpoint: {
        ///             id: string
        ///           },
        ///           privateLinkServiceConnectionState: {
        ///             actionsRequired: string,
        ///             description: string,
        ///             status: "Unknown" | "Pending" | "Approved" | "Rejected" | "Disconnected"
        ///           },
        ///           provisioningState: string
        ///         },
        ///         type: string
        ///       }
        ///     ],
        ///     provisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "SoftDeleting" | "SoftDeleted" | "Failed" | "Succeeded" | "Canceled",
        ///     publicNetworkAccess: "NotSpecified" | "Enabled" | "Disabled"
        ///   },
        ///   sku: {
        ///     capacity: number,
        ///     name: "Standard"
        ///   },
        ///   systemData: {
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///     lastModifiedAt: string (ISO 8601 Format),
        ///     lastModifiedBy: string,
        ///     lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///   },
        ///   tags: Dictionary<string, string>,
        ///   type: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> GetAccountPropertiesAsync(RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetAccountPropertiesRequest();
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetAccountProperties");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Get an account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   id: string,
        ///   identity: {
        ///     principalId: string,
        ///     tenantId: string,
        ///     type: "SystemAssigned"
        ///   },
        ///   location: string,
        ///   name: string,
        ///   properties: {
        ///     cloudConnectors: {
        ///       awsExternalId: string
        ///     },
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByObjectId: string,
        ///     endpoints: {
        ///       catalog: string,
        ///       guardian: string,
        ///       scan: string
        ///     },
        ///     friendlyName: string,
        ///     managedResourceGroupName: string,
        ///     managedResources: {
        ///       eventHubNamespace: string,
        ///       resourceGroup: string,
        ///       storageAccount: string
        ///     },
        ///     privateEndpointConnections: [
        ///       {
        ///         id: string,
        ///         name: string,
        ///         properties: {
        ///           privateEndpoint: {
        ///             id: string
        ///           },
        ///           privateLinkServiceConnectionState: {
        ///             actionsRequired: string,
        ///             description: string,
        ///             status: "Unknown" | "Pending" | "Approved" | "Rejected" | "Disconnected"
        ///           },
        ///           provisioningState: string
        ///         },
        ///         type: string
        ///       }
        ///     ],
        ///     provisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "SoftDeleting" | "SoftDeleted" | "Failed" | "Succeeded" | "Canceled",
        ///     publicNetworkAccess: "NotSpecified" | "Enabled" | "Disabled"
        ///   },
        ///   sku: {
        ///     capacity: number,
        ///     name: "Standard"
        ///   },
        ///   systemData: {
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///     lastModifiedAt: string (ISO 8601 Format),
        ///     lastModifiedBy: string,
        ///     lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///   },
        ///   tags: Dictionary<string, string>,
        ///   type: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response GetAccountProperties(RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetAccountPropertiesRequest();
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetAccountProperties");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateGetAccountPropertiesRequest()
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Updates an account. </summary>
        /// <remarks>
        /// Schema for <c>Request Body</c>:
        /// <code>{
        ///   friendlyName: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   id: string,
        ///   identity: {
        ///     principalId: string,
        ///     tenantId: string,
        ///     type: "SystemAssigned"
        ///   },
        ///   location: string,
        ///   name: string,
        ///   properties: {
        ///     cloudConnectors: {
        ///       awsExternalId: string
        ///     },
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByObjectId: string,
        ///     endpoints: {
        ///       catalog: string,
        ///       guardian: string,
        ///       scan: string
        ///     },
        ///     friendlyName: string,
        ///     managedResourceGroupName: string,
        ///     managedResources: {
        ///       eventHubNamespace: string,
        ///       resourceGroup: string,
        ///       storageAccount: string
        ///     },
        ///     privateEndpointConnections: [
        ///       {
        ///         id: string,
        ///         name: string,
        ///         properties: {
        ///           privateEndpoint: {
        ///             id: string
        ///           },
        ///           privateLinkServiceConnectionState: {
        ///             actionsRequired: string,
        ///             description: string,
        ///             status: "Unknown" | "Pending" | "Approved" | "Rejected" | "Disconnected"
        ///           },
        ///           provisioningState: string
        ///         },
        ///         type: string
        ///       }
        ///     ],
        ///     provisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "SoftDeleting" | "SoftDeleted" | "Failed" | "Succeeded" | "Canceled",
        ///     publicNetworkAccess: "NotSpecified" | "Enabled" | "Disabled"
        ///   },
        ///   sku: {
        ///     capacity: number,
        ///     name: "Standard"
        ///   },
        ///   systemData: {
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///     lastModifiedAt: string (ISO 8601 Format),
        ///     lastModifiedBy: string,
        ///     lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///   },
        ///   tags: Dictionary<string, string>,
        ///   type: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="content"> The content to send as the body of the request. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> UpdateAccountPropertiesAsync(RequestContent content, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateUpdateAccountPropertiesRequest(content);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.UpdateAccountProperties");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Updates an account. </summary>
        /// <remarks>
        /// Schema for <c>Request Body</c>:
        /// <code>{
        ///   friendlyName: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   id: string,
        ///   identity: {
        ///     principalId: string,
        ///     tenantId: string,
        ///     type: "SystemAssigned"
        ///   },
        ///   location: string,
        ///   name: string,
        ///   properties: {
        ///     cloudConnectors: {
        ///       awsExternalId: string
        ///     },
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByObjectId: string,
        ///     endpoints: {
        ///       catalog: string,
        ///       guardian: string,
        ///       scan: string
        ///     },
        ///     friendlyName: string,
        ///     managedResourceGroupName: string,
        ///     managedResources: {
        ///       eventHubNamespace: string,
        ///       resourceGroup: string,
        ///       storageAccount: string
        ///     },
        ///     privateEndpointConnections: [
        ///       {
        ///         id: string,
        ///         name: string,
        ///         properties: {
        ///           privateEndpoint: {
        ///             id: string
        ///           },
        ///           privateLinkServiceConnectionState: {
        ///             actionsRequired: string,
        ///             description: string,
        ///             status: "Unknown" | "Pending" | "Approved" | "Rejected" | "Disconnected"
        ///           },
        ///           provisioningState: string
        ///         },
        ///         type: string
        ///       }
        ///     ],
        ///     provisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "SoftDeleting" | "SoftDeleted" | "Failed" | "Succeeded" | "Canceled",
        ///     publicNetworkAccess: "NotSpecified" | "Enabled" | "Disabled"
        ///   },
        ///   sku: {
        ///     capacity: number,
        ///     name: "Standard"
        ///   },
        ///   systemData: {
        ///     createdAt: string (ISO 8601 Format),
        ///     createdBy: string,
        ///     createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///     lastModifiedAt: string (ISO 8601 Format),
        ///     lastModifiedBy: string,
        ///     lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///   },
        ///   tags: Dictionary<string, string>,
        ///   type: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="content"> The content to send as the body of the request. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response UpdateAccountProperties(RequestContent content, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateUpdateAccountPropertiesRequest(content);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.UpdateAccountProperties");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateUpdateAccountPropertiesRequest(RequestContent content)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Patch;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            request.Content = content;
            return message;
        }

        /// <summary> List the authorization keys associated with this account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   atlasKafkaPrimaryEndpoint: string,
        ///   atlasKafkaSecondaryEndpoint: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> GetAccessKeysAsync(RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetAccessKeysRequest();
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetAccessKeys");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List the authorization keys associated with this account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   atlasKafkaPrimaryEndpoint: string,
        ///   atlasKafkaSecondaryEndpoint: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response GetAccessKeys(RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetAccessKeysRequest();
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetAccessKeys");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateGetAccessKeysRequest()
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/listkeys", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Regenerate the authorization keys associated with this data catalog. </summary>
        /// <remarks>
        /// Schema for <c>Request Body</c>:
        /// <code>{
        ///   keyType: "PrimaryAtlasKafkaKey" | "SecondaryAtlasKafkaKey"
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   atlasKafkaPrimaryEndpoint: string,
        ///   atlasKafkaSecondaryEndpoint: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="content"> The content to send as the body of the request. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> RegenerateAccessKeyAsync(RequestContent content, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateRegenerateAccessKeyRequest(content);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.RegenerateAccessKey");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Regenerate the authorization keys associated with this data catalog. </summary>
        /// <remarks>
        /// Schema for <c>Request Body</c>:
        /// <code>{
        ///   keyType: "PrimaryAtlasKafkaKey" | "SecondaryAtlasKafkaKey"
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   atlasKafkaPrimaryEndpoint: string,
        ///   atlasKafkaSecondaryEndpoint: string
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="content"> The content to send as the body of the request. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response RegenerateAccessKey(RequestContent content, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateRegenerateAccessKeyRequest(content);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.RegenerateAccessKey");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateRegenerateAccessKeyRequest(RequestContent content)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/regeneratekeys", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            request.Content = content;
            return message;
        }

        /// <summary> List the collections in the account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   count: number,
        ///   nextLink: string,
        ///   value: [
        ///     {
        ///       collectionProvisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "Failed" | "Succeeded",
        ///       description: string,
        ///       friendlyName: string,
        ///       name: string,
        ///       parentCollection: {
        ///         referenceName: string,
        ///         type: string
        ///       },
        ///       systemData: {
        ///         createdAt: string (ISO 8601 Format),
        ///         createdBy: string,
        ///         createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///         lastModifiedAt: string (ISO 8601 Format),
        ///         lastModifiedBy: string,
        ///         lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///       }
        ///     }
        ///   ]
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="skipToken"> The String to use. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> GetCollectionsAsync(string skipToken = null, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetCollectionsRequest(skipToken);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetCollections");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List the collections in the account. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   count: number,
        ///   nextLink: string,
        ///   value: [
        ///     {
        ///       collectionProvisioningState: "Unknown" | "Creating" | "Moving" | "Deleting" | "Failed" | "Succeeded",
        ///       description: string,
        ///       friendlyName: string,
        ///       name: string,
        ///       parentCollection: {
        ///         referenceName: string,
        ///         type: string
        ///       },
        ///       systemData: {
        ///         createdAt: string (ISO 8601 Format),
        ///         createdBy: string,
        ///         createdByType: "User" | "Application" | "ManagedIdentity" | "Key",
        ///         lastModifiedAt: string (ISO 8601 Format),
        ///         lastModifiedBy: string,
        ///         lastModifiedByType: "User" | "Application" | "ManagedIdentity" | "Key"
        ///       }
        ///     }
        ///   ]
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="skipToken"> The String to use. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response GetCollections(string skipToken = null, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetCollectionsRequest(skipToken);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetCollections");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateGetCollectionsRequest(string skipToken)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/collections", false);
            uri.AppendQuery("api-version", apiVersion, true);
            if (skipToken != null)
            {
                uri.AppendQuery("$skipToken", skipToken, true);
            }
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Get a resource set config service model. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   count: number,
        ///   nextLink: string,
        ///   value: [
        ///     {
        ///       advancedResourceSet: {
        ///         modifiedAt: string (ISO 8601 Format),
        ///         resourceSetProcessing: "Default" | "Advanced"
        ///       },
        ///       name: string,
        ///       pathPatternConfig: {
        ///         acceptedPatterns: [
        ///           {
        ///             createdBy: string,
        ///             filterType: "Pattern" | "Regex",
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             path: string
        ///           }
        ///         ],
        ///         complexReplacers: [
        ///           {
        ///             createdBy: string,
        ///             description: string,
        ///             disabled: boolean,
        ///             disableRecursiveReplacerApplication: boolean,
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             typeName: string
        ///           }
        ///         ],
        ///         createdBy: string,
        ///         enableDefaultPatterns: boolean,
        ///         lastUpdatedTimestamp: number,
        ///         modifiedBy: string,
        ///         normalizationRules: [
        ///           {
        ///             description: string,
        ///             disabled: boolean,
        ///             dynamicReplacement: boolean,
        ///             entityTypes: [string],
        ///             lastUpdatedTimestamp: number,
        ///             name: string,
        ///             regex: {
        ///               maxDigits: number,
        ///               maxLetters: number,
        ///               minDashes: number,
        ///               minDigits: number,
        ///               minDigitsOrLetters: number,
        ///               minDots: number,
        ///               minHex: number,
        ///               minLetters: number,
        ///               minUnderscores: number,
        ///               options: number,
        ///               regexStr: string
        ///             },
        ///             replaceWith: string,
        ///             version: number
        ///           }
        ///         ],
        ///         regexReplacers: [
        ///           {
        ///             condition: string,
        ///             createdBy: string,
        ///             description: string,
        ///             disabled: boolean,
        ///             disableRecursiveReplacerApplication: boolean,
        ///             doNotReplaceRegex: FastRegex,
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             regex: FastRegex,
        ///             replaceWith: string
        ///           }
        ///         ],
        ///         rejectedPatterns: [Filter],
        ///         scopedRules: [
        ///           {
        ///             bindingUrl: string,
        ///             rules: [
        ///               {
        ///                 displayName: string,
        ///                 isResourceSet: boolean,
        ///                 lastUpdatedTimestamp: number,
        ///                 name: string,
        ///                 qualifiedName: string
        ///               }
        ///             ],
        ///             storeType: string
        ///           }
        ///         ],
        ///         version: number
        ///       }
        ///     }
        ///   ]
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="skipToken"> The String to use. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual async Task<Response> GetResourceSetRulesAsync(string skipToken = null, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetResourceSetRulesRequest(skipToken);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetResourceSetRules");
            scope.Start();
            try
            {
                await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Get a resource set config service model. </summary>
        /// <remarks>
        /// Schema for <c>Response Body</c>:
        /// <code>{
        ///   count: number,
        ///   nextLink: string,
        ///   value: [
        ///     {
        ///       advancedResourceSet: {
        ///         modifiedAt: string (ISO 8601 Format),
        ///         resourceSetProcessing: "Default" | "Advanced"
        ///       },
        ///       name: string,
        ///       pathPatternConfig: {
        ///         acceptedPatterns: [
        ///           {
        ///             createdBy: string,
        ///             filterType: "Pattern" | "Regex",
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             path: string
        ///           }
        ///         ],
        ///         complexReplacers: [
        ///           {
        ///             createdBy: string,
        ///             description: string,
        ///             disabled: boolean,
        ///             disableRecursiveReplacerApplication: boolean,
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             typeName: string
        ///           }
        ///         ],
        ///         createdBy: string,
        ///         enableDefaultPatterns: boolean,
        ///         lastUpdatedTimestamp: number,
        ///         modifiedBy: string,
        ///         normalizationRules: [
        ///           {
        ///             description: string,
        ///             disabled: boolean,
        ///             dynamicReplacement: boolean,
        ///             entityTypes: [string],
        ///             lastUpdatedTimestamp: number,
        ///             name: string,
        ///             regex: {
        ///               maxDigits: number,
        ///               maxLetters: number,
        ///               minDashes: number,
        ///               minDigits: number,
        ///               minDigitsOrLetters: number,
        ///               minDots: number,
        ///               minHex: number,
        ///               minLetters: number,
        ///               minUnderscores: number,
        ///               options: number,
        ///               regexStr: string
        ///             },
        ///             replaceWith: string,
        ///             version: number
        ///           }
        ///         ],
        ///         regexReplacers: [
        ///           {
        ///             condition: string,
        ///             createdBy: string,
        ///             description: string,
        ///             disabled: boolean,
        ///             disableRecursiveReplacerApplication: boolean,
        ///             doNotReplaceRegex: FastRegex,
        ///             lastUpdatedTimestamp: number,
        ///             modifiedBy: string,
        ///             name: string,
        ///             regex: FastRegex,
        ///             replaceWith: string
        ///           }
        ///         ],
        ///         rejectedPatterns: [Filter],
        ///         scopedRules: [
        ///           {
        ///             bindingUrl: string,
        ///             rules: [
        ///               {
        ///                 displayName: string,
        ///                 isResourceSet: boolean,
        ///                 lastUpdatedTimestamp: number,
        ///                 name: string,
        ///                 qualifiedName: string
        ///               }
        ///             ],
        ///             storeType: string
        ///           }
        ///         ],
        ///         version: number
        ///       }
        ///     }
        ///   ]
        /// }
        /// </code>
        ///
        /// Schema for <c>Response Error</c>:
        /// <code>{
        ///   error: {
        ///     code: string,
        ///     details: [
        ///       {
        ///         code: string,
        ///         details: [ErrorModel],
        ///         message: string,
        ///         target: string
        ///       }
        ///     ],
        ///     message: string,
        ///     target: string
        ///   }
        /// }
        /// </code>
        ///
        /// </remarks>
        /// <param name="skipToken"> The String to use. </param>
        /// <param name="options"> The request options. </param>
#pragma warning disable AZC0002
        public virtual Response GetResourceSetRules(string skipToken = null, RequestOptions options = null)
#pragma warning restore AZC0002
        {
            options ??= new RequestOptions();
            using HttpMessage message = CreateGetResourceSetRulesRequest(skipToken);
            RequestOptions.Apply(options, message);
            using var scope = _clientDiagnostics.CreateScope("PurviewAccountClient.GetResourceSetRules");
            scope.Start();
            try
            {
                Pipeline.Send(message, options.CancellationToken);
                if (options.StatusOption == ResponseStatusOption.Default)
                {
                    switch (message.Response.Status)
                    {
                        case 200:
                            return message.Response;
                        default:
                            throw _clientDiagnostics.CreateRequestFailedException(message.Response);
                    }
                }
                else
                {
                    return message.Response;
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        private HttpMessage CreateGetResourceSetRulesRequest(string skipToken)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/resourceSetRuleConfigs", false);
            uri.AppendQuery("api-version", apiVersion, true);
            if (skipToken != null)
            {
                uri.AppendQuery("$skipToken", skipToken, true);
            }
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }
    }
}


text:
package bnw.abm.intg.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Properties;

import bnw.abm.intg.util.GlobalConstants.EXITCODE;

/**
 * @author Bhagya N. Wickramasinghe
 *
 */
public class BNWProperties extends Properties {
    /**
     *
     */
    private static final long serialVersionUID = -5371179228765375673L;

    public BNWProperties(String propertyFile) throws IOException {
        this.loadPropertyFile(propertyFile);
    }

    public BNWProperties loadPropertyFile(String propertyFile) throws IOException {

        try (InputStream inputStream = Files.newInputStream(Paths.get(propertyFile))) {

            if (inputStream != null) {
                this.load(inputStream);
            } else {
                Log.errorAndExit("Property file loading : FAILED", EXITCODE.IOERROR);
            }
        } catch (IOException e) {
            Log.errorAndExit(e.toString(), e, EXITCODE.IOERROR);
        }
        return this;
    }

    /**
     * Reads property file entry as a HashMap. Each Map Entry must be separated by a comma and Key Value pair must be separated by a colon. e.g.
     * President=Name:James,Age:16.
     *
     * @param propertyName
     * @return A HashMap of key value pairs
     */
    public HashMap<String, String> readKeyValuePairs(String propertyName) {
        String[] entries = readCommaSepProperties(propertyName);
        if (entries != null) {
            return splitByColon(entries);
        } else {
            return null;
        }
    }

    /**
     * Reads a property entry's values separated by commas as an array e.g. Names=Bhagya,Sewwandi
     *
     * @param propertyName
     * @return
     */
    public String[] readCommaSepProperties(String propertyName) {
        String entry = this.getProperty(propertyName);
        entry = resolveEnvvar(entry);
        if (entry != null) {
            return entry.trim().split(",");
        } else {
            return null;
        }
    }

    /**
     * Reads a property entry with multiple values each separated by colons as an array. e.g. CsvFile="Test.csv:2:8"
     *
     * @param propertyName
     * @return
     */
    public String[] readColonSeperatedProperties(String propertyName) {
        String entry = this.getProperty(propertyName);
        entry = resolveEnvvar(entry);
        if (entry != null) {
            return entry.trim().split(":");
        } else {
            return null;
        }
    }

    private HashMap<String, String> splitByColon(String[] entries) {

        HashMap<String, String> kvEntries = new HashMap<String, String>();
        for (int i = 0; i < entries.length; i++) {
            String[] arr = entries[i].split(":");
            if (arr.length == 1 || arr[1].trim().equals("")) {
                kvEntries.put(arr[0], null);
            } else {
                kvEntries.put(arr[0], arr[1]);
            }
        }
        return kvEntries;
    }

    public Path readFileOrDirectoryPath(String propertyName) {
        String entry = this.getProperty(propertyName);
        entry = resolveEnvvar(entry);
        return Paths.get(entry);
    }

    /**
     * Resolves environment variables that are in a file path
     *
     * @param filePath
     *            File path String
     * @return returns filePath after replacing environment variable with correct file path
     */
    public static String resolveEnvvar(String filePath) {
        int dollar = filePath.indexOf('$');
        if (dollar != -1) {
            String envVar = filePath.substring(dollar, filePath.indexOf(File.separatorChar));
            String replacement = System.getenv(envVar.substring(1));
            if (replacement == null) {
                Log.errorAndExit(envVar.substring(1) + "  environment variable not found", EXITCODE.ENVVAR);
            }
            return filePath.replace(envVar, replacement);
        } else {
            return filePath;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: OfacSdnLoader</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Class
          OfacSdnLoader

            In:

                lib/ofac/models/ofac_sdn_loader.rb

            Parent:

                Object

Methods

      load_current_sdn_file

Public Class methods

          load_current_sdn_file() {|"Downloading OFAC data from https://www.treasury.gov/resource-center/sanctions/SDN-List/Pages/default.aspx" if block_given?| ...}

Loads the most recent file from www.treasury.gov/resource-center/sanctions/SDN-List/Pages/default.aspx

[Source]

# File lib/ofac/models/ofac_sdn_loader.rb, line 9
  def self.load_current_sdn_file
    puts "Reloading OFAC sdn data"
    puts "Downloading OFAC data from https://www.treasury.gov/resource-center/sanctions/SDN-List/Pages/default.aspx"
    yield "Downloading OFAC data from https://www.treasury.gov/resource-center/sanctions/SDN-List/Pages/default.aspx" if block_given?
    #get the 3 data files
    sdn   = Tempfile.new('sdn')
    bytes = sdn.write(Net::HTTP.get(URI.parse('https://www.treasury.gov/ofac/downloads/sdn.pip')))
    sdn.rewind
    if bytes == 0 || convert_line_to_array(sdn.readline).size != 12
      puts "Trouble downloading file.  The url may have changed."
      yield "Trouble downloading file.  The url may have changed." if block_given?
      return
    else
      sdn.rewind
    end
    address = Tempfile.new('sdn')
    address.write(Net::HTTP.get(URI.parse('https://www.treasury.gov/ofac/downloads/add.pip')))
    address.rewind
    alt = Tempfile.new('sdn')
    alt.write(Net::HTTP.get(URI.parse('https://www.treasury.gov/ofac/downloads/alt.pip')))
    alt.rewind

    if OfacSdn.connection.kind_of?(ActiveRecord::ConnectionAdapters::MysqlAdapter)
      puts "Converting file to csv format for Mysql import.  This could take several minutes."
      yield "Converting file to csv format for Mysql import.  This could take several minutes." if block_given?

      csv_file = convert_to_flattened_csv(sdn, address, alt) do |status|
        yield status if block_given?
      end

      bulk_mysql_update(csv_file)do |status|
        yield status if block_given?
      end
    else
      active_record_file_load(sdn, address, alt)do |status|
        yield status if block_given?
      end
    end

    sdn.close
    @address.close
    @alt.close
  end

[Validate]


text:
/*
 * Powered By agile
 * Web Site: http://www.agile.com
 * Since 2008 - 2016
 */

package persistent.prestige.modules.edu.model;

import java.beans.Transient;
import java.util.HashSet;
import java.util.Set;

import persistent.prestige.platform.base.model.AuditableModel;

/**
 * TeacherUser 实体类
 * @author 雅居乐 2016-9-10 22:35:48
 * @version 1.0
 */
public class TeacherUser extends AuditableModel{

	//alias
	public static final String TABLE_ALIAS = "TeacherUser";

	//columns START
	/**account*/
	private java.lang.String account;
	/**password*/
	private java.lang.String password;
	/**username*/
	private java.lang.String username;
	/**sex*/
	private java.lang.Integer sex;
	/**delFlag*/
	private java.lang.Integer delFlag;
	//columns END

	public java.lang.String getAccount() {
		return this.account;
	}

	public void setAccount(java.lang.String value) {
		this.account = value;
	}

	public java.lang.String getPassword() {
		return this.password;
	}

	public void setPassword(java.lang.String value) {
		this.password = value;
	}

	public java.lang.String getUsername() {
		return this.username;
	}

	public void setUsername(java.lang.String value) {
		this.username = value;
	}

	public java.lang.Integer getSex() {
		return this.sex;
	}

	public void setSex(java.lang.Integer value) {
		this.sex = value;
	}

	public java.lang.Integer getDelFlag() {
		return this.delFlag;
	}

	public void setDelFlag(java.lang.Integer value) {
		this.delFlag = value;
	}

	private Set teacherPossitionUsers = new HashSet(0);
	@Transient
	public Set<TeacherPossitionUser> getTeacherPossitionUsers() {
		return teacherPossitionUsers;
	}
	public void setTeacherPossitionUsers(Set<TeacherPossitionUser> teacherPossitionUser){
		this.teacherPossitionUsers = teacherPossitionUser;
	}

}


text:
/*
 * HomeReducer
 *
 * The reducer takes care of our data. Using actions, we can change our
 * application state.
 * To add a new action, add it to the switch statement in the reducer function
 *
 * Example:
 * case YOUR_ACTION_CONSTANT:
 *   return state.set('yourStateVariable', true);
 */
import omit from 'lodash/omit';
import assign from 'lodash/assign';
import mapValues from 'lodash/mapValues';
import { CREATE_COURSE, DELETE_COURSE, STAR_COURSE } from './constants';

// The initial state of the App
const initialState = {
  courses: [],
};

const initialState3 = {
  courses: [1, 2],
  coursesById: {
    1: {
      id: 1,
      title: 'title one',
    },
    2: {
      id: 2,
      title: 'title two',
    },
  },
};

export function coursesReducer(state = initialState, action) {
  switch (action.type) {
    case CREATE_COURSE:
      console.log('I am here...');
      return {
        courses: state.concat(action.course),
      };
    default:
      return state;
  }
}

export function coursesReducer1(state = initialState, action) {
  switch (action.type) {
    case CREATE_COURSE:

      return [
        ...state,
        Object.assign({}, action.course),
      ];
    default:
      return state;
  }
}

export function coursesReducer2(state = initialState, action) {
  switch (action.type) {
    case CREATE_COURSE:

      return [
        ...state,
        {
          id: action.course.id,
          title: action.course.title,
        },
      ];
    default:
      return state;
  }
}

export default function coursesReducer3(state = initialState3, action) {
  switch (action.type) {
    case CREATE_COURSE:
      console.log(action.course);
      return {
        courses: state.courses.concat(action.course.id),
        coursesById: {
          ...state.coursesById,
          [action.course.id]: {
            id: action.course.id,
            title: action.course.title,
          },
        },
      };
    case DELETE_COURSE:
      return {
        ...state,
        courses: state.courses.filter((id) => id !== action.course.id),
        coursesById: omit(state.coursesById, action.course.id),
      };
    case STAR_COURSE:
      return {
        ...state,
        coursesById: mapValues(state.coursesById, (course) => course.id === action.course.id ?
            assign({}, course, { starred: !course.starred }) :
            course),
      };

    default:
      return state;
  }
}


text:
from flask import Blueprint

movie = Blueprint('movie', __name__)

from . import views


text:
package com.consol.citrus.ws.server;

import com.consol.citrus.endpoint.AbstractEndpointBuilder;
import com.consol.citrus.endpoint.EndpointAdapter;
import com.consol.citrus.ws.message.converter.WebServiceMessageConverter;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.servlet.ServletHandler;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

/**
 * @author Christoph Deppisch
 * @since 2.5
 */
public class WebServiceServerBuilder extends AbstractEndpointBuilder<WebServiceServer> {

    /** Endpoint target */
    private WebServiceServer endpoint = new WebServiceServer();

    @Override
    protected WebServiceServer getEndpoint() {
        return endpoint;
    }

    /**
     * Sets the port property.
     * @param port
     * @return
     */
    public WebServiceServerBuilder port(int port) {
        endpoint.setPort(port);
        return this;
    }

    /**
     * Sets the autoStart property.
     * @param autoStart
     * @return
     */
    public WebServiceServerBuilder autoStart(boolean autoStart) {
        endpoint.setAutoStart(autoStart);
        return this;
    }

    /**
     * Sets the context config location.
     * @param configLocation
     * @return
     */
    public WebServiceServerBuilder contextConfigLocation(String configLocation) {
        endpoint.setContextConfigLocation(configLocation);
        return this;
    }

    /**
     * Sets the resource base.
     * @param resourceBase
     * @return
     */
    public WebServiceServerBuilder resourceBase(String resourceBase) {
        endpoint.setResourceBase(resourceBase);
        return this;
    }

    /**
     * Enables/disables the root parent context.
     * @param rootParentContext
     * @return
     */
    public WebServiceServerBuilder rootParentContext(boolean rootParentContext) {
        endpoint.setUseRootContextAsParent(rootParentContext);
        return this;
    }

    /**
     * Sets the connectors.
     * @param connectors
     * @return
     */
    public WebServiceServerBuilder connectors(List<Connector> connectors) {
        endpoint.setConnectors(connectors.toArray(new Connector[connectors.size()]));
        return this;
    }

    /**
     * Sets the connector.
     * @param connector
     * @return
     */
    public WebServiceServerBuilder connector(Connector connector) {
        endpoint.setConnector(connector);
        return this;
    }

    /**
     * Sets the servlet name.
     * @param servletName
     * @return
     */
    public WebServiceServerBuilder servletName(String servletName) {
        endpoint.setServletName(servletName);
        return this;
    }

    /**
     * Sets the servlet mapping path.
     * @param servletMappingPath
     * @return
     */
    public WebServiceServerBuilder servletMappingPath(String servletMappingPath) {
        endpoint.setServletMappingPath(servletMappingPath);
        return this;
    }

    /**
     * Sets the context path.
     * @param contextPath
     * @return
     */
    public WebServiceServerBuilder contextPath(String contextPath) {
        endpoint.setContextPath(contextPath);
        return this;
    }

    /**
     * Sets the servlet handler.
     * @param servletHandler
     * @return
     */
    public WebServiceServerBuilder servletHandler(ServletHandler servletHandler) {
        endpoint.setServletHandler(servletHandler);
        return this;
    }

    /**
     * Sets the security handler.
     * @param securityHandler
     * @return
     */
    public WebServiceServerBuilder securityHandler(SecurityHandler securityHandler) {
        endpoint.setSecurityHandler(securityHandler);
        return this;
    }

    /**
     * Sets the message converter.
     * @param messageConverter
     * @return
     */
    public WebServiceServerBuilder messageConverter(WebServiceMessageConverter messageConverter) {
        endpoint.setMessageConverter(messageConverter);
        return this;
    }

    /**
     * Sets the default timeout.
     * @param timeout
     * @return
     */
    public WebServiceServerBuilder timeout(long timeout) {
        endpoint.setDefaultTimeout(timeout);
        return this;
    }

    /**
     * Sets the endpoint adapter.
     * @param endpointAdapter
     * @return
     */
    public WebServiceServerBuilder endpointAdapter(EndpointAdapter endpointAdapter) {
        endpoint.setEndpointAdapter(endpointAdapter);
        return this;
    }

    /**
     * Sets the interceptors.
     * @param interceptors
     * @return
     */
    public WebServiceServerBuilder interceptors(List<HandlerInterceptor> interceptors) {
        endpoint.setInterceptors((List) interceptors);
        return this;
    }

    /**
     * Sets the message factory.
     * @param messageFactory
     * @return
     */
    public WebServiceServerBuilder messageFactory(String messageFactory) {
        endpoint.setMessageFactoryName(messageFactory);
        return this;
    }

    /**
     * Sets the keepSoapEnvelope property.
     * @param flag
     * @return
     */
    public WebServiceServerBuilder keepSoapEnvelope(boolean flag) {
        endpoint.setKeepSoapEnvelope(flag);
        return this;
    }

    /**
     * Sets the handleMimeHeaders property.
     * @param flag
     * @return
     */
    public WebServiceServerBuilder handleMimeHeaders(boolean flag) {
        endpoint.setHandleMimeHeaders(flag);
        return this;
    }

    /**
     * Sets the handleAttributeHeaders property.
     * @param flag
     * @return
     */
    public WebServiceServerBuilder handleAttributeHeaders(boolean flag) {
        endpoint.setHandleAttributeHeaders(flag);
        return this;
    }

    /**
     * Sets the SOAP header namespace.
     * @param namespace
     * @return
     */
    public WebServiceServerBuilder soapHeaderNamespace(String namespace) {
        endpoint.setSoapHeaderNamespace(namespace);
        return this;
    }

    /**
     * Sets the SOAP header prefix.
     * @param prefix
     * @return
     */
    public WebServiceServerBuilder soapHeaderPrefix(String prefix) {
        endpoint.setSoapHeaderPrefix(prefix);
        return this;
    }
}


text:
package com.facebook.react.views.text;

import android.content.Context;
import android.text.Spannable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.react.R;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.common.mapbuffer.MapBuffer;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.IViewManagerWithChildren;
import com.facebook.react.uimanager.ReactAccessibilityDelegate;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.yoga.YogaMeasureMode;
import java.util.HashMap;
import java.util.Map;

/**
 * Concrete class for {@link ReactTextAnchorViewManager} which represents view managers of anchor
 * {@code <Text>} nodes.
 */
@ReactModule(name = ReactTextViewManager.REACT_CLASS)
public class ReactTextViewManager
    extends ReactTextAnchorViewManager<ReactTextView, ReactTextShadowNode>
    implements IViewManagerWithChildren {

  private static final short TX_STATE_KEY_ATTRIBUTED_STRING = 0;
  private static final short TX_STATE_KEY_PARAGRAPH_ATTRIBUTES = 1;
  // used for text input
  private static final short TX_STATE_KEY_HASH = 2;
  private static final short TX_STATE_KEY_MOST_RECENT_EVENT_COUNT = 3;

  @VisibleForTesting public static final String REACT_CLASS = "RCTText";

  protected @Nullable ReactTextViewManagerCallback mReactTextViewManagerCallback;

  public ReactTextViewManager() {
    this(null);
  }

  public ReactTextViewManager(@Nullable ReactTextViewManagerCallback reactTextViewManagerCallback) {
    mReactTextViewManagerCallback = reactTextViewManagerCallback;
    setupViewRecycling();
  }

  @Override
  protected ReactTextView prepareToRecycleView(
      @NonNull ThemedReactContext reactContext, ReactTextView view) {
    // BaseViewManager
    super.prepareToRecycleView(reactContext, view);

    // Resets background and borders
    view.recycleView();

    // Defaults from ReactTextAnchorViewManager
    setSelectionColor(view, null);

    return view;
  }

  @Override
  public String getName() {
    return REACT_CLASS;
  }

  @Override
  public ReactTextView createViewInstance(ThemedReactContext context) {
    return new ReactTextView(context);
  }

  @Override
  public void updateExtraData(ReactTextView view, Object extraData) {
    ReactTextUpdate update = (ReactTextUpdate) extraData;
    Spannable spannable = update.getText();
    if (update.containsImages()) {
      TextInlineImageSpan.possiblyUpdateInlineImageSpans(spannable, view);
    }
    view.setText(update);

    // If this text view contains any clickable spans, set a view tag and reset the accessibility
    // delegate so that these can be picked up by the accessibility system.
    ReactClickableSpan[] clickableSpans =
        spannable.getSpans(0, update.getText().length(), ReactClickableSpan.class);

    if (clickableSpans.length > 0) {
      view.setTag(
          R.id.accessibility_links,
          new ReactAccessibilityDelegate.AccessibilityLinks(clickableSpans, spannable));
      ReactAccessibilityDelegate.resetDelegate(
          view, view.isFocusable(), view.getImportantForAccessibility());
    }
  }

  @Override
  public ReactTextShadowNode createShadowNodeInstance() {
    return new ReactTextShadowNode(mReactTextViewManagerCallback);
  }

  public ReactTextShadowNode createShadowNodeInstance(
      @Nullable ReactTextViewManagerCallback reactTextViewManagerCallback) {
    return new ReactTextShadowNode(reactTextViewManagerCallback);
  }

  @Override
  public Class<ReactTextShadowNode> getShadowNodeClass() {
    return ReactTextShadowNode.class;
  }

  @Override
  protected void onAfterUpdateTransaction(ReactTextView view) {
    super.onAfterUpdateTransaction(view);
    view.updateView();
  }

  public boolean needsCustomLayoutForChildren() {
    return true;
  }

  @Override
  public Object updateState(
      ReactTextView view, ReactStylesDiffMap props, StateWrapper stateWrapper) {
    MapBuffer stateMapBuffer = stateWrapper.getStateDataMapBuffer();
    if (stateMapBuffer != null) {
      return getReactTextUpdate(view, props, stateMapBuffer);
    }
    ReadableNativeMap state = stateWrapper.getStateData();
    if (state == null) {
      return null;
    }

    ReadableMap attributedString = state.getMap("attributedString");
    ReadableMap paragraphAttributes = state.getMap("paragraphAttributes");
    Spannable spanned =
        TextLayoutManager.getOrCreateSpannableForText(
            view.getContext(), attributedString, mReactTextViewManagerCallback);
    view.setSpanned(spanned);

    int textBreakStrategy =
        TextAttributeProps.getTextBreakStrategy(paragraphAttributes.getString("textBreakStrategy"));

    return new ReactTextUpdate(
        spanned,
        state.hasKey("mostRecentEventCount") ? state.getInt("mostRecentEventCount") : -1,
        false, // TODO add this into local Data
        TextAttributeProps.getTextAlignment(props, TextLayoutManager.isRTL(attributedString)),
        textBreakStrategy,
        TextAttributeProps.getJustificationMode(props));
  }

  private Object getReactTextUpdate(ReactTextView view, ReactStylesDiffMap props, MapBuffer state) {

    MapBuffer attributedString = state.getMapBuffer(TX_STATE_KEY_ATTRIBUTED_STRING);
    MapBuffer paragraphAttributes = state.getMapBuffer(TX_STATE_KEY_PARAGRAPH_ATTRIBUTES);
    Spannable spanned =
        TextLayoutManagerMapBuffer.getOrCreateSpannableForText(
            view.getContext(), attributedString, mReactTextViewManagerCallback);
    view.setSpanned(spanned);

    int textBreakStrategy =
        TextAttributeProps.getTextBreakStrategy(
            paragraphAttributes.getString(TextLayoutManagerMapBuffer.PA_KEY_TEXT_BREAK_STRATEGY));

    return new ReactTextUpdate(
        spanned,
        -1, // UNUSED FOR TEXT
        false, // TODO add this into local Data
        TextAttributeProps.getTextAlignment(
            props, TextLayoutManagerMapBuffer.isRTL(attributedString)),
        textBreakStrategy,
        TextAttributeProps.getJustificationMode(props));
  }

  @Override
  public @Nullable Map getExportedCustomDirectEventTypeConstants() {
    @Nullable
    Map<String, Object> baseEventTypeConstants = super.getExportedCustomDirectEventTypeConstants();
    Map<String, Object> eventTypeConstants =
        baseEventTypeConstants == null ? new HashMap<String, Object>() : baseEventTypeConstants;
    eventTypeConstants.putAll(
        MapBuilder.of(
            "topTextLayout", MapBuilder.of("registrationName", "onTextLayout"),
            "topInlineViewLayout", MapBuilder.of("registrationName", "onInlineViewLayout")));
    return eventTypeConstants;
  }

  @Override
  public long measure(
      Context context,
      ReadableMap localData,
      ReadableMap props,
      ReadableMap state,
      float width,
      YogaMeasureMode widthMode,
      float height,
      YogaMeasureMode heightMode,
      @Nullable float[] attachmentsPositions) {
    return TextLayoutManager.measureText(
        context,
        localData,
        props,
        width,
        widthMode,
        height,
        heightMode,
        mReactTextViewManagerCallback,
        attachmentsPositions);
  }

  @Override
  public long measure(
      Context context,
      MapBuffer localData,
      MapBuffer props,
      @Nullable MapBuffer state,
      float width,
      YogaMeasureMode widthMode,
      float height,
      YogaMeasureMode heightMode,
      @Nullable float[] attachmentsPositions) {
    return TextLayoutManagerMapBuffer.measureText(
        context,
        localData,
        props,
        width,
        widthMode,
        height,
        heightMode,
        mReactTextViewManagerCallback,
        attachmentsPositions);
  }

  @Override
  public void setPadding(ReactTextView view, int left, int top, int right, int bottom) {
    view.setPadding(left, top, right, bottom);
  }
}


text:
using namespace Arc;

struct RenderData
	: public ManagedObject
{
public:

	virtual inline string getClassName( void ) const { return "Render Data"; }

	Scene*					pScene;
	mat4x4					View;
	mat4x4					Proj;
	mat4x4					ViewProj;
	vec3					AmbientLightAmount;
	vec3					GlobalLightColor;
	vec3					GlobalLightDirection;
	GLfloat					ElapsedTime;
	GLfloat					TimeOfDay;
};

#endif // GRAPHICS_II_RENDER_DATA_H


text:
package com.ibm.liberty.starter;

import java.io.InputStream;
import java.net.URI;
import java.util.logging.Logger;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.ibm.liberty.starter.api.v1.model.internal.Services;
import com.ibm.liberty.starter.api.v1.model.registration.Service;

public class ServiceConnector {

    private static final Logger log = Logger.getLogger(ServiceConnector.class.getName());

    private final Services services;
    private String serverHostPort;
    private final String internalServerHostPort;

    public ServiceConnector(URI uri) {
        String scheme = uri.getScheme();
        String authority = uri.getAuthority();
        serverHostPort = scheme + "://" + authority;
        internalServerHostPort = "http://" + authority;
        services = parseServicesJson();
    }

    public ServiceConnector(String hostPort, String internalHostPort) {
        serverHostPort = hostPort;
        internalServerHostPort = internalHostPort;
        services = parseServicesJson();
    }

    public Services parseServicesJson() {
        log.fine("Parsing services json file. INTERNAL_SERVER_HOST_PORT=" + internalServerHostPort);
        Services services = getObjectFromEndpoint(Services.class,
                internalServerHostPort + "/start/api/v1/services",
                                                  MediaType.APPLICATION_JSON_TYPE);
        log.fine("Setting SERVICES object to " + services.getServices());
        return services;
    }

    public Services getServices() {
        return services;
    }

    public String getServerHostPort() {
        return serverHostPort;
    }

    // Returns the service object associated with the given id
    public Service getServiceObjectFromId(String id) {
        log.fine("Return service object for " + id);
        Service service = null;
        for (Service s : services.getServices()) {
            if (id.equals(s.getId())) {
                return s;
            }
        }
        return service;
    }

    public String processUploadedFiles(Service service, String uploadDirectory) {
        log.finer("service=" + service.getId() + " : uploadDirectory=" + uploadDirectory);
        String url = urlConstructor("/api/v1/provider/uploads/process?path=" + uploadDirectory, service);
        String response = getObjectFromEndpoint(String.class, url, MediaType.TEXT_PLAIN_TYPE);
        log.fine("Response of processing uploaded files from " + uploadDirectory + " : " + response);
        return response;
    }

    public void prepareDynamicPackages(Service service, String techWorkspaceDir, String options, String[] techs) {
        log.finer("service=" + service.getId() + " : options=" + options + " : techWorkspaceDir=" + techWorkspaceDir + " : techs=" + techs);
        String optionsParam = (options != null && !options.trim().isEmpty()) ? ("&options=" + options) : "";
        String techsParam = "&techs=" + String.join(",", techs);
        String url = urlConstructor("/api/v1/provider/packages/prepare?path=" + techWorkspaceDir + optionsParam + techsParam, service);
        Response response = getResponseFromEndpoint(url, MediaType.TEXT_PLAIN_TYPE);
        String responseString = response.readEntity(String.class);
        if (response.getStatus() == 404) {
            // The service doesn't offer this endpoint, so the exception can be ignored.
            log.warning("Ignore expected 404 : The service doesn't offer endpoint " + url);
        } else {
            log.fine("Response of preparing dynamic packages from " + techWorkspaceDir + " : " + responseString);
        }
    }

    public InputStream getArtifactAsInputStream(Service service, String extension) {
        extension = extension.startsWith("/") ? extension.substring(1) : extension;
        String url = urlConstructor("/artifacts/" + extension, service);
        return getObjectFromEndpoint(InputStream.class, url, MediaType.WILDCARD_TYPE);
    }

    private String urlConstructor(String extension, Service service) {
        log.fine("Constructing url:" + internalServerHostPort + "+" + service.getEndpoint() + "+" + extension);
        String url = internalServerHostPort + service.getEndpoint() + extension;
        return url;
    }

    public < E > E getObjectFromEndpoint(Class<E> klass, String url, MediaType mediaType) {
        System.out.println("Getting object from url " + url);
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Invocation.Builder invoBuild = target.request();
        E object = invoBuild.accept(mediaType).get(klass);
        client.close();
        return object;
    }

    public Response getResponseFromEndpoint(String url, MediaType mediaType) {
        System.out.println("Getting object from url " + url);
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Invocation.Builder invoBuild = target.request();
        Response response = invoBuild.accept(mediaType).get();
        client.close();
        return response;
    }

}


text:
package eu.epfc.cours3449.Personne;

public class Personne {
    private char genre; // M ou F
    private String nom;
    private String prenom;
    private double age; // en années
    private String nationalite;
    //private String adresse; // complète: rue,numero,ville,pays
    private Addresse addresse;
    private String mailadresse;
    private String telephone;

    /*
    public Personne(){
        this.genre='M';
        this.nom="John";
        this.prenom="Doe";
    }

    public Personne(char genre, String nom, String prenom){
        this.genre=genre;
        this.nom=nom;
        this.prenom=prenom;
    }

    public Personne(char genre, String nom, String prenom, double age, String nationalite, String adresse, String mailadresse, String telephone) {
        this.genre = genre;
        this.nom = nom;
        this.prenom = prenom;
        this.age = age;
        this.nationalite = nationalite;
        this.adresse = adresse;
        this.mailadresse = mailadresse;
        this.telephone = telephone;
    }
    */
    public char getGenre(){
        return genre;
    }

    public void setGenre(char genre){
        this.genre=genre;
    }

    public String getNom(){
        return nom;
    }

    public void setNom(String nom){
        this.nom=nom;
    }

    public String getPrenom(){
        return nom;
    }

    public void setPrenom(String prenom){
        this.prenom=prenom;
    }

    public double getAge(){
        return age;
    }

    public void setAge(double age) {
        if (age<0 || age>200) {
            throw new IllegalArgumentException("Impossible age, please select another");
        }
        this.age=age;
    }

    public String getNationalite(){
        return nationalite;
    }

    public void setNationalite(String nationalite){
        this.nationalite=nationalite;
    }

    public Addresse getAddresse() {
        return addresse;
    }

    public void setAddresse(Addresse addresse) {
        this.addresse = addresse;
    }

    public String getMailadresse() {
        return mailadresse;
    }

    public void setMailadresse(String mailadresse) {
        this.mailadresse = mailadresse;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getTitre(){
        String titre;
        if(genre=='M') titre="M";
        else if(genre=='F') titre="Mme";
        else titre="La personne";
        return titre;
    }

    public String headToString(){
        return getTitre()+" "+nom+" "+prenom;
    }

    public String tailToString(){
        return ", de nationalité "+nationalite+", ayant pour adresse "+getAddresse()+", pour adresse mail "+mailadresse+" et comme numero de telephone "+telephone;
    }

    /*
    public String toString() {
        return headToString()+" "+tailToString();
    }

    public boolean equals(Personne p){
        boolean isequal=false;
        if (genre==p.getGenre() && getNom().equals(p.getNom()) && getPrenom().equals(p.getPrenom())
                && age==p.getAge() && getNationalite().equals(p.getNationalite())
                && getAdresse().equals(p.getAdresse()) && getMailadresse().equals(p.getMailadresse())
                && getTelephone().equals(p.getTelephone()))
            isequal=true;
        return isequal;
    }

    /*
    public boolean equals(char genre, String nom, String prenom, double age, String nationalite, String adresse, String mailadresse, String telephone){
        boolean isequal=false;
        if (this.genre==genre && this.nom.equals(nom) && this.prenom.equals(prenom)
                && this.nom.equals(nom) && this.age==age && this.nationalite.equals(nationalite)
                && this.adresse.equals(adresse) && this.mailadresse.equals(mailadresse)
                && this.telephone.equals(telephone)) {
            isequal=true;
        }
        return isequal;
    }
    */

    @Override
    public String toString() {
        return "Personne{" + "nom=" + nom + ", addresse=" + addresse + '}';
    }

}


text:
/**
 * Created by Ellery on 2018/5/7.
 * multiple select with select2
 */

// 获取 base path
var localObj = window.location;
var contextPath = localObj.pathname.split("/")[1];
var basePath2 = localObj.protocol + "//" + localObj.host;

$(document).ready(function() {
    // multi-select
    $('.js-example-basic-multiple').select2({
        // theme: "bootstrap",
        width: '100%',
        multiple: true,
        maximumSelectionLength: 5,
        minimumInputLength: 2,
        language: "zh-CN",
        placeholder: '添加话题',
        ajax: {
            url: basePath2 + '/topic-search',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    topicName: encodeURIComponent(params.term)
                };
            },
            processResults: function (data) {
                console.log(data);
                return {
                    results: data
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });

});

function formatRepo(repo) {
    return repo.topicName;
}
function formatRepoSelection(repo) {
    return repo.topicName;
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>twine</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" href="favicon.ico" type="image/x-icon" />

        <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700|Oswald' rel='stylesheet' type='text/css'>
        <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet">

        <link rel="stylesheet" href="css/main.css">

 Things have changed. Refresh your browser


text:
namespace IntegrationTests.Services.Locations
{
    using IntegrationTests.Middleware;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.eShopOnContainers.Services.Locations.API;
    using System.Security.Claims;
    using System.Threading.Tasks;

    public class LocationsTestsStartup : Startup
    {
        public LocationsTestsStartup(IHostingEnvironment env) : base(env)
        {
        }

        protected override void ConfigureAuth(IApplicationBuilder app)
        {
            if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant())
            {
                app.UseMiddleware<LocationAuthorizeMiddleware>();
            }
            else
            {
                base.ConfigureAuth(app);
            }
        }

        class LocationAuthorizeMiddleware
        {
            private readonly RequestDelegate _next;
            public LocationAuthorizeMiddleware(RequestDelegate rd)
            {
                _next = rd;
            }

            public async Task Invoke(HttpContext httpContext)
            {
                var identity = new ClaimsIdentity("cookies");
                identity.AddClaim(new Claim("sub", "4611ce3f-380d-4db5-8d76-87a8689058ed"));
                httpContext.User.AddIdentity(identity);
                await _next.Invoke(httpContext);
            }
        }
    }
}


text:
<?php

namespace SpBar\Bundle\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
* @ORM\Entity
* @ORM\Table(name="spbar_users")
* @ORM\HasLifecycleCallbacks
*/
class User extends BaseUser
{
    /**
    * @ORM\Column(type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @Gedmo\Timestampable(on="create")
    * @ORM\Column(name="created_at", type="datetime")
    */
    protected $createdAt;

    //personal informations

    /**
    * @Assert\NotBlank(groups={"Profile"})
    * @ORM\Column(name="firstname", type="string", length=100, nullable=true)
    */
    protected $firstname;

    /**
    * @Assert\NotBlank(groups={"Profile"})
    * @ORM\Column(name="lastname", type="string", length=100, nullable=true)
    */
    protected $lastname;

    /**
    * @Assert\NotBlank(groups={"Profile"})
    * @ORM\Column(name="date_of_birth", type="date", nullable=true)
    */
    protected $dateOfBirth;

    /**
    * @Assert\NotBlank(groups={"Profile"})
    * @Assert\Choice(choices={"Male", "Female"}, message="Invalid selection of gender.")
    * @ORM\Column(name="gender", type="string", nullable=true)
    */
    protected $gender;

    /**
    * Assert\Regex(pattern="/^([+]([0-9])*([\\(][0-9]+[\\)])*?)*$/", message="The number typed is invaild.", groups={"Profile"})
    * @ORM\Column(name="phone_number", type="string", nullable=true)
    */
    protected $phoneNumber;

    /**
    * Assert\Regex(pattern="/^([+][0-9]+)*$/", message="The number typed is invaild.", groups={"Profile"})
    * @ORM\Column(name="mobile_number", type="string", nullable=true)
    */
    protected $mobileNumber;

    /**
    * @Assert\NotBlank(groups={"Profile"})
    * @ORM\Column(name="address", type="string", length=255, nullable=true)
    */
    protected $address;

    /**
    * @ORM\Column(name="biography", type="text", length=255, nullable=true)
    */
    protected $biography;

    /**
    * @ORM\Column(name="website", type="string", length=100, nullable=true)
    */
    protected $website;

    //social informations
    /**
    * @ORM\Column(name="facebook_id", type="string",length=100, nullable=true)
    */
    protected $facebookId;

    /**
    * @ORM\Column(name="gplus_id", type="string",length=100, nullable=true)
    */
    protected $gplusId;

    /**
    * @ORM\Column(name="twitter_id", type="string",length=100, nullable=true)
    */
    protected $twitterId;

    /**
    * @ORM\Column(type="string", length=255, nullable=true)
    */
    protected $image;

    /**
    * @Assert\File(maxSize="6000000",
    * mimeTypes = {"image/jpg", "image/png", "image/jpeg"},
    * mimeTypesMessage = "Please upload a valid image")
    */
    private $tempImage;

    private $temp;

    /**
    * @ORM\ManyToMany(targetEntity="SpBar\Bundle\UserBundle\Entity\Group")
    * @ORM\JoinTable(name="spbar_user_group",
    *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
    *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
    * )
    */
    protected $groups;

    /*******************************files to be changed*******************************************/
        /**
        *@ORM\OneToMany(targetEntity="SpBar\Bundle\BlogBundle\Entity\Post", mappedBy="author", cascade={"persist"})
        */
        protected $posts = null;

        /**
        *@ORM\OneToMany(targetEntity="SpBar\Bundle\BlogBundle\Entity\Comment", mappedBy="user")
        */
        protected $comments;

        public function __construct()
        {
            parent::__construct();
            $this->posts = new ArrayCollection();
            $this->comments = new ArrayCollection();
        }
    /*******************************files to be changed*******************************************/

    public function getId()
    {
        return $this->id;
    }

    public function setCreatedAt($datetime)
    {
        $this->createdAt = $datetime;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setFirstname($fname)
    {
        $this->firstname = ucfirst($fname);
    }

    public function getFirstname()
    {
        return $this->firstname;
    }

    public function setLastname($lastname)
    {
        $this->lastname = ucfirst($lastname);
    }

    public function getLastname()
    {
        return $this->lastname;
    }

    public function getName()
    {
        return $this->firstname." ".$this->lastname;
    }

    public function setDateOfBirth($dob)
    {
        $this->dateOfBirth= $dob;
    }

    public function getDateOfBirth()
    {
        return $this->dateOfBirth;
    }

    public function setGender($gender)
    {
        $this->gender = $gender;
    }

    public function getGender()
    {
        return $this->gender;
    }

    public function setPhoneNumber($pnum)
    {
        $this->phoneNumber = $pnum;
    }

    public function getPhoneNumber()
    {
        return $this->phoneNumber;
    }

    public function setMobileNumber($mnum)
    {
        $this->mobileNumber = $mnum;
    }

    public function getMobileNumber()
    {
        return $this->mobileNumber;
    }

    public function setAddress($addr)
    {
        $this->address = $addr;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function setBiography($bio)
    {
        $this->biography = $bio;
    }

    public function getBiography()
    {
        return $this->biography;
    }

    public function setWebsite($webs)
    {
        $this->website = $webs;
    }

    public function getWebsite()
    {
        return $this->website;
    }

    public function setFacebookId($fid)
    {
        $this->facebookId = $fid;
    }

    public function getFacebookId()
    {
        return $this->facebookId;
    }

    public function setGplusId($gid)
    {
        $this->gplusId = $gid;
    }

    public function getGplusId()
    {
        return $this->gplusId;
    }

    public function setTwitterId($tid)
    {
        $this->twitterId = $tid;
    }

    public function getTwitterId()
    {
        return $this->twitterId;
    }

    public function setGroups($groups)
    {
            $this->addGroup($groups);
    }

    /*******************************files to be changed*******************************************/
        public function setPosts($post)
        {
            $this->posts[] = $post;
        }

        public function setComments($comment)
        {
            $this->comments[] = $comment;
        }
    /*******************************files to be changed*******************************************/

    public function getImage()
    {
        return $this->image;
    }

    public function setTempImage($image = null)
    {
        $this->tempImage = $image;
        // check if we have an old image path
        if (isset($this->image)) {
            // store the old name to delete after the update
            $this->temp = $this->image;
            $this->image = null;
        } else {
            $this->image = 'initial';
        }
    }

    public function getTempImage()
    {
        return $this->tempImage;
    }

    /**
    * @ORM\PrePersist()
    * @ORM\PreUpdate()
    */
    public function preUpload()
    {
        if (null !== $this->getTempImage()) {
            // do whatever you want to generate a unique name
            $imageName = sha1(uniqid(mt_rand(), true));
            $this->image = $imageName.'.'.$this->getTempImage()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->getTempImage()) {
            return;
        }

        // if there is an error when moving the file, an exception will
        // be automatically thrown by move(). This will properly prevent
        // the entity from being persisted to the database on error
        $this->getTempImage()->move($this->getUploadRootDir(), $this->image);

        // check if we have an old image
        if (isset($this->temp)) {
            // delete the old image
            unlink($this->getUploadRootDir().'/'.$this->temp);
            // clear the temp image path
            $this->temp = null;
        }
        $this->tempImage = null;
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        $image = $this->getAbsolutePath();
        if ($image) {
            unlink($image);
        }
    }

    public function getAbsolutePath()
    {
        return null === $this->image
            ? null
            : $this->getUploadRootDir().'/'.$this->image;
    }

    public function getWebPath()
    {
        return null === $this->image
            ? null
            : $this->getUploadDir().'/'.$this->image;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__.'/../../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/profile';
    }
}