text:
package com.example.lighthousecontroller.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/* adaptado de: https://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment*/
public class SimpleDialogFragment extends DialogFragment {
	public interface DialogResponseListener{
		public void onResponse(boolean positive);
	}
	private String dialogMessage;
	private String okMessage, cancelMessage;
	private DialogResponseListener dialogResponseListener;
	private int layoutId;
	private boolean isModal;
	private String title;

	public SimpleDialogFragment() {
		super();
		this.dialogMessage = "";
		this.okMessage = null;
		this.cancelMessage = null;
		this.dialogResponseListener = null;
		this.layoutId = 0;
		this.isModal = false;
		this.title = null;
	}

	public String getDialogMessage() { return dialogMessage; }
	public String getOkMessage() 	 { return okMessage; }
	public String getCancelMessage() { return cancelMessage;}
	public DialogResponseListener getDialogResponseListener() { return dialogResponseListener;}

	public void setDialogMessage(String dialogMessage) {
		this.dialogMessage = dialogMessage;
	}
	public void setOkMessage(String okMessage) {
		this.okMessage = okMessage;
	}
	public void hideOkButton() {
		this.okMessage = null;
	}
	public void setCancelMessage(String cancelMessage) {
		this.cancelMessage = cancelMessage;
	}
	public void hideCancelButton() {
		this.cancelMessage = null;
	}
	public void setDialogResponseListener(DialogResponseListener dialogResponseListener) {
		this.dialogResponseListener = dialogResponseListener;
	}

	public int getLayoutId() {
		return layoutId;
	}
	public void setLayoutId(int layoutId) {
		this.layoutId = layoutId;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(layoutId > 0 && !isModal){
        	return createView(layoutId, inflater, container);
        }
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		isModal = true;

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        if(layoutId > 0 && isModal){
        	LayoutInflater inflater = getActivity().getLayoutInflater();
        	View view = createView(layoutId, inflater, null);
        	builder.setView(view);
        }
        builder.setMessage(this.getDialogMessage());
        if(this.getTitle() != null){
        	builder.setTitle(getTitle());
        }
        if(isValidMessage(getOkMessage())){
        	builder.setPositiveButton(getOkMessage(), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    notifyResponse(true);
                }
            });
        };
        if(isValidMessage(getCancelMessage())){
        	builder.setNegativeButton(getCancelMessage(), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    notifyResponse(false);
                }
            })
            .setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
                    notifyResponse(false);
				}
			});
        };

        return builder.create();

	}

	protected View createView(int layoutId, LayoutInflater inflater, ViewGroup container) {
		return inflater.inflate(layoutId, container, false);
	}

	private boolean isValidMessage(String message) {
		return message != null && message.length() != 0;
	}

	private void notifyResponse(boolean response) {
		if(dialogResponseListener != null){
			dialogResponseListener.onResponse(response);
		}
	}

}


text:
<?php

namespace MtSimpleCms;

use RuntimeException;
use Zend\Cache\Storage\Adapter\AbstractAdapter as CacheAdapter;
use Zend\Cache\Storage\FlushableInterface;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Console\ColorInterface as Color;
use Zend\Console\Request as ConsoleRequest;
use Zend\Mvc\Controller\AbstractActionController;

class CacheController extends AbstractActionController
{
    protected $cache;

    protected $console;

    public function setCache(CacheAdapter $cache)
    {
        $this->cache = $cache;
    }

    public function setConsole(Console $console)
    {
        $this->console = $console;
    }

    public function clearAllAction()
    {
        $request = $this->getRequest();
        if (!$request instanceof ConsoleRequest) {
            throw new RuntimeException(sprintf(
                '%s can only be run from the console',
                __METHOD__
            ));
        }

        $this->console->writeLine('Clearing caches for all static pages', Color::BLUE);

        if (!$this->cache instanceof FlushableInterface) {
            $this->console->writeLine('Cache does not support flushing!', Color::RED);
            return;
        }

        $this->cache->flush();

        $this->console->writeLine('Cache operation complete', Color::GREEN);
    }

    public function clearOneAction()
    {
        $request = $this->getRequest();
        if (!$request instanceof ConsoleRequest) {
            throw new RuntimeException(sprintf(
                '%s can only be run from the console',
                __METHOD__
            ));
        }

        $page = $this->params()->fromRoute('page', false);
        if (!$page) {
            $this->console->writeLine('No page provided', Color::GREEN);
            return;
        }

        $this->console->writeLine(sprintf('Clearing cache for page "%s"', $page), Color::BLUE);

        $key = Module::normalizeCacheKey($page);
        if (!$this->cache->hasItem($key)) {
            $this->console->writeLine('Page is not in cache', Color::GREEN);
            return;
        }

        $this->cache->removeItem($key);

        $this->console->writeLine('Cache operation complete', Color::GREEN);
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'base_user_menu.html' %}
{% load AddCSSToTemplatesTag %}
{% load staticfiles %}

{% block CONTENT %}

User Profile

           Edit

    <form class="form-horizontal" action='/Profile/update-profile' method="POST">
      <fieldset>

        {% csrf_token %}
        {{ profile.non_field_errors }}

          First Name

              {{ profile.first_name|addcss:'class:form-control,aria-describedby:firstNameLabel,readOnly:True' }}

          Last Name

              {{ profile.last_name|addcss:'class:form-control,aria-describedby:lastNameLabel,readOnly:True' }}

          Email

              {{ profile.email|addcss:'class:form-control,aria-describedby:emailLabel,readOnly:True' }}

          Current Password

              {{ profile.old_password|addcss:'class:form-control,aria-describedby:currentPasswordLabel,readOnly:True' }}

          New Password

              {{ profile.new_password|addcss:'class:form-control,aria-describedby:newPasswordLabel,readOnly:True' }}

          Repeat
            Password

              {{ profile.repeat_new_password|addcss:'class:form-control,aria-describedby:repNewPasswordLabel,readOnly:True' }}

            <button id="updateProfileBtn" class="btn btn-success" value="Submit">Update Profile</button>

      </fieldset>
    </form>

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Sql
{
    /// <summary>
    /// Represents all the operations to manage Azure SQL Database and Database
    /// Server Audit policy.  Contains operations to: Create, Retrieve and
    /// Update audit policy.
    /// </summary>
    internal partial class AuditingPolicyOperations : IServiceOperations<SqlManagementClient>, IAuditingPolicyOperations
    {
        /// <summary>
        /// Initializes a new instance of the AuditingPolicyOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal AuditingPolicyOperations(SqlManagementClient client)
        {
            this._client = client;
        }

        private SqlManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.Azure.Management.Sql.SqlManagementClient.
        /// </summary>
        public SqlManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Creates or updates an Azure SQL Database auditing policy.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='databaseName'>
        /// Required. The name of the Azure SQL Database for which the auditing
        /// policy applies.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for createing or updating a Azure
        /// SQL Database auditing policy.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task<AzureOperationResponse> CreateOrUpdateDatebasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (databaseName == null)
            {
                throw new ArgumentNullException("databaseName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("databaseName", databaseName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatebasePolicyAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/databases/";
            url = url + Uri.EscapeDataString(databaseName);
            url = url + "/auditingPolicies/Default";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-04-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc = null;

                JObject databaseAuditingPolicyCreateOrUpdateParametersValue = new JObject();
                requestDoc = databaseAuditingPolicyCreateOrUpdateParametersValue;

                JObject propertiesValue = new JObject();
                databaseAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;

                if (parameters.Properties.AuditingState != null)
                {
                    propertiesValue["auditingState"] = parameters.Properties.AuditingState;
                }

                if (parameters.Properties.EventTypesToAudit != null)
                {
                    propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
                }

                if (parameters.Properties.StorageAccountName != null)
                {
                    propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
                }

                if (parameters.Properties.StorageAccountKey != null)
                {
                    propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
                }

                if (parameters.Properties.StorageAccountSecondaryKey != null)
                {
                    propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
                }

                if (parameters.Properties.StorageTableEndpoint != null)
                {
                    propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
                }

                if (parameters.Properties.StorageAccountResourceGroupName != null)
                {
                    propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
                }

                if (parameters.Properties.StorageAccountSubscriptionId != null)
                {
                    propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
                }

                if (parameters.Properties.RetentionDays != null)
                {
                    propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
                }

                if (parameters.Properties.UseServerDefault != null)
                {
                    propertiesValue["useServerDefault"] = parameters.Properties.UseServerDefault;
                }

                if (parameters.Properties.AuditLogsTableName != null)
                {
                    propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
                }

                requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AzureOperationResponse result = null;
                    // Deserialize Response
                    result = new AzureOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Creates or updates an Azure SQL Database Server auditing policy.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for createing or updating a Azure
        /// SQL Database Server auditing policy.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task<AzureOperationResponse> CreateOrUpdateServerPolicyAsync(string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateServerPolicyAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/auditingPolicies/Default";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-04-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc = null;

                JObject serverAuditingPolicyCreateOrUpdateParametersValue = new JObject();
                requestDoc = serverAuditingPolicyCreateOrUpdateParametersValue;

                JObject propertiesValue = new JObject();
                serverAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;

                if (parameters.Properties.AuditingState != null)
                {
                    propertiesValue["auditingState"] = parameters.Properties.AuditingState;
                }

                if (parameters.Properties.EventTypesToAudit != null)
                {
                    propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
                }

                if (parameters.Properties.StorageAccountName != null)
                {
                    propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
                }

                if (parameters.Properties.StorageAccountKey != null)
                {
                    propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
                }

                if (parameters.Properties.StorageAccountSecondaryKey != null)
                {
                    propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
                }

                if (parameters.Properties.StorageTableEndpoint != null)
                {
                    propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
                }

                if (parameters.Properties.StorageAccountResourceGroupName != null)
                {
                    propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
                }

                if (parameters.Properties.StorageAccountSubscriptionId != null)
                {
                    propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
                }

                if (parameters.Properties.RetentionDays != null)
                {
                    propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
                }

                if (parameters.Properties.AuditLogsTableName != null)
                {
                    propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
                }

                requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AzureOperationResponse result = null;
                    // Deserialize Response
                    result = new AzureOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Returns an Azure SQL Database auditing policy.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='databaseName'>
        /// Required. The name of the Azure SQL Database for which the auditing
        /// policy applies.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a get database auditing policy request.
        /// </returns>
        public async Task<DatabaseAuditingPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (databaseName == null)
            {
                throw new ArgumentNullException("databaseName");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("databaseName", databaseName);
                TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/databases/";
            url = url + Uri.EscapeDataString(databaseName);
            url = url + "/auditingPolicies/Default";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-04-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DatabaseAuditingPolicyGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DatabaseAuditingPolicyGetResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            DatabaseAuditingPolicy auditingPolicyInstance = new DatabaseAuditingPolicy();
                            result.AuditingPolicy = auditingPolicyInstance;

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                DatabaseAuditingPolicyProperties propertiesInstance = new DatabaseAuditingPolicyProperties();
                                auditingPolicyInstance.Properties = propertiesInstance;

                                JToken auditingStateValue = propertiesValue["auditingState"];
                                if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
                                {
                                    string auditingStateInstance = ((string)auditingStateValue);
                                    propertiesInstance.AuditingState = auditingStateInstance;
                                }

                                JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
                                if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
                                {
                                    string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
                                    propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
                                }

                                JToken storageAccountNameValue = propertiesValue["storageAccountName"];
                                if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountNameInstance = ((string)storageAccountNameValue);
                                    propertiesInstance.StorageAccountName = storageAccountNameInstance;
                                }

                                JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
                                if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
                                {
                                    string storageAccountKeyInstance = ((string)storageAccountKeyValue);
                                    propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
                                }

                                JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
                                if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
                                {
                                    string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
                                    propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
                                }

                                JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
                                if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
                                {
                                    string storageTableEndpointInstance = ((string)storageTableEndpointValue);
                                    propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
                                }

                                JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
                                if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
                                    propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
                                }

                                JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
                                if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
                                {
                                    string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
                                    propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
                                }

                                JToken retentionDaysValue = propertiesValue["retentionDays"];
                                if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
                                {
                                    string retentionDaysInstance = ((string)retentionDaysValue);
                                    propertiesInstance.RetentionDays = retentionDaysInstance;
                                }

                                JToken useServerDefaultValue = propertiesValue["useServerDefault"];
                                if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null)
                                {
                                    string useServerDefaultInstance = ((string)useServerDefaultValue);
                                    propertiesInstance.UseServerDefault = useServerDefaultInstance;
                                }

                                JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
                                if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
                                {
                                    string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
                                    propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
                                }
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                auditingPolicyInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                auditingPolicyInstance.Name = nameInstance;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                auditingPolicyInstance.Type = typeInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                auditingPolicyInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Returns an Azure SQL Database server auditing policy.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a get database auditing policy request.
        /// </returns>
        public async Task<ServerAuditingPolicyGetResponse> GetServerPolicyAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                TracingAdapter.Enter(invocationId, this, "GetServerPolicyAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/auditingPolicies/Default";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-04-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerAuditingPolicyGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new ServerAuditingPolicyGetResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            ServerAuditingPolicy auditingPolicyInstance = new ServerAuditingPolicy();
                            result.AuditingPolicy = auditingPolicyInstance;

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                ServerAuditingPolicyProperties propertiesInstance = new ServerAuditingPolicyProperties();
                                auditingPolicyInstance.Properties = propertiesInstance;

                                JToken auditingStateValue = propertiesValue["auditingState"];
                                if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
                                {
                                    string auditingStateInstance = ((string)auditingStateValue);
                                    propertiesInstance.AuditingState = auditingStateInstance;
                                }

                                JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
                                if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
                                {
                                    string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
                                    propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
                                }

                                JToken storageAccountNameValue = propertiesValue["storageAccountName"];
                                if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountNameInstance = ((string)storageAccountNameValue);
                                    propertiesInstance.StorageAccountName = storageAccountNameInstance;
                                }

                                JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
                                if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
                                {
                                    string storageAccountKeyInstance = ((string)storageAccountKeyValue);
                                    propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
                                }

                                JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
                                if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
                                {
                                    string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
                                    propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
                                }

                                JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
                                if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
                                {
                                    string storageTableEndpointInstance = ((string)storageTableEndpointValue);
                                    propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
                                }

                                JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
                                if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
                                    propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
                                }

                                JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
                                if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
                                {
                                    string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
                                    propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
                                }

                                JToken retentionDaysValue = propertiesValue["retentionDays"];
                                if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
                                {
                                    string retentionDaysInstance = ((string)retentionDaysValue);
                                    propertiesInstance.RetentionDays = retentionDaysInstance;
                                }

                                JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
                                if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
                                {
                                    string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
                                    propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
                                }
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                auditingPolicyInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                auditingPolicyInstance.Name = nameInstance;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                auditingPolicyInstance.Type = typeInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                auditingPolicyInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
using System.Reflection;

namespace NMoneys.Demo.CodeProject.Support
{
	internal static class CurrencyIsoCodeExtensions
	{
		internal static ICustomAttributeProvider AsAttributeProvider(this CurrencyIsoCode code)
		{
			return typeof(CurrencyIsoCode).GetField(code.ToString());
		}
	}
}


text:
package org.myrobotlab.service.interfaces;

import org.myrobotlab.framework.interfaces.NameProvider;

public interface HttpResponseListener extends NameProvider {

  public void onHttpResponse(String data);

}


text:
import styled from 'styled-components';
export default styled.section`
 width: 100%;
 display: flex;
 &::after {
   content: ' ';
   clear: both;
   display: block;
 }

 @media(max-width: 1320px) {
 }
 @media(max-width: 970px) {
   display: block;
 }
`;


text:
namespace net {

namespace {

// Matches the caIssuers hostname from the generated certificate.
const char kAiaHost[] = "aia-test.invalid";
// Returning a single DER-encoded cert, so the mime-type must be
// application/pkix-cert per RFC 5280.
const char kAiaHeaders[] = "HTTP/1.1 200 OK\0"
                           "Content-type: application/pkix-cert\0"
                           "\0";

class AiaResponseHandler : public URLRequestInterceptor {
 public:
  AiaResponseHandler(const std::string& headers, const std::string& cert_data)
      : headers_(headers), cert_data_(cert_data), request_count_(0) {}
  ~AiaResponseHandler() override {}

  // URLRequestInterceptor implementation:
  URLRequestJob* MaybeInterceptRequest(
      URLRequest* request,
      NetworkDelegate* network_delegate) const override {
    ++const_cast<AiaResponseHandler*>(this)->request_count_;

    return new URLRequestTestJob(request, network_delegate, headers_,
                                 cert_data_, true);
  }

  int request_count() const { return request_count_; }

 private:
  std::string headers_;
  std::string cert_data_;
  int request_count_;

  DISALLOW_COPY_AND_ASSIGN(AiaResponseHandler);
};

}  // namespace

class NssHttpTest : public ::testing::Test {
 public:
  NssHttpTest()
      : context_(false),
        handler_(NULL),
        verify_proc_(new CertVerifyProcNSS),
        verifier_(new MultiThreadedCertVerifier(verify_proc_.get())) {}
  ~NssHttpTest() override {}

  void SetUp() override {
    std::string file_contents;
    ASSERT_TRUE(base::ReadFileToString(
        GetTestCertsDirectory().AppendASCII("aia-intermediate.der"),
        &file_contents));
    ASSERT_FALSE(file_contents.empty());

    // Ownership of |handler| is transferred to the URLRequestFilter, but
    // hold onto the original pointer in order to access |request_count()|.
    scoped_ptr<AiaResponseHandler> handler(
        new AiaResponseHandler(kAiaHeaders, file_contents));
    handler_ = handler.get();

    URLRequestFilter::GetInstance()->AddHostnameInterceptor(
        "http", kAiaHost, handler.Pass());

    SetURLRequestContextForNSSHttpIO(&context_);
    EnsureNSSHttpIOInit();
  }

  void TearDown() override {
    ShutdownNSSHttpIO();

    if (handler_)
      URLRequestFilter::GetInstance()->RemoveHostnameHandler("http", kAiaHost);
  }

  CertVerifier* verifier() const {
    return verifier_.get();
  }

  int request_count() const {
    return handler_->request_count();
  }

 protected:
  const CertificateList empty_cert_list_;

 private:
  TestURLRequestContext context_;
  AiaResponseHandler* handler_;
  scoped_refptr<CertVerifyProc> verify_proc_;
  scoped_ptr<CertVerifier> verifier_;
};

// Tests that when using NSS to verify certificates, and IO is enabled,
// that a request to fetch missing intermediate certificates is
// made successfully.
TEST_F(NssHttpTest, TestAia) {
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(GetTestCertsDirectory(), "aia-cert.pem"));
  ASSERT_TRUE(test_cert.get());

  scoped_refptr<X509Certificate> test_root(
      ImportCertFromFile(GetTestCertsDirectory(), "aia-root.pem"));
  ASSERT_TRUE(test_root.get());

  ScopedTestRoot scoped_root(test_root.get());

  CertVerifyResult verify_result;
  TestCompletionCallback test_callback;
  scoped_ptr<CertVerifier::Request> request;

  int flags = CertVerifier::VERIFY_CERT_IO_ENABLED;
  int error = verifier()->Verify(
      test_cert.get(), "aia-host.invalid", std::string(), flags, NULL,
      &verify_result, test_callback.callback(), &request, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);

  error = test_callback.WaitForResult();

  EXPECT_EQ(OK, error);

  // Ensure that NSS made an AIA request for the missing intermediate.
  EXPECT_LT(0, request_count());
}

}  // namespace net


text:
package com.cloud.consoleproxy;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.ejb.Local;
import javax.naming.ConfigurationException;

import com.cloud.utils.component.AdapterBase;
import com.cloud.vm.ConsoleProxyVO;

import edu.emory.mathcs.backport.java.util.Collections;

@Local(value={ConsoleProxyAllocator.class})
public class ConsoleProxyBalanceAllocator extends AdapterBase implements ConsoleProxyAllocator {

    private final Random _rand = new Random(System.currentTimeMillis());

    @Override
    public ConsoleProxyVO allocProxy(List<ConsoleProxyVO> candidates, final Map<Long, Integer> loadInfo, long dataCenterId) {
        if(candidates != null) {

            List<ConsoleProxyVO> allocationList = new ArrayList<ConsoleProxyVO>();
            for(ConsoleProxyVO proxy : candidates) {
                allocationList.add(proxy);
            }

            Collections.sort(candidates, new Comparator<ConsoleProxyVO> () {
                @Override
                public int compare(ConsoleProxyVO x, ConsoleProxyVO y) {
                    Integer loadOfX = loadInfo.get(x.getId());
                    Integer loadOfY = loadInfo.get(y.getId());

                    if(loadOfX != null && loadOfY != null) {
                        if(loadOfX < loadOfY)
                            return -1;
                        else if(loadOfX > loadOfY)
                            return 1;
                        return 0;
                    } else if(loadOfX == null && loadOfY == null) {
                        return 0;
                    } else {
                        if(loadOfX == null)
                            return -1;
                        return 1;
                    }
                }
            });

            if(allocationList.size() > 0)
                return allocationList.get(0);
        }
        return null;
    }

    @Override
    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
        return true;
    }

    @Override
    public boolean start() {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}


text:
<{{menu.currentPage|humanizeDoc}} />

In some scenarios on Mobile devices (without jQuery), the click events should NOT be hijacked.
$mdGestureProvider is used to configure the Gesture module to ignore or skip click hijacking on mobile
devices.

<hljs lang="js">
  app.config(function($mdGestureProvider) {

    // For mobile devices without jQuery loaded, do not
    // intercept click events during the capture phase.
    $mdGestureProvider.skipClickHijack();

  });
</hljs>


text:
using System;

namespace Hawk.Core.Utils.Plugins
{
    /// <summary>
    /// 该类定义了插件系统的接口契约记录
    /// </summary>
     [Serializable]
    public class InterfaceAttribute : System.Attribute
    {
        public InterfaceAttribute()
        {
        }

        public string Name { get; set; }
        /// <summary>
        /// 相关信息
        /// </summary>
        public string Description { get; set; }

        public InterfaceAttribute(string thisDetailInfo=null)
        // 定位参数
        {

            this.Description = thisDetailInfo;

        }

    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="MeshTexture" inherits="Texture" category="Core" version="3.2">
	<brief_description>
		Simple texture that uses a mesh to draw itself.
	</brief_description>
	<description>
		Simple texture that uses a mesh to draw itself. It's limited because flags can't be changed and region drawing is not supported.
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<members>
		<member name="base_texture" type="Texture" setter="set_base_texture" getter="get_base_texture">
			Set the base texture that the Mesh will use to draw.
		</member>
		<member name="image_size" type="Vector2" setter="set_image_size" getter="get_image_size">
			Set the size of the image, needed for reference.
		</member>
		<member name="mesh" type="Mesh" setter="set_mesh" getter="get_mesh">
			Set the mesh used to draw. It must be a mesh using 2D vertices.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
import matplotlib.delaunay as md
from scipy import ndimage
from pylab import *
from numpy import *

from PCV.geometry import homography

def image_in_image(im1,im2,tp):
    """ Put im1 in im2 with an affine transformation
        such that corners are as close to tp as possible.
        tp are homogeneous and counter-clockwise from top left. """

    # points to warp from
    m,n = im1.shape[:2]
    fp = array([[0,m,m,0],[0,0,n,n],[1,1,1,1]])

    # compute affine transform and apply
    H = homography.Haffine_from_points(tp,fp)
    im1_t = ndimage.affine_transform(im1,H[:2,:2],
                    (H[0,2],H[1,2]),im2.shape[:2])
    alpha = (im1_t > 0)

    return (1-alpha)*im2 + alpha*im1_t

def combine_images(im1,im2,alpha):
    """ Blend two images with weights as in alpha. """
    return (1-alpha)*im1 + alpha*im2

def alpha_for_triangle(points,m,n):
    """ Creates alpha map of size (m,n)
        for a triangle with corners defined by points
        (given in normalized homogeneous coordinates). """

    alpha = zeros((m,n))
    for i in range(min(points[0]),max(points[0])):
        for j in range(min(points[1]),max(points[1])):
            x = linalg.solve(points,[i,j,1])
            if min(x) > 0: #all coefficients positive
                alpha[i,j] = 1
    return alpha

def triangulate_points(x,y):
    """ Delaunay triangulation of 2D points. """

    centers,edges,tri,neighbors = md.delaunay(x,y)
    return tri

def plot_mesh(x,y,tri):
    """ Plot triangles. """

    for t in tri:
        t_ext = [t[0], t[1], t[2], t[0]] # add first point to end
        plot(x[t_ext],y[t_ext],'r')

def pw_affine(fromim,toim,fp,tp,tri):
    """ Warp triangular patches from an image.
        fromim = image to warp
        toim = destination image
        fp = from points in hom. coordinates
        tp = to points in hom.  coordinates
        tri = triangulation. """

    im = toim.copy()

    # check if image is grayscale or color
    is_color = len(fromim.shape) == 3

    # create image to warp to (needed if iterate colors)
    im_t = zeros(im.shape, 'uint8')

    for t in tri:
        # compute affine transformation
        H = homography.Haffine_from_points(tp[:,t],fp[:,t])

        if is_color:
            for col in range(fromim.shape[2]):
                im_t[:,:,col] = ndimage.affine_transform(
                    fromim[:,:,col],H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])
        else:
            im_t = ndimage.affine_transform(
                    fromim,H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])

        # alpha for triangle
        alpha = alpha_for_triangle(tp[:,t],im.shape[0],im.shape[1])

        # add triangle to image
        im[alpha>0] = im_t[alpha>0]

    return im

def panorama(H,fromim,toim,padding=2400,delta=2400):
    """ Create horizontal panorama by blending two images
        using a homography H (preferably estimated using RANSAC).
        The result is an image with the same height as toim. 'padding'
        specifies number of fill pixels and 'delta' additional translation. """

    # check if images are grayscale or color
    is_color = len(fromim.shape) == 3

    # homography transformation for geometric_transform()
    def transf(p):
        p2 = dot(H,[p[0],p[1],1])
        return (p2[0]/p2[2],p2[1]/p2[2])

    if H[1,2]<0: # fromim is to the right
        print 'warp - right'
        # transform fromim
        if is_color:
            # pad the destination image with zeros to the right
            toim_t = hstack((toim,zeros((toim.shape[0],padding,3))))
            fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2]))
            for col in range(3):
                fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col],
                                        transf,(toim.shape[0],toim.shape[1]+padding))
        else:
            # pad the destination image with zeros to the right
            toim_t = hstack((toim,zeros((toim.shape[0],padding))))
            fromim_t = ndimage.geometric_transform(fromim,transf,
                                    (toim.shape[0],toim.shape[1]+padding))
    else:
        print 'warp - left'
        # add translation to compensate for padding to the left
        H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]])
        H = dot(H,H_delta)
        # transform fromim
        if is_color:
            # pad the destination image with zeros to the left
            toim_t = hstack((zeros((toim.shape[0],padding,3)),toim))
            fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2]))
            for col in range(3):
                fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col],
                                            transf,(toim.shape[0],toim.shape[1]+padding))
        else:
            # pad the destination image with zeros to the left
            toim_t = hstack((zeros((toim.shape[0],padding)),toim))
            fromim_t = ndimage.geometric_transform(fromim,
                                    transf,(toim.shape[0],toim.shape[1]+padding))

    # blend and return (put fromim above toim)
    if is_color:
        # all non black pixels
        alpha = ((fromim_t[:,:,0] * fromim_t[:,:,1] * fromim_t[:,:,2] ) > 0)
        for col in range(3):
            toim_t[:,:,col] = fromim_t[:,:,col]*alpha + toim_t[:,:,col]*(1-alpha)
    else:
        alpha = (fromim_t > 0)
        toim_t = fromim_t*alpha + toim_t*(1-alpha)

    return toim_t


text:
{{tag}}
  x

  <input ng-model='currentTag' ng-blur="addTag(currentTag)" type="text" value="" />


text:
package saltchannel.a1a2;

import saltchannel.ByteChannel;

/**
 * The client-side of one A1-A2 session.
 *
 * @author Frans Lundberg
 */
public class A1Client {
    private ByteChannel channel;
    private A1Packet a1;

    public A1Client(ByteChannel channel) {
        this.channel = channel;
        this.a1 = new A1Packet();
    }

    /**
     * Allows the consumer to modify A1 before it is sent.
     */
    public A1Packet getA1() {
        return a1;
    }

    public A2Packet go() {
        byte[] buffer = new byte[a1.getSize()];
        a1.toBytes(buffer, 0);
        channel.write(false, buffer);

        byte[] response = channel.read();
        A2Packet a2 = A2Packet.fromBytes(response, 0);
        return a2;
    }
}


text:
module Lobbyist
  module V2

    class CustomerTag < Lobbyist::V2::Base
      attr_accessor :id, :company_id, :filename, :status, :created_at, :updated_at

      def self.create(params = {})
        create_from_response(post("/v2/customer_tags.json", { customer_tag: params }, true))
      end
    end
  end
end


text:
import sys
from setuptools import setup, find_packages

try:
    __import__('multiprocessing')
except:
    pass

if 'nosetests' in sys.argv:
    setup_requires = ['nose']
else:
    setup_requires = []

tests_require = [
    'mock',
    'nose',
    'pycassa',
    'pylibmc',
    'redis',
    'riak',
    'thoonk',
    'unittest2',
]

dependency_links = [
    'https://github.com/andyet/thoonk.py/tarball/master#egg=thoonk',
]

install_requires = [
]

setup(
    name='nydus',
    version='0.11.0',
    author='DISQUS',
    author_email='opensource@disqus.com',
    url='https://github.com/disqus/nydus',
    description='Connection utilities',
    packages=find_packages(exclude=('tests',)),
    zip_safe=False,
    setup_requires=setup_requires,
    install_requires=install_requires,
    dependency_links=dependency_links,
    tests_require=tests_require,
    extras_require={'test': tests_require},
    test_suite='nose.collector',
    include_package_data=True,
    license='Apache License 2.0',
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Operating System :: OS Independent',
        'Topic :: Software Development'
    ],
)


text:
/** @file test_zmqreqrep_req_socket_connect_fail.c

This file tests whether ZMQ Requester socket fails when we pass the Invalid IP Address.
*/

#include <stdio.h>
#include <zmq.h>
#include <zmq_utils.h>
#include "iotkit-comm.h"

int main(void) {
    ServiceQuery *serviceQuery = (ServiceQuery *)malloc(sizeof(ServiceQuery));
    if (serviceQuery != NULL) {
        serviceQuery->address = "127.0.0.123232132321323123232233";
        serviceQuery->port = 100;
        int result = init(serviceQuery, NULL);
        done();
        free(serviceQuery);
        if (result == 0) {
            puts("Requester Socket Successfully Connected");
        } else {
            puts("Failed: Requester Socket Binding");
            exit(EXIT_SUCCESS);
        }
    }
    exit(EXIT_FAILURE);
}


text:
package org.apache.james.user.jcr.model;

import org.apache.jackrabbit.util.Text;
import org.apache.james.user.api.model.User;

/**
 * User backed by JCR data. Differs from standard James by improved hash. TODO:
 * think about improving DefaultUser.
 */
public class JCRUser implements User {

    /**
     * Static salt for hashing password. Modifying this value will render all
     * passwords unrecognizable.
     */
    public static final String SALT = "JCRUsersRepository";

    /**
     * Hashes salted password.
     *
     * @param username
     *            not null
     * @param password
     *            not null
     * @return not null
     */
    public static String hashPassword(String username, String password) {
        // Combine dynamic and static salt
        final String hashedSaltedPassword = Text.md5(Text.md5(username + password) + SALT);
        return hashedSaltedPassword;
    }

    private final String userName;
    private String hashedSaltedPassword;

    public JCRUser(final String userName, String hashedSaltedPassword) {
        super();
        this.userName = userName;
        this.hashedSaltedPassword = hashedSaltedPassword;
    }

    public String getUserName() {
        return userName;
    }

    /**
     * Gets salted, hashed password.
     *
     * @return the hashedSaltedPassword
     */
    public final String getHashedSaltedPassword() {
        return hashedSaltedPassword;
    }

    public boolean setPassword(String newPass) {
        final boolean result;
        if (newPass == null) {
            result = false;
        } else {
            hashedSaltedPassword = hashPassword(userName, newPass);
            result = true;
        }
        return result;
    }

    public boolean verifyPassword(String pass) {
        final boolean result;
        if (pass == null) {
            result = false;
        } else {
            result = hashedSaltedPassword.equals(hashPassword(userName, pass));
        }
        return result;
    }
}


text:
Powerful, flexible web routing for PSR-7 requests.

## Installation and Autoloading

This package is installable and PSR-4 autoloadable via Composer as
[aura/router][].

Alternatively, [download a release][], or clone this repository, then map the
`Aura\Router\` namespace to the package `src/` directory.

## Dependencies

This package requires PHP 5.5 or later. It has been tested on PHP 5.5-8.1. We recommend using the latest available version of PHP as a matter of principle.

Aura library packages may sometimes depend on external interfaces, but never on
external implementations. This allows compliance with community standards
without compromising flexibility. For specifics, please examine the package
[composer.json][] file.

## Quality

[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/auraphp/Aura.Router/badges/quality-score.png?b=3.x)](https://scrutinizer-ci.com/g/auraphp/Aura.Router/)
[![codecov](https://codecov.io/gh/auraphp/Aura.Router/branch/3.x/graph/badge.svg?token=UASDouLxyc)](https://codecov.io/gh/auraphp/Aura.Router)
[![Continuous Integration](https://github.com/auraphp/Aura.Router/actions/workflows/continuous-integration.yml/badge.svg?branch=3.x)](https://github.com/auraphp/Aura.Router/actions/workflows/continuous-integration.yml)

To run the unit tests at the command line, issue `composer install` and then
`./vendor/bin/phpunit` at the package root. (This requires [Composer][] to be
available as `composer`.)

This package attempts to comply with [PSR-1][], [PSR-2][], and [PSR-4][]. If
you notice compliance oversights, please send a patch via pull request.

## Community

To ask questions, provide feedback, or otherwise communicate with other Aura
users, please join our [Google Group][], follow [@auraphp][], or chat with us
on Freenode in the #auraphp channel.

## Documentation

This package is fully documented [here](./docs/index.md).

[PSR-1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md
[PSR-2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md
[Composer]: http://getcomposer.org/
[PHPUnit]: http://phpunit.de/
[Google Group]: http://groups.google.com/group/auraphp
[@auraphp]: http://twitter.com/auraphp
[download a release]: https://github.com/auraphp/Aura.Router/releases
[aura/router]: https://packagist.org/packages/aura/router
[composer.json]: ./composer.json


text:
var jsx = require('../../index').jsxTranspile(process.env.COVERAGE);
var assert = require('assert');

describe('UnnamedComponent', function() {
    var UnnamedComponent = require('../UnnamedComponent.jsx');

    describe('#render', function () {
        it('renders with
UNNAMED_COMPONENT
', function () {
            jsx.assertRender(UnnamedComponent, {}, '
UNNAMED_COMPONENT
');
        });
    });
});


text:
<?php

namespace Moulino\Framework\Auth;

use Moulino\Framework\Service\Container;
use Moulino\Framework\Model\ModelInterface;
use Moulino\Framework\Config\Config as AppConfig;

use Moulino\Framework\Auth\Exception\JwtKeyNotConfiguredException;
use Moulino\Framework\Auth\Exception\BadCredentialsException;
use Firebase\JWT\JWT;

class JwtAuthenticator extends AbstractAuthenticator
{
	const JWT_KEY_NOT_CONFIGURED = "The key for jwt is not configured";

	private $request = null;

	public function __construct(Container $container, ModelInterface $model, $salt) {
		parent::__construct($container, $model, $salt);
		$this->request = $container->get('request');
	}

	public function isAuthenticated($remoteAddr) {
		$headers = $this->request->getHeaders();

		if(isset($headers['Authorization'])) {
			$authorization = $headers['Authorization'];
			$regex = '#^Bearer ([A-Za-z0-9\-\._~\+\/]+=*)#';
			$key = $this->getKey();

			if(preg_match($regex, $authorization, $matches)) {
				$decoded = (array) JWT::decode($matches[1], $key, array('HS256'));
				if(isset($decoded['user_id']) && isset($decoded['remoteAddr'])) {
					if($decoded['remoteAddr'] === $remoteAddr) return true;
				}
			}
		}
		return false;
	}

	public function login($remoteAddr, $user_id, $password) {
		$user = $this->fetchUser($user_id);
		$pwdEnc = $this->encodePassword($password);

		if($user['password'] == $pwdEnc) {
			$data = array(
				'remoteAddr' => $remoteAddr,
				'user_id' => $user['user_id'],
				'name' => $user['name'],
				'roles' => (is_null($user['roles'])) ? array() : explode(',', $user['roles'])
			);

			$key = $this->getKey();
			$jwt = JWT::encode($data, $key);
			return $jwt;
		}
		$this->model->set($user['id'], array('errors' => intval($user['errors']) +1));
		throw new BadCredentialsException($this->translator->tr(self::WRONG_PASSWORD), 403);
	}

	public function getAuthInfo() {
		$headers = $this->request->getHeaders();
		$decoded = array();

		if(isset($headers['Authorization'])) {
			$authorization = $headers['Authorization'];
			$regex = '#^Bearer ([A-Za-z0-9\-\._~\+\/]+=*)#';
			$key = $this->getKey();

			if(preg_match($regex, $authorization, $matches)) {
				$decoded = (array) JWT::decode($matches[1], $key, array('HS256'));
			}
		}

		$authInfo = array(
			'authenticated' => isset($decoded['user_id']),
			'user_id' => isset($decoded['user_id']) ? $decoded['user_id'] : '',
			'name' => isset($decoded['name']) ? $decoded['name'] : '',
			'roles' => isset($decoded['roles']) ? $decoded['roles'] : array()
		);

		return $authInfo;
	}

	private function getKey() {
		if(!AppConfig::isDefined('security.jwt_key')) {
			throw new JwtKeyNotConfiguredException($this->translator->tr(self::JWT_KEY_NOT_CONFIGURED));
		}
		return AppConfig::get('security.jwt_key');
	}

	/**
	 * Check if the user has the role specified.
	 * @param string Role name
	 * @return boolean
	 */
	public function hasRole($role) {
		$authInfo = $this->getAuthInfo();
		return in_array($role, $authInfo['roles']);
	}
}


text:
package org.tinylog.benchmarks.logging.logback_;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.tinylog.benchmarks.logging.core.LocationInfo;
import org.tinylog.benchmarks.logging.logback_.util.LogbackUtil;

import static org.assertj.core.api.Assertions.assertThat;

@TestMethodOrder(OrderAnnotation.class)
class FullLocationInformationTest {

	private static final String NEW_LINE = System.lineSeparator();

	private static Logback_Benchmark benchmark;

	/**
	 * Initializes the benchmark including the logging framework.
	 *
	 * @throws Exception Failed to configure the logging framework
	 */
	@BeforeAll
	static void init() throws Exception {
		benchmark = new Logback_Benchmark(LocationInfo.FULL);
		benchmark.configure();
	}

	/**
	 * Shuts the benchmark including the logging framework gracefully down.
	 */
	@AfterAll
	static void dispose() {
		benchmark.shutdown();
	}

	/**
	 * Verifies that the debug log entry will be not output.
	 */
	@Test
	@Order(1)
	void discard() throws InterruptedException, IOException {
		benchmark.discard();
		LogbackUtil.flush();

		String logFile = benchmark.getLogFile();
		assertThat(logFile).isNotNull();

		Path path = Paths.get(logFile);
		assertThat(path).isEmptyFile();
	}

	/**
	 * Verifies that the into log entry will be output correctly.
	 */
	@Test
	@Order(2)
	void output() throws InterruptedException, IOException {
		benchmark.output();
		LogbackUtil.flush();

		String logFile = benchmark.getLogFile();
		assertThat(logFile).isNotNull();

		Path path = Paths.get(logFile);
		assertThat(path)
			.content(StandardCharsets.UTF_8)
			.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} - main - org\\.tinylog\\.benchmarks\\.logging\\."
				+ "logback_\\.Logback_Benchmark\\.output\\(\\) - INFO: Hello 42!" + NEW_LINE);
	}

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.cooloongwu.coolchat.activity.UserProfileActivity">
    <item
        android:id="@+id/action_create"
        android:orderInCategory="100"
        app:showAsAction="ifRoom"
        android:icon="@mipmap/icon_menu_create_group_ok"
        android:title="" />
</menu>


text:
package com.suchorski.sicpag.filters;

import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(dispatcherTypes = { DispatcherType.REQUEST }, urlPatterns = { "/*" })
public class ContentTypeFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);
	}

	public void destroy() {
		return;
	}

	public void init(FilterConfig fConfig) throws ServletException {
		return;
	}

}


text:
export * from "./handle-response";
export * from "./query-param";
export * from "./appinsights";


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.red5.server.service.mp4 (Red5 :: Server 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style">

org.red5.server.service.mp4

Interfaces

IMP4Service


text:
from django.db import models

class CommentForListDestroyModelMixin(models.Model):
    email = models.EmailField()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleEngine;

namespace Stars
{
    class Program
    {
        static void Main(string[] args)
        {
            new Stars().Start();
        }
    }
}


text:
// Package webhook implements the authorizer.Authorizer interface using HTTP webhooks.
package webhook

import (
	"encoding/json"
	"time"

	"github.com/golang/glog"

	"k8s.io/apiserver/pkg/authorization/authorizer"
	"k8s.io/apiserver/pkg/util/cache"
	authorizationclient "k8s.io/client-go/kubernetes/typed/authorization/v1beta1"
	authorization "k8s.io/client-go/pkg/apis/authorization/v1beta1"
	"k8s.io/client-go/pkg/runtime/schema"

	"k8s.io/kubernetes/plugin/pkg/webhook"

	_ "k8s.io/kubernetes/pkg/apis/authorization/install"
)

var (
	groupVersions = []schema.GroupVersion{authorization.SchemeGroupVersion}
)

const retryBackoff = 500 * time.Millisecond

// Ensure Webhook implements the authorizer.Authorizer interface.
var _ authorizer.Authorizer = (*WebhookAuthorizer)(nil)

type WebhookAuthorizer struct {
	subjectAccessReview authorizationclient.SubjectAccessReviewInterface
	responseCache       *cache.LRUExpireCache
	authorizedTTL       time.Duration
	unauthorizedTTL     time.Duration
	initialBackoff      time.Duration
}

// NewFromInterface creates a WebhookAuthorizer using the given subjectAccessReview client
func NewFromInterface(subjectAccessReview authorizationclient.SubjectAccessReviewInterface, authorizedTTL, unauthorizedTTL time.Duration) (*WebhookAuthorizer, error) {
	return newWithBackoff(subjectAccessReview, authorizedTTL, unauthorizedTTL, retryBackoff)
}

// New creates a new WebhookAuthorizer from the provided kubeconfig file.
//
// The config's cluster field is used to refer to the remote service, user refers to the returned authorizer.
//
//     # clusters refers to the remote service.
//     clusters:
//     - name: name-of-remote-authz-service
//       cluster:
//         certificate-authority: /path/to/ca.pem      # CA for verifying the remote service.
//         server: https://authz.example.com/authorize # URL of remote service to query. Must use 'https'.
//
//     # users refers to the API server's webhook configuration.
//     users:
//     - name: name-of-api-server
//       user:
//         client-certificate: /path/to/cert.pem # cert for the webhook plugin to use
//         client-key: /path/to/key.pem          # key matching the cert
//
// For additional HTTP configuration, refer to the kubeconfig documentation
// http://kubernetes.io/v1.1/docs/user-guide/kubeconfig-file.html.
func New(kubeConfigFile string, authorizedTTL, unauthorizedTTL time.Duration) (*WebhookAuthorizer, error) {
	subjectAccessReview, err := subjectAccessReviewInterfaceFromKubeconfig(kubeConfigFile)
	if err != nil {
		return nil, err
	}
	return newWithBackoff(subjectAccessReview, authorizedTTL, unauthorizedTTL, retryBackoff)
}

// newWithBackoff allows tests to skip the sleep.
func newWithBackoff(subjectAccessReview authorizationclient.SubjectAccessReviewInterface, authorizedTTL, unauthorizedTTL, initialBackoff time.Duration) (*WebhookAuthorizer, error) {
	return &WebhookAuthorizer{
		subjectAccessReview: subjectAccessReview,
		responseCache:       cache.NewLRUExpireCache(1024),
		authorizedTTL:       authorizedTTL,
		unauthorizedTTL:     unauthorizedTTL,
		initialBackoff:      initialBackoff,
	}, nil
}

// Authorize makes a REST request to the remote service describing the attempted action as a JSON
// serialized api.authorization.v1beta1.SubjectAccessReview object. An example request body is
// provided bellow.
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "spec": {
//         "resourceAttributes": {
//           "namespace": "kittensandponies",
//           "verb": "GET",
//           "group": "group3",
//           "resource": "pods"
//         },
//         "user": "jane",
//         "group": [
//           "group1",
//           "group2"
//         ]
//       }
//     }
//
// The remote service is expected to fill the SubjectAccessReviewStatus field to either allow or
// disallow access. A permissive response would return:
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "status": {
//         "allowed": true
//       }
//     }
//
// To disallow access, the remote service would return:
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "status": {
//         "allowed": false,
//         "reason": "user does not have read access to the namespace"
//       }
//     }
//
func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (authorized bool, reason string, err error) {
	r := &authorization.SubjectAccessReview{}
	if user := attr.GetUser(); user != nil {
		r.Spec = authorization.SubjectAccessReviewSpec{
			User:   user.GetName(),
			Groups: user.GetGroups(),
			Extra:  convertToSARExtra(user.GetExtra()),
		}
	}

	if attr.IsResourceRequest() {
		r.Spec.ResourceAttributes = &authorization.ResourceAttributes{
			Namespace:   attr.GetNamespace(),
			Verb:        attr.GetVerb(),
			Group:       attr.GetAPIGroup(),
			Version:     attr.GetAPIVersion(),
			Resource:    attr.GetResource(),
			Subresource: attr.GetSubresource(),
			Name:        attr.GetName(),
		}
	} else {
		r.Spec.NonResourceAttributes = &authorization.NonResourceAttributes{
			Path: attr.GetPath(),
			Verb: attr.GetVerb(),
		}
	}
	key, err := json.Marshal(r.Spec)
	if err != nil {
		return false, "", err
	}
	if entry, ok := w.responseCache.Get(string(key)); ok {
		r.Status = entry.(authorization.SubjectAccessReviewStatus)
	} else {
		var (
			result *authorization.SubjectAccessReview
			err    error
		)
		webhook.WithExponentialBackoff(w.initialBackoff, func() error {
			result, err = w.subjectAccessReview.Create(r)
			return err
		})
		if err != nil {
			// An error here indicates bad configuration or an outage. Log for debugging.
			glog.Errorf("Failed to make webhook authorizer request: %v", err)
			return false, "", err
		}
		r.Status = result.Status
		if r.Status.Allowed {
			w.responseCache.Add(string(key), r.Status, w.authorizedTTL)
		} else {
			w.responseCache.Add(string(key), r.Status, w.unauthorizedTTL)
		}
	}
	return r.Status.Allowed, r.Status.Reason, nil
}

func convertToSARExtra(extra map[string][]string) map[string]authorization.ExtraValue {
	if extra == nil {
		return nil
	}
	ret := map[string]authorization.ExtraValue{}
	for k, v := range extra {
		ret[k] = authorization.ExtraValue(v)
	}

	return ret
}

// subjectAccessReviewInterfaceFromKubeconfig builds a client from the specified kubeconfig file,
// and returns a SubjectAccessReviewInterface that uses that client. Note that the client submits SubjectAccessReview
// requests to the exact path specified in the kubeconfig file, so arbitrary non-API servers can be targeted.
func subjectAccessReviewInterfaceFromKubeconfig(kubeConfigFile string) (authorizationclient.SubjectAccessReviewInterface, error) {
	gw, err := webhook.NewGenericWebhook(kubeConfigFile, groupVersions, 0)
	if err != nil {
		return nil, err
	}
	return &subjectAccessReviewClient{gw}, nil
}

type subjectAccessReviewClient struct {
	w *webhook.GenericWebhook
}

func (t *subjectAccessReviewClient) Create(subjectAccessReview *authorization.SubjectAccessReview) (*authorization.SubjectAccessReview, error) {
	result := &authorization.SubjectAccessReview{}
	err := t.w.RestClient.Post().Body(subjectAccessReview).Do().Into(result)
	return result, err
}


text:
using System;

namespace Exer_19_TheaThePhotographer
{
    class Program
    {
        static void Main(string[] args)
        {
            long picsTaken = long.Parse(Console.ReadLine());
            long filterTime = long.Parse(Console.ReadLine());
            long percentage = long.Parse(Console.ReadLine());
            long uploadTime = long.Parse(Console.ReadLine());

            long amountFiltered = (long)Math.Ceiling(picsTaken * percentage / 100d);
            long filterAllPics = picsTaken * filterTime;
            long uploadAllPics = amountFiltered * uploadTime;
            long totalTime = filterAllPics + uploadAllPics;

            TimeSpan projectTime = TimeSpan.FromSeconds(totalTime);
            Console.WriteLine("{0:D1}:{1:D2}:{2:D2}:{3:D2}",
                projectTime.Days,
                projectTime.Hours,
                projectTime.Minutes,
                projectTime.Seconds);
        }
    }
}


text:
import * as React from 'react';

import { Tooltip, classnames } from '@proton/components';

interface Props {
    icon: React.ReactNode;
    text: string;
    extraText?: string;
    title: string;
    initials: string;
    tooltip: string;
    className?: string;
}

const Participant = ({ icon, text, title, tooltip, initials, extraText, className }: Props) => {
    return (

            <Tooltip title={tooltip}>

{initials}

                    {icon}

            </Tooltip>
            <Tooltip title={title}>

{text}

                    {!!extraText && (

                            {extraText}

                    )}

            </Tooltip>

    );
};

export default Participant;


text:
function pressFunction(choice) {
    if (choice == "Return")
        window.location = "game.html";
    if(!city.isInRange(city.player.coordinates, menu.building.coordinates, range))
        return;
    if (choice == "Upgrade") {
        menu.building.upgrade();
    }
    if (choice == "Put gold") {
        menu.building.putGold(rangeInput.value * 10);
    }
    if (choice == "Take product") {
        menu.building.takeProduct();
    }
    reload();
}

var rangeInput = document.getElementById("rangeinput");
if (rangeInput != null) {
    rangeInput.addEventListener('mousemove', function() {
        $("#goldp").val(rangeInput.value * 10);
    });
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Media.Models
{
    internal partial class FirstQuality : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("bitrate");
            writer.WriteNumberValue(Bitrate);
            writer.WriteEndObject();
        }

        internal static FirstQuality DeserializeFirstQuality(JsonElement element)
        {
            int bitrate = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("bitrate"))
                {
                    bitrate = property.Value.GetInt32();
                    continue;
                }
            }
            return new FirstQuality(bitrate);
        }
    }
}