text:
// -----------------------------------------------------------------------------------------
// <copyright file="BlobClientTest.cs" company="Microsoft">
//    Copyright 2012 Microsoft Corporation
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;

namespace Microsoft.WindowsAzure.Storage.Blob.Protocol
{
    internal class BlobClientTests
    {
        public BlobContext BlobContext { get; private set; }

        public BlobProperties Properties { get; private set; }
        public string LeaseId { get; private set; }
        public string BlobName { get; private set; }
        public string ContainerName { get; private set; }
        public string PublicBlobName { get; private set; }
        public string PublicContainerName { get; private set; }
        public byte[] Content { get; private set; }

        private Random random = new Random();

        public BlobClientTests(bool owner, bool async, int timeout)
        {
            BlobContext = new BlobContext(owner, async, timeout);
        }

        public void Initialize()
        {
            ContainerName = "defaultcontainer";
            PublicContainerName = "publiccontainer";
            BlobName = "defaultblob";
            PublicBlobName = "public";

            Content = new byte[7000];
            random.NextBytes(Content);

            CreateContainer(ContainerName, false);
            CreateBlob(ContainerName, BlobName, false);
            CreateContainer(PublicContainerName, true);
            CreateBlob(PublicContainerName, PublicBlobName, true);
        }

        public void Cleanup()
        {
            DeleteContainer(ContainerName);
            DeleteContainer(PublicContainerName);
        }

        public void CreateContainer(string containerName, bool isPublic)
        {
            CreateContainer(containerName, isPublic, 3);
        }

        public void CreateContainer(string containerName, bool isPublic, int retries)
        {
            // by default, sleep 35 seconds between retries
            CreateContainer(containerName, isPublic, retries, 35000);
        }

        public void CreateContainer(string containerName, bool isPublic, int retries, int millisecondsBetweenRetries)
        {
            while (true)
            {
                HttpWebRequest request = BlobTests.CreateContainerRequest(BlobContext, containerName);
                Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
                if (isPublic)
                {
                    request.Headers["x-ms-blob-public-access"] = "container";
                }
                if (BlobContext.Credentials != null)
                {
                    BlobTests.SignRequest(request, BlobContext);
                }
                HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
                HttpStatusCode statusCode = response.StatusCode;
                string statusDescription = response.StatusDescription;
                StorageExtendedErrorInformation error = StorageExtendedErrorInformation.ReadFromStream(response.GetResponseStream());
                response.Close();

                // if the container is being deleted, retry up to the specified times.
                if (statusCode == HttpStatusCode.Conflict && error != null && error.ErrorCode == BlobErrorCodeStrings.ContainerBeingDeleted && retries > 0)
                {
                    Thread.Sleep(millisecondsBetweenRetries);
                    retries--;
                    continue;
                }

                break;
            }
        }

        public void DeleteContainer(string containerName)
        {
            HttpWebRequest request = BlobTests.DeleteContainerRequest(BlobContext, containerName, null);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            HttpStatusCode statusCode = response.StatusCode;
            string statusDescription = response.StatusDescription;
            response.Close();
        }

        public void CreateBlob(string containerName, string blobName, bool isPublic)
        {
            Properties = new BlobProperties() { BlobType = BlobType.BlockBlob };
            HttpWebRequest request = BlobTests.PutBlobRequest(BlobContext, containerName, blobName, Properties, BlobType.BlockBlob, Content, 0, null);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");

            request.ContentLength = Content.Length;
            request.Timeout = 30000;
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            Stream stream = request.GetRequestStream();
            stream.Write(Content, 0, Content.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            HttpStatusCode statusCode = response.StatusCode;
            string statusDescription = response.StatusDescription;
            response.Close();
            if (statusCode != HttpStatusCode.Created)
            {
                Assert.Fail(string.Format("Failed to create blob: {0}, Status: {1}, Status Description: {2}", containerName, statusCode, statusDescription));
            }
        }

        public void DeleteBlob(string containerName, string blobName)
        {
            HttpWebRequest request = BlobTests.DeleteBlobRequest(BlobContext, containerName, blobName, null);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            response.Close();
        }

        /// <summary>
        /// Scenario test for acquiring a lease.
        /// </summary>
        /// <param name="containerName">The name of the container.</param>
        /// <param name="blobName">The name of the blob, if any.</param>
        /// <param name="leaseDuration">The lease duration.</param>
        /// <param name="proposedLeaseId">The proposed lease ID.</param>
        /// <param name="expectedError">The error status code to expect.</param>
        /// <returns>The lease ID.</returns>
        public string AcquireLeaseScenarioTest(string containerName, string blobName, int leaseDuration, string proposedLeaseId, HttpStatusCode? expectedError)
        {
            // Create and validate the web request
            HttpWebRequest request = BlobTests.AcquireLeaseRequest(BlobContext, containerName, blobName, leaseDuration, proposedLeaseId, null);

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            using (HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.AcquireLeaseResponse(response, proposedLeaseId, expectedError);

                return BlobHttpResponseParsers.GetLeaseId(response);
            }
        }

        /// <summary>
        /// Scenario test for renewing a lease.
        /// </summary>
        /// <param name="containerName">The name of the container.</param>
        /// <param name="blobName">The name of the blob, if any.</param>
        /// <param name="leaseId">The lease ID.</param>
        /// <param name="expectedError">The error status code to expect.</param>
        public void RenewLeaseScenarioTest(string containerName, string blobName, string leaseId, HttpStatusCode? expectedError)
        {
            // Create and validate the web request
            HttpWebRequest request = BlobTests.RenewLeaseRequest(BlobContext, containerName, blobName, AccessCondition.GenerateLeaseCondition(leaseId));

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            using (HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.RenewLeaseResponse(response, leaseId, expectedError);
            }
        }

        /// <summary>
        /// Scenario test for changing a lease.
        /// </summary>
        /// <param name="containerName">The name of the container.</param>
        /// <param name="blobName">The name of the blob, if any.</param>
        /// <param name="leaseId">The lease ID.</param>
        /// <param name="proposedLeaseId">The proposed lease ID.</param>
        /// <param name="expectedError">The error status code to expect.</param>
        /// <returns>The lease ID.</returns>
        public string ChangeLeaseScenarioTest(string containerName, string blobName, string leaseId, string proposedLeaseId, HttpStatusCode? expectedError)
        {
            // Create and validate the web request
            HttpWebRequest request = BlobTests.ChangeLeaseRequest(BlobContext, containerName, blobName, proposedLeaseId, AccessCondition.GenerateLeaseCondition(leaseId));

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            using (HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.ChangeLeaseResponse(response, proposedLeaseId, expectedError);

                return BlobHttpResponseParsers.GetLeaseId(response);
            }
        }

        /// <summary>
        /// Scenario test for releasing a lease.
        /// </summary>
        /// <param name="containerName">The name of the container.</param>
        /// <param name="blobName">The name of the blob, if any.</param>
        /// <param name="leaseId">The lease ID.</param>
        /// <param name="expectedError">The error status code to expect.</param>
        public void ReleaseLeaseScenarioTest(string containerName, string blobName, string leaseId, HttpStatusCode? expectedError)
        {
            // Create and validate the web request
            HttpWebRequest request = BlobTests.ReleaseLeaseRequest(BlobContext, containerName, blobName, AccessCondition.GenerateLeaseCondition(leaseId));

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            using (HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.ReleaseLeaseResponse(response, expectedError);
            }
        }

        /// <summary>
        /// Scenario test for breaking a lease.
        /// </summary>
        /// <param name="containerName">The name of the container.</param>
        /// <param name="blobName">The name of the blob, if any.</param>
        /// <param name="breakPeriod">The break period.</param>
        /// <param name="expectedRemainingTime">The expected remaining time.</param>
        /// <param name="expectedError">The error status code to expect.</param>
        /// <returns>The remaining lease time.</returns>
        public int BreakLeaseScenarioTest(string containerName, string blobName, int? breakPeriod, int? expectedRemainingTime, HttpStatusCode? expectedError)
        {
            // Create and validate the web request
            HttpWebRequest request = BlobTests.BreakLeaseRequest(BlobContext, containerName, blobName, breakPeriod, null);

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            using (HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext))
            {
                int expectedTime = expectedRemainingTime ?? breakPeriod.Value;
                int errorMargin = 10;
                BlobTests.BreakLeaseResponse(response, expectedTime, errorMargin, expectedError);

                return expectedError.HasValue ? 0 : BlobHttpResponseParsers.GetRemainingLeaseTime(response).Value;
            }
        }

        /// <summary>
        /// Test acquire lease semantics.
        /// </summary>
        /// <param name="containerName">The container.</param>
        /// <param name="blobName">The blob, if any.</param>
        public void AcquireLeaseTests(string containerName, string blobName)
        {
            string proposedLeaseId = Guid.NewGuid().ToString();
            string proposedLeaseId2 = Guid.NewGuid().ToString();
            string leaseId;
            string leaseId2;

            // Acquire the lease while in available state
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Acquire the lease while in leased state (idempotent)
            leaseId2 = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Acquire the lease while in leased state (conflict)
            AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId2, HttpStatusCode.Conflict);

            // Break lease for 60 seconds
            BreakLeaseScenarioTest(containerName, blobName, 60, 60, null);

            // Acquire the lease while in breaking state (conflict)
            AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, HttpStatusCode.Conflict);
            AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId2, HttpStatusCode.Conflict);

            // Break lease instantly
            BreakLeaseScenarioTest(containerName, blobName, 0, 0, null);

            // Acquire the lease while in broken state (same ID)
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease instantly
            BreakLeaseScenarioTest(containerName, blobName, 0, 0, null);

            // Acquire the lease while in broken state (new ID)
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId2, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire the lease while in released state (same ID)
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId2, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire the lease while in released state (new ID)
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire a lease that is too short
            AcquireLeaseScenarioTest(containerName, blobName, 14, proposedLeaseId, HttpStatusCode.BadRequest);

            // Acquire a lease that is too long
            AcquireLeaseScenarioTest(containerName, blobName, 61, proposedLeaseId, HttpStatusCode.BadRequest);

            // Acquire minimum finite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, 15, proposedLeaseId, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire maximum finite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, 60, proposedLeaseId, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire with no proposed ID (non-idempotent)
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, null, null);

            // Acquire with no proposed ID (attempt to use as though idempotent)
            AcquireLeaseScenarioTest(containerName, blobName, -1, null, HttpStatusCode.Conflict);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);
        }

        /// <summary>
        /// Test renew lease semantics.
        /// </summary>
        /// <param name="containerName">The container.</param>
        /// <param name="blobName">The blob, if any.</param>
        public void RenewLeaseTests(string containerName, string blobName)
        {
            string proposedLeaseId = Guid.NewGuid().ToString();
            string unknownLeaseId = Guid.NewGuid().ToString();
            string leaseId;

            // Renew lease (no lease)
            RenewLeaseScenarioTest(containerName, blobName, null, HttpStatusCode.BadRequest);

            // Renew lease in available state
            RenewLeaseScenarioTest(containerName, blobName, proposedLeaseId, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Renew infinite lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Renew released lease (wrong lease)
            RenewLeaseScenarioTest(containerName, blobName, unknownLeaseId, HttpStatusCode.Conflict);

            // Renew released infinite lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, HttpStatusCode.Conflict);

            // Acquire finite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, 60, proposedLeaseId, null);

            // Renew finite lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Renew lease (wrong lease)
            RenewLeaseScenarioTest(containerName, blobName, unknownLeaseId, HttpStatusCode.Conflict);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Renew released finite lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease for 60 seconds
            BreakLeaseScenarioTest(containerName, blobName, 60, 60, null);

            // Renew breaking lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, HttpStatusCode.Conflict);

            // Break lease instantly
            BreakLeaseScenarioTest(containerName, blobName, 0, 0, null);

            // Renew broken lease
            RenewLeaseScenarioTest(containerName, blobName, leaseId, HttpStatusCode.Conflict);
        }

        /// <summary>
        /// Test change lease semantics.
        /// </summary>
        /// <param name="containerName">The container.</param>
        /// <param name="blobName">The blob, if any.</param>
        public void ChangeLeaseTests(string containerName, string blobName)
        {
            string proposedLeaseId = Guid.NewGuid().ToString();
            string proposedLeaseId2 = Guid.NewGuid().ToString();
            string unknownLeaseId = Guid.NewGuid().ToString();
            string leaseId;
            string leaseId2;

            // Change lease (no lease)
            ChangeLeaseScenarioTest(containerName, blobName, null, proposedLeaseId2, HttpStatusCode.BadRequest);

            // Change lease (no proposed lease)
            ChangeLeaseScenarioTest(containerName, blobName, proposedLeaseId, null, HttpStatusCode.BadRequest);

            // Change lease in available state
            ChangeLeaseScenarioTest(containerName, blobName, proposedLeaseId, proposedLeaseId2, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Change lease
            leaseId2 = ChangeLeaseScenarioTest(containerName, blobName, leaseId, proposedLeaseId2, null);

            // Change lease (idempotent)
            leaseId2 = ChangeLeaseScenarioTest(containerName, blobName, leaseId, proposedLeaseId2, null);

            // Change lease (idempotent, other source)
            leaseId2 = ChangeLeaseScenarioTest(containerName, blobName, unknownLeaseId, proposedLeaseId2, null);

            // Change lease (wrong lease)
            ChangeLeaseScenarioTest(containerName, blobName, unknownLeaseId, proposedLeaseId, HttpStatusCode.Conflict);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId2, null);

            // Change released lease
            ChangeLeaseScenarioTest(containerName, blobName, leaseId2, proposedLeaseId, HttpStatusCode.Conflict);

            // Change released lease (idempotent attempt)
            ChangeLeaseScenarioTest(containerName, blobName, leaseId, proposedLeaseId2, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease for 60 seconds
            BreakLeaseScenarioTest(containerName, blobName, 60, 60, null);

            // Change breaking lease
            ChangeLeaseScenarioTest(containerName, blobName, leaseId, proposedLeaseId2, HttpStatusCode.Conflict);

            // Change breaking lease (idempotent attempt)
            ChangeLeaseScenarioTest(containerName, blobName, leaseId2, proposedLeaseId, HttpStatusCode.Conflict);

            // Break lease instantly
            BreakLeaseScenarioTest(containerName, blobName, 0, 0, null);

            // Change broken lease
            ChangeLeaseScenarioTest(containerName, blobName, leaseId, proposedLeaseId2, HttpStatusCode.Conflict);

            // Change broken lease (idempotent attempt)
            ChangeLeaseScenarioTest(containerName, blobName, leaseId2, proposedLeaseId, HttpStatusCode.Conflict);
        }

        /// <summary>
        /// Test release lease semantics.
        /// </summary>
        /// <param name="containerName">The container.</param>
        /// <param name="blobName">The blob, if any.</param>
        public void ReleaseLeaseTests(string containerName, string blobName)
        {
            string proposedLeaseId = Guid.NewGuid().ToString();
            string unknownLeaseId = Guid.NewGuid().ToString();
            string leaseId;

            // Release lease (no lease)
            ReleaseLeaseScenarioTest(containerName, blobName, null, HttpStatusCode.BadRequest);

            // Release lease in available state (unknown lease)
            ReleaseLeaseScenarioTest(containerName, blobName, proposedLeaseId, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Release lease (wrong lease)
            ReleaseLeaseScenarioTest(containerName, blobName, unknownLeaseId, HttpStatusCode.Conflict);

            // Release lease (right lease)
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Release lease (old lease)
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, HttpStatusCode.Conflict);

            // Release lease in released state (unknown lease)
            ReleaseLeaseScenarioTest(containerName, blobName, unknownLeaseId, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease for 60 seconds
            BreakLeaseScenarioTest(containerName, blobName, 60, 60, null);

            // Release breaking lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease instantly
            BreakLeaseScenarioTest(containerName, blobName, 0, 0, null);

            // Release broken lease (right lease)
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Release broken lease (wrong lease)
            ReleaseLeaseScenarioTest(containerName, blobName, unknownLeaseId, HttpStatusCode.Conflict);
        }

        /// <summary>
        /// Test break lease semantics.
        /// </summary>
        /// <param name="containerName">The container.</param>
        /// <param name="blobName">The blob, if any.</param>
        public void BreakLeaseTests(string containerName, string blobName)
        {
            string proposedLeaseId = Guid.NewGuid().ToString();
            string unknownLeaseId = Guid.NewGuid().ToString();
            string leaseId;
            int leaseTime;

            // Break lease in available state
            BreakLeaseScenarioTest(containerName, blobName, null, 0, HttpStatusCode.Conflict);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease (negative break time)
            BreakLeaseScenarioTest(containerName, blobName, -1, null, HttpStatusCode.BadRequest);

            // Break lease (too large break time)
            BreakLeaseScenarioTest(containerName, blobName, 61, null, HttpStatusCode.BadRequest);

            // Break lease (default break time)
            BreakLeaseScenarioTest(containerName, blobName, null, 0, null);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease (zero break time)
            BreakLeaseScenarioTest(containerName, blobName, 0, null, null);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease (1 second break time)
            BreakLeaseScenarioTest(containerName, blobName, 1, null, null);

            // Wait for lease to break
            Thread.Sleep(TimeSpan.FromSeconds(2));

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Break lease (60 seconds break time)
            BreakLeaseScenarioTest(containerName, blobName, 60, null, null);

            // Break breaking lease (zero break time)
            BreakLeaseScenarioTest(containerName, blobName, 0, null, null);

            // Acquire finite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, 59, proposedLeaseId, null);

            // Break lease (longer than lease time)
            BreakLeaseScenarioTest(containerName, blobName, 60, 59, null);

            // Break lease (zero break time)
            BreakLeaseScenarioTest(containerName, blobName, 0, null, null);

            // Acquire finite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, 60, proposedLeaseId, null);

            // Break lease (default break time)
            leaseTime = BreakLeaseScenarioTest(containerName, blobName, null, 60, null);

            // Break breaking lease (default break time)
            BreakLeaseScenarioTest(containerName, blobName, null, leaseTime, null);

            // Break breaking lease (zero break time)
            BreakLeaseScenarioTest(containerName, blobName, 0, null, null);

            // Acquire infinite lease
            leaseId = AcquireLeaseScenarioTest(containerName, blobName, -1, proposedLeaseId, null);

            // Release lease
            ReleaseLeaseScenarioTest(containerName, blobName, leaseId, null);

            // Break released lease
            BreakLeaseScenarioTest(containerName, blobName, null, 0, HttpStatusCode.Conflict);
        }

        public void PutBlobScenarioTest(string containerName, string blobName, BlobProperties properties, BlobType blobType, byte[] content, HttpStatusCode? expectedError)
        {
            HttpWebRequest request = BlobTests.PutBlobRequest(BlobContext, containerName, blobName, properties, blobType, content, content.Length, null);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            request.ContentLength = content.Length;
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            BlobTestUtils.SetRequest(request, BlobContext, content);
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.PutBlobResponse(response, BlobContext, expectedError);
            }
            finally
            {
                response.Close();
            }
        }

        public void ClearPageRangeScenarioTest(string containerName, string blobName, HttpStatusCode? expectedError)
        {
            // 1. Create Sparse Page Blob
            int blobSize = 128 * 1024;

            BlobProperties properties = new BlobProperties() { BlobType = BlobType.PageBlob };
            Uri uri = BlobTests.ConstructPutUri(BlobContext.Address, containerName, blobName);
            OperationContext opContext = new OperationContext();
            HttpWebRequest webRequest = BlobHttpWebRequestFactory.Put(uri, BlobContext.Timeout, properties, BlobType.PageBlob, blobSize, null, opContext);

            BlobTests.SignRequest(webRequest, BlobContext);

            using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
            {
                BlobTests.PutBlobResponse(response, BlobContext, expectedError);
            }

            // 2. Now upload some page ranges
            for (int m = 0; m * 512 * 4 < blobSize; m++)
            {
                int startOffset = 512 * 4 * m;
                int length = 512;

                PageRange range = new PageRange(startOffset, startOffset + length - 1);
                opContext = new OperationContext();
                HttpWebRequest pageRequest = BlobHttpWebRequestFactory.PutPage(uri, BlobContext.Timeout, range, PageWrite.Update, null, opContext);
                pageRequest.ContentLength = 512;
                BlobTests.SignRequest(pageRequest, BlobContext);

                Stream outStream = pageRequest.GetRequestStream();

                for (int n = 0; n < 512; n++)
                {
                    outStream.WriteByte((byte)m);
                }

                outStream.Close();
                using (HttpWebResponse pageResponse = pageRequest.GetResponse() as HttpWebResponse)
                {
                }
            }

            // 3. Now do a Get Page Ranges
            List<PageRange> pageRanges = new List<PageRange>();
            opContext = new OperationContext();
            HttpWebRequest pageRangeRequest = BlobHttpWebRequestFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, opContext);
            BlobTests.SignRequest(pageRangeRequest, BlobContext);
            using (HttpWebResponse pageRangeResponse = pageRangeRequest.GetResponse() as HttpWebResponse)
            {
                GetPageRangesResponse getPageRangesResponse = new GetPageRangesResponse(pageRangeResponse.GetResponseStream());
                pageRanges.AddRange(getPageRangesResponse.PageRanges.ToList());
            }

            // 4. Now Clear some pages
            bool skipFlag = false;
            foreach (PageRange pRange in pageRanges)
            {
                skipFlag = !skipFlag;
                if (skipFlag)
                {
                    continue;
                }

                opContext = new OperationContext();
                HttpWebRequest clearPageRequest = BlobHttpWebRequestFactory.PutPage(uri, BlobContext.Timeout, pRange, PageWrite.Clear, null, opContext);
                clearPageRequest.ContentLength = 0;
                BlobTests.SignRequest(clearPageRequest, BlobContext);
                using (HttpWebResponse clearResponse = clearPageRequest.GetResponse() as HttpWebResponse)
                {
                }
            }

            // 5. Get New Page ranges and verify
            List<PageRange> newPageRanges = new List<PageRange>();

            opContext = new OperationContext();
            HttpWebRequest newPageRangeRequest = BlobHttpWebRequestFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, opContext);
            BlobTests.SignRequest(newPageRangeRequest, BlobContext);
            using (HttpWebResponse newPageRangeResponse = newPageRangeRequest.GetResponse() as HttpWebResponse)
            {
                GetPageRangesResponse getNewPageRangesResponse = new GetPageRangesResponse(newPageRangeResponse.GetResponseStream());
                newPageRanges.AddRange(getNewPageRangesResponse.PageRanges.ToList());
            }

            Assert.AreEqual(pageRanges.Count(), newPageRanges.Count() * 2);
            for (int l = 0; l < newPageRanges.Count(); l++)
            {
                Assert.AreEqual(pageRanges[2 * l].StartOffset, newPageRanges[l].StartOffset);
                Assert.AreEqual(pageRanges[2 * l].EndOffset, newPageRanges[l].EndOffset);
            }
        }

        public void GetBlobScenarioTest(string containerName, string blobName, BlobProperties properties, string leaseId,
            byte[] content, HttpStatusCode? expectedError)
        {
            HttpWebRequest request = BlobTests.GetBlobRequest(BlobContext, containerName, blobName, AccessCondition.GenerateLeaseCondition(leaseId));
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.GetBlobResponse(response, BlobContext, properties, content, expectedError);
            }
            finally
            {
                response.Close();
            }
        }

        /// <summary>
        /// Sends a get blob range request with the given parameters and validates both request and response.
        /// </summary>
        /// <param name="containerName">The blob's container's name.</param>
        /// <param name="blobName">The blob's name.</param>
        /// <param name="leaseId">The lease ID, or null if there is no lease.</param>
        /// <param name="content">The total contents of the blob.</param>
        /// <param name="offset">The offset of the contents we will get.</param>
        /// <param name="count">The number of bytes we will get, or null to get the rest of the blob.</param>
        /// <param name="expectedError">The error code we expect from this operation, or null if we expect it to succeed.</param>
        public void GetBlobRangeScenarioTest(string containerName, string blobName, string leaseId, byte[] content, long offset, long? count, HttpStatusCode? expectedError)
        {
            HttpWebRequest request = BlobTests.GetBlobRangeRequest(BlobContext, containerName, blobName, offset, count, AccessCondition.GenerateLeaseCondition(leaseId));
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");

            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }

            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);

            try
            {
                long endRange = count.HasValue ? count.Value + offset - 1 : content.Length - 1;
                byte[] selectedContent = null;

                // Compute expected content only if call is expected to succeed.
                if (expectedError == null)
                {
                    selectedContent = new byte[endRange - offset + 1];
                    Array.Copy(content, offset, selectedContent, 0, selectedContent.Length);
                }

                BlobTests.CheckBlobRangeResponse(response, BlobContext, selectedContent, offset, endRange, content.Length, expectedError);
            }
            finally
            {
                response.Close();
            }
        }

        public void ListBlobsScenarioTest(string containerName, BlobListingContext listingContext, HttpStatusCode? expectedError, params string[] expectedBlobs)
        {
            HttpWebRequest request = BlobTests.ListBlobsRequest(BlobContext, containerName, listingContext);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.ListBlobsResponse(response, BlobContext, expectedError);
                ListBlobsResponse listBlobsResponse = new ListBlobsResponse(response.GetResponseStream());
                int i = 0;
                foreach (IListBlobEntry item in listBlobsResponse.Blobs)
                {
                    var blob = item as ListBlobEntry;
                    if (expectedBlobs == null)
                    {
                        Assert.Fail("Should not have blobs.");
                    }
                    Assert.IsTrue(i < expectedBlobs.Length, "Unexpected blob: " + blob.Name);
                    Assert.AreEqual<string>(expectedBlobs[i++], blob.Name, "Incorrect blob.");
                }
                if (expectedBlobs != null && i < expectedBlobs.Length)
                {
                    Assert.Fail("Missing blob: " + expectedBlobs[i] + "(and " + (expectedBlobs.Length - i - 1) + " more).");
                }
            }
            finally
            {
                response.Close();
            }
        }

        public void ListContainersScenarioTest(ListingContext listingContext, HttpStatusCode? expectedError, params string[] expectedContainers)
        {
            HttpWebRequest request = BlobTests.ListContainersRequest(BlobContext, listingContext);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.ListContainersResponse(response, BlobContext, expectedError);
                ListContainersResponse listContainersResponse = new ListContainersResponse(response.GetResponseStream());
                int i = 0;
                foreach (BlobContainerEntry item in listContainersResponse.Containers)
                {
                    if (expectedContainers == null)
                    {
                        Assert.Fail("Should not have containers.");
                    }
                    Assert.IsTrue(i < expectedContainers.Length, "Unexpected container: " + item.Name);
                    Assert.AreEqual<string>(expectedContainers[i++], item.Name, "Incorrect container.");
                }
                if (expectedContainers != null && i < expectedContainers.Length)
                {
                    Assert.Fail("Missing container: " + expectedContainers[i] + "(and " + (expectedContainers.Length - i - 1) + " more).");
                }
            }
            finally
            {
                response.Close();
            }
        }

        public void PutBlockScenarioTest(string containerName, string blobName, string blockId, string leaseId, byte[] content, HttpStatusCode? expectedError)
        {
            HttpWebRequest request = BlobTests.PutBlockRequest(BlobContext, containerName, blobName, blockId, AccessCondition.GenerateLeaseCondition(leaseId));
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            request.ContentLength = content.Length;
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            BlobTestUtils.SetRequest(request, BlobContext, content);
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.PutBlockResponse(response, BlobContext, expectedError);
            }
            finally
            {
                response.Close();
            }
        }

        public void PutBlockListScenarioTest(string containerName, string blobName, List<PutBlockListItem> blocks, BlobProperties blobProperties, string leaseId, HttpStatusCode? expectedError)
        {
            HttpWebRequest request = BlobTests.PutBlockListRequest(BlobContext, containerName, blobName, blobProperties, AccessCondition.GenerateLeaseCondition(leaseId));
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            byte[] content;
            using (MemoryStream stream = new MemoryStream())
            {
                BlobRequest.WriteBlockListBody(blocks, stream);
                stream.Seek(0, SeekOrigin.Begin);
                content = new byte[stream.Length];
                stream.Read(content, 0, content.Length);
            }
            request.ContentLength = content.Length;
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            BlobTestUtils.SetRequest(request, BlobContext, content);
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.PutBlockListResponse(response, BlobContext, expectedError);
            }
            finally
            {
                response.Close();
            }
        }

        public void GetBlockListScenarioTest(string containerName, string blobName, BlockListingFilter typesOfBlocks, string leaseId, HttpStatusCode? expectedError, params string[] expectedBlocks)
        {
            HttpWebRequest request = BlobTests.GetBlockListRequest(BlobContext, containerName, blobName, typesOfBlocks, AccessCondition.GenerateLeaseCondition(leaseId));
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            if (BlobContext.Credentials != null)
            {
                BlobTests.SignRequest(request, BlobContext);
            }
            HttpWebResponse response = BlobTestUtils.GetResponse(request, BlobContext);
            try
            {
                BlobTests.GetBlockListResponse(response, BlobContext, expectedError);
                GetBlockListResponse getBlockListResponse = new GetBlockListResponse(response.GetResponseStream());
                int i = 0;
                foreach (ListBlockItem item in getBlockListResponse.Blocks)
                {
                    if (expectedBlocks == null)
                    {
                        Assert.Fail("Should not have blocks.");
                    }
                    Assert.IsTrue(i < expectedBlocks.Length, "Unexpected block: " + item.Name);
                    Assert.AreEqual<string>(expectedBlocks[i++], item.Name, "Incorrect block.");
                }
                if (expectedBlocks != null && i < expectedBlocks.Length)
                {
                    Assert.Fail("Missing block: " + expectedBlocks[i] + "(and " + (expectedBlocks.Length - i - 1) + " more).");
                }
            }
            finally
            {
                response.Close();
            }
        }

        public static Uri ConstructUri(string address, params string[] folders)
        {
            Assert.IsNotNull(address);

            string uriString = address;
            foreach (string folder in folders)
            {
                uriString = String.Format("{0}/{1}", uriString, folder);
            }
            Uri uri = null;
            uri = new Uri(uriString);
            return uri;
        }

        public void CopyFromToRestoreSnapshot(BlobContext context, string containerName, string blobName)
        {
            string oldText = "Old stuff";
            string newText = "New stuff";

            StorageCredentials accountAndKey = new StorageCredentials(context.Account, context.Key);
            CloudStorageAccount account = new CloudStorageAccount(accountAndKey, false);
            CloudBlobClient blobClient = new CloudBlobClient(new Uri(context.Address), account.Credentials);
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
            BlobTestBase.UploadText(blob, oldText, Encoding.UTF8);
            CloudBlockBlob snapshot = blob.CreateSnapshot();
            Assert.IsNotNull(snapshot.SnapshotTime);
            BlobTestBase.UploadText(blob, newText, Encoding.UTF8);

            Uri sourceUri = new Uri(snapshot.Uri.AbsoluteUri + "?snapshot=" + BlobRequest.ConvertDateTimeToSnapshotString(snapshot.SnapshotTime.Value));
            OperationContext opContext = new OperationContext();
            HttpWebRequest request = BlobHttpWebRequestFactory.CopyFrom(blob.Uri, 30, sourceUri, null, null, opContext);
            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            BlobTests.SignRequest(request, context);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Assert.AreEqual<HttpStatusCode>(response.StatusCode, HttpStatusCode.Accepted);

            string text = BlobTestBase.DownloadText(blob, Encoding.UTF8);
            Assert.AreEqual<string>(text, oldText);

            blob.Delete(DeleteSnapshotsOption.IncludeSnapshots, null, null);
        }
    }
}


text:
package org.mustbe.consulo.codeInsight.navigation.actions;

import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;

/**
 * @author VISTALL
 * @since 02.05.2015
 */
public interface GotoDeclarationHandlerEx extends GotoDeclarationHandler {
  @NotNull
  PsiElementListCellRenderer<PsiElement> createRender(@NotNull PsiElement[] elements);
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Other;
using Mono.Cecil;
using ILRuntime.Runtime.Intepreter;
namespace ILRuntime.CLR.Utils
{
    public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5);

    public static class Extensions
    {
        public static List<IType> EmptyParamList = new List<IType>();
        public static List<IType> GetParamList(this MethodReference def, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IType contextType, IMethod contextMethod, IType[] genericArguments)
        {
            if (def.HasParameters)
            {
                List<IType> param = new List<IType>();
                var dt = appdomain.GetType(def.DeclaringType, contextType, contextMethod);
                foreach (var i in def.Parameters)
                {
                    IType t = null;
                    t = appdomain.GetType(i.ParameterType, dt, null);
                    if (t == null && def.IsGenericInstance)
                    {
                        GenericInstanceMethod gim = (GenericInstanceMethod)def;
                        string name = i.ParameterType.IsByReference ? i.ParameterType.GetElementType().FullName : i.ParameterType.FullName;

                        for (int j = 0; j < gim.GenericArguments.Count; j++)
                        {
                            var gp = gim.ElementMethod.GenericParameters[j];
                            var ga = gim.GenericArguments[j];
                            if (name == gp.Name)
                            {
                                t = appdomain.GetType(ga, contextType, contextMethod);
                                if (t == null && genericArguments != null)
                                    t = genericArguments[j];
                                break;
                            }
                            else if (name.Contains(gp.Name))
                            {
                                if (name == gp.Name)
                                {
                                    name = ga.FullName;
                                }
                                else if (name == gp.Name + "[]")
                                {
                                    name = ga.FullName + "[]";
                                }
                                else
                                {
                                    /*name = name.Replace("<" + gp.Name + ">", "<" + ga.FullName + ">");
                                    name = name.Replace("<" + gp.Name + "[", "<" + ga.FullName + "[");
                                    name = name.Replace("<" + gp.Name + ",", "<" + ga.FullName + ",");
                                    name = name.Replace("," + gp.Name + ">", "," + ga.FullName + ">");
                                    name = name.Replace("," + gp.Name + "[", "," + ga.FullName + "[");
                                    name = name.Replace("," + gp.Name + ",", "," + ga.FullName + ",");
                                    name = name.Replace("," + gp.Name + "[", "," + ga.FullName + "[");*/
                                    name = ReplaceGenericArgument(name, gp.Name, ga.FullName);
                                }
                            }
                        }
                        if (t == null)
                            t = appdomain.GetType(name);
                    }

                    param.Add(t);
                }
                return param;
            }
            else
                return EmptyParamList;
        }

        static string ReplaceGenericArgument(string typename, string argumentName, string argumentType)
        {
            string baseType;
            StringBuilder sb = new StringBuilder();
            List<string> ga;
            bool isArray;
            Runtime.Enviorment.AppDomain.ParseGenericType(typename, out baseType, out ga, out isArray);
            if (baseType == argumentName)
                sb.Append(argumentType);
            else
                sb.Append(baseType);
            if (ga != null && ga.Count > 0)
            {
                sb.Append("<");
                bool isFirst = true;
                foreach(var i in ga)
                {
                    if (isFirst)
                        isFirst = false;
                    else
                        sb.Append(",");

                    sb.Append(ReplaceGenericArgument(i, argumentName, argumentType));
                }
                sb.Append(">");
            }
            if (isArray)
                sb.Append("[]");
            return sb.ToString();
        }

        [Flags]
        public enum TypeFlags
        {
            Default = 0,
            IsPrimitive = 0x1,
            IsByRef = 0x2,
            IsEnum = 0x4,
            IsDelegate = 0x8,
            IsValueType = 0x10,
        }

        private static readonly Dictionary<Type, TypeFlags> typeFlags = new Dictionary<Type, TypeFlags>(new ByReferenceKeyComparer<Type>());

        public static bool FastIsEnum(this Type pt)
        {
            return (pt.GetTypeFlags() & TypeFlags.IsEnum) != 0;
        }

        public static bool FastIsByRef(this Type pt)
        {
            return (pt.GetTypeFlags() & TypeFlags.IsByRef) != 0;
        }

        public static bool FastIsPrimitive(this Type pt)
        {
            return (pt.GetTypeFlags() & TypeFlags.IsPrimitive) != 0;
        }

        public static bool FastIsValueType(this Type pt)
        {
            return (pt.GetTypeFlags() & TypeFlags.IsValueType) != 0;
        }

        public static TypeFlags GetTypeFlags(this Type pt)
        {
            var result = TypeFlags.Default;

            if (!typeFlags.TryGetValue(pt, out result))
            {
                if (pt.IsPrimitive)
                {
                    result |= TypeFlags.IsPrimitive;
                }

                if (pt == typeof(Delegate) || pt.IsSubclassOf(typeof(Delegate)))
                {
                    result |= TypeFlags.IsDelegate;
                }

                if (pt.IsByRef)
                {
                    result |= TypeFlags.IsByRef;
                }

                if (pt.IsEnum)
                {
                    result |= TypeFlags.IsEnum;
                }

                if (pt.IsValueType)
                {
                    result |= TypeFlags.IsValueType;
                }

                typeFlags[pt] = result;
            }

            return result;
        }

        public static object CheckCLRTypes(this Type pt, object obj)
        {
            if (obj == null)
                return null;

            var typeFlags = GetTypeFlags(pt);

            if ((typeFlags & TypeFlags.IsPrimitive) != 0 && pt != typeof(int))
            {
                if (pt == typeof(bool) && !(obj is bool))
                {
                    obj = (int)obj == 1;
                }
                else if (pt == typeof(byte) && !(obj is byte))
                    obj = (byte)(int)obj;
                else if (pt == typeof(short) && !(obj is short))
                    obj = (short)(int)obj;
                else if (pt == typeof(char) && !(obj is char))
                    obj = (char)(int)obj;
                else if (pt == typeof(ushort) && !(obj is ushort))
                    obj = (ushort)(int)obj;
                else if (pt == typeof(uint) && !(obj is uint))
                    obj = (uint)(int)obj;
                else if (pt == typeof(sbyte) && !(obj is sbyte))
                    obj = (sbyte)(int)obj;
                else if (pt == typeof(ulong) && !(obj is ulong))
                {
                    obj = (ulong)(long)obj;
                }
            }
            else if (obj is ILRuntime.Reflection.ILRuntimeWrapperType)
            {
                obj = ((ILRuntime.Reflection.ILRuntimeWrapperType)obj).RealType;
            }
            else if ((typeFlags & TypeFlags.IsDelegate) != 0)
            {
                if (obj is Delegate)
                    return obj;
                if (pt == typeof(Delegate))
                    return ((IDelegateAdapter)obj).Delegate;
                return ((IDelegateAdapter)obj).GetConvertor(pt);
            }
            else if ((typeFlags & TypeFlags.IsByRef) != 0)
            {
                return CheckCLRTypes(pt.GetElementType(), obj);
            }
            else if ((typeFlags & TypeFlags.IsEnum) != 0)
            {
                return Enum.ToObject(pt, obj);
            }
            else if (obj is ILTypeInstance)
            {
                var adapter = obj as IDelegateAdapter;

                if (adapter != null && pt != typeof(ILTypeInstance))
                {
                    return adapter.Delegate;
                }

                if (!(obj is ILEnumTypeInstance))
                {
                    var ins = (ILTypeInstance)obj;
                    if (ins.IsValueType)
                        ins = ins.Clone();
                    return ins.CLRInstance;
                }
            }
            return obj;
        }
    }
}


text:
<?php

namespace ChillDev\Bundle\FileManagerBundle\Tests\Action\Handler;

use stdClass;

use PHPUnit_Framework_TestCase;

use ChillDev\Bundle\FileManagerBundle\Action\Handler\ImageViewer;
use ChillDev\Bundle\FileManagerBundle\Filesystem\Disk;
use ChillDev\Bundle\FileManagerBundle\Tests\BaseContainerTest;

use Symfony\Component\HttpFoundation\Request;

use org\bovigo\vfs\vfsStream;

/**
 * @author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
 * @copyright 2014 © by Rafał Wrzeszcz - Wrzasq.pl.
 * @version 0.1.3
 * @since 0.1.3
 * @package ChillDev\Bundle\FileManagerBundle
 */
class ImageViewerTest extends BaseContainerTest
{
    /**
     * @var Symfony\Bundle\FrameworkBundle\Templating\EngineInterface
     * @version 0.1.3
     * @since 0.1.3
     */
    protected $templating;

    /**
     * @version 0.1.3
     * @since 0.1.3
     */
    protected function setUpContainer()
    {
        parent::setUpContainer();

        $this->templating = $this->getMock('Symfony\\Bundle\\FrameworkBundle\\Templating\\EngineInterface');
    }

    /**
     * @test
     * @version 0.1.3
     * @since 0.1.3
     */
    public function getLabel()
    {
        $this->assertInternalType('string', $this->createHandler()->getLabel(), 'ImageViewer::getLabel() should return button label.');
    }

    /**
     * @test
     * @version 0.1.3
     * @since 0.1.3
     */
    public function supports()
    {
        $handler = $this->createHandler();

        $this->assertTrue($handler->supports('image/jepg'), 'ImageViewer::supports() should return TRUE for any image MIME type.');
        $this->assertTrue($handler->supports('image/gif'), 'ImageViewer::supports() should return TRUE for any image MIME type.');
        $this->assertFalse($handler->supports('text/plain'), 'ImageViewer::supports() should return FALSE for any non-image MIME type.');
    }

    /**
     * @test
     * @version 0.1.3
     * @since 0.1.3
     */
    public function handleRequest()
    {
        $path = 'foo';
        vfsStream::create([$path => 'bar']);

        // needed for closure scope
        $assert = $this;
        $toReturn = new stdClass();

        $disk = $this->manager['id'];

        $this->templating->expects($this->once())
            ->method('renderResponse')
            ->with(
                $this->equalTo('ChillDevFileManagerBundle:Action:image-viewer.html.default'),
                $this->anything(),
                $this->isNull()
            )
            ->will($this->returnCallback(function($view, $parameters) use ($assert, $toReturn, $disk, $path) {
                        $assert->assertArrayHasKey('disk', $parameters, 'ImageViewer::handle() should return disk scope object under key "disk".');
                        $assert->assertSame($disk, $parameters['disk'], 'ImageViewer::handle() should return disk scope object under key "disk".');
                        $assert->assertArrayHasKey('path', $parameters, 'ImageViewer::handle() should return path under key "path".');
                        $assert->assertSame($path, $parameters['path'], 'ImageViewer::handle() should return path under key "path".');
                        return $toReturn;
            }));

        $handler = $this->createHandler();
        $response = $handler->handle(new Request(), $disk, $path);

        $this->assertSame($toReturn, $response, 'ImageViewer::handle() should return response generated with templating service.');
    }

    /**
     * @test
     * @expectedException Symfony\Component\HttpKernel\Exception\HttpException
     * @expectedExceptionMessage "[Test]/bar" is a directory.
     * @version 0.1.3
     * @since 0.1.3
     */
    public function handleNonfilePath()
    {
        vfsStream::create(['bar' => []]);

        $this->createHandler()->handle(new Request(), $this->manager['id'], 'bar');
    }

    /**
     * @return ImageViewer
     * @version 0.1.3
     * @since 0.1.3
     */
    protected function createHandler()
    {
        return new ImageViewer(
            $this->templating
        );
    }
}


text:
CREATE INDEX applications_all_data_casedate_idx
  ON planning.applications_all_data
  USING btree
  (casedate );

CREATE INDEX applications_all_data_gsscode_id_idx
  ON planning.applications_all_data
  USING btree
  (gsscode_id );

CREATE INDEX applications_all_data_status_id_gsscode_id_idx
  ON planning.applications_all_data
  USING btree
  (status_id, gsscode_id );

CREATE INDEX applications_all_data_status_id_idx
  ON planning.applications_all_data
  USING btree
  (status_id );

CREATE INDEX applications_all_data_wkb_geometry_idx
  ON planning.applications_all_data
  USING gist
  (wkb_geometry );

CREATE INDEX areas_id_idx
  ON planning.areas
  USING btree
  (id );

CREATE INDEX applications_statuses_id_idx
  ON planning.applications_statuses
  USING btree
  (id );

CREATE INDEX applications_statuses_api_lookup_idx
  ON planning.applications_statuses
  USING btree
  (api_lookup );


text:
/**
 * Tests for Search
 *
 * @author Dena Mujtaba
 */

QUnit.module("Search Tests");


text:
/**
* @author Alexander V. Astapchuk
* @version $Revision$
*/

package org.apache.harmony.security.fortress;

import java.security.AccessControlContext;
import java.util.WeakHashMap;

//FIXME: move this class under umbrella of protected packages -
// see lib/java.security: property 'package.access',
// so only trusted classes like Thread and AccessController will
// have an access to this class.
// This is to remove dependency on VMStack, to reduce number
// of VM2API-dependent classes.

/**
 * The class is used to perform an exchange of information between
 * java.lang.Thread and java.security.AccessController.

 * The data to exchange is inherited contexts for the Thread-s.
 *
 */
public final class SecurityUtils {

    // A map used to store inherited contexts.

    // A thread is used as a key for the map and AccessControlContext
    // passed to the putContext is used as a value.
    private static final WeakHashMap<Thread, AccessControlContext> ACC_CACHE = new WeakHashMap<Thread, AccessControlContext>();

    /**
     * This method to be invoked in the Thread's constructor. The first argument
     * (thread) must be Thread's this and the second must be a snapshot of the
     * current AccessControlContext:
     *

     *
     * Thread() {

     * SecurityUtils.putContext(this,AccessController.getContext());

     *  ...do the stuff you need...

     * }

     *
     *
     * The method throws SecurityException if the method is called more than
     * once for a given thread. The first call to putContext is
     * always performed in the Thread's constructor so this effectively means
     * that no one can replace the snapshot taken.
     *
     * @throws SecurityException if a context for the passed
     *     thread already exists in the map.
     * @throws NullPointerException if thread is null
     * @throws Error if context is null AND if null context is already stored
     *     in the map
     */
    public static void putContext(Thread thread, AccessControlContext context)
            throws SecurityException {
        if (thread == null) {
            throw new NullPointerException();
        }
        synchronized (ACC_CACHE) {
            if (ACC_CACHE.containsKey(thread)) {
                throw new SecurityException("You can not modify this map");
            }
            if (context == null) {
                // this only allowed once - for the very first thread.
                if (ACC_CACHE.containsValue(null)) {
                    throw new Error("null context may be stored only once");
                }
            }
            ACC_CACHE.put(thread, context);
        }
    }

    /**
     * Returns the AccessControlContext stored for a given thread.

     * The method may return null - for the very first thread created
     * by the VM which does not have inherited context.

     * It may also return null if no Thread found in the map - that seems
     * possible during VM startup process.
     */
    public static AccessControlContext getContext(Thread thread)
            throws SecurityException {

        // ~fixme: see 'fixme' at the top of the file
        /*
         Class cl = VMStack.getCallerClass(0);
         if (cl != AccessController.class) {
         throw new SecurityException("You ["+cl+"] do not have access to this resource.");
         }
         */

        synchronized (ACC_CACHE) {
            return ACC_CACHE.get(thread);
        }
    }
}


text:
<TITLE>Review for Portrait d'une jeune fille de la fin des années 60 à Bruxelles (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Portrait d'une jeune fille de la fin des années 60 à Bruxelles (1994)

reviewed by
James Berardinelli

(Part of the Series ALL THE BOYS AND GIRLS IN THEIR TIME)

RATING (0 TO 10):  7.9

Shown at the Philadelphia Festival of World Cinema
Running Length: 0:59
MPAA Classification: Not Rated (Mature themes)

Cast: Circe, Julien Rassam, Joelle Cohen, James Brown
Director: Chantal Akerman
Screenplay: Chantal Akerman
Cinematography: Raymond Fromont
Distribution unknown
In French with subtitles

     ALL THE BOYS AND GIRLS IN THEIR TIME is a series of films
commissioned by the French-German TV station Arte.  Ten directors were
asked to participate by making a movie about their teenage years.  Each
film had to include at least one party scene which highlighted the music
of the time.  PORTRAIT OF A YOUNG GIRL AT THE END OF THE 1960S IN
BRUSSELS, Chantal Akerman's entry, takes place in April of 1968 and, as
the title states, occurs on the streets of Brussels.  Aside from a few
supporting figures, there are really only two characters:  Michelle, a
thoughtful teenage loner who has given up school, and Paul, a guy she
meets in a movie theater.

     Like Richard Linklater's BEFORE SUNRISE, this movie is about two
people walking around a European city, getting to know one another.
Some of the subjects of conversation here even match those of
Linklater's picture.  However, while SUNRISE is a love story, PORTRAIT
is something less romantic.  It's about two people learning the other's
secrets, but never really connecting.  Michelle is a lonely, morose
person who, by her own admission, hates having fun.  "Even when I'm
happy," she says, "I'm in pain, but I never show it."  Paul, on the
other hand, is eager to soothe her, but it's rare that she lets him
within arm's distance.

     Akerman, known for extremely slow-moving character dramas, speeds
up the pace a little here, although this film certainly doesn't fly by.
Nevertheless, during the one-hour running time, we get to know both
Michelle and Paul, and are given an opportunity to ponder the subjects
that arise during their rambling discussions.  Michelle is an especially
fascinating person, and perhaps the most refreshing aspect of PORTRAIT
is that it allows us to spend time with her without foisting distracting
plot complications upon us.  Akerman has painted just what the title
suggests -- a portrait for all who enjoy a slow-paced, leisurely look at
a select character and her circumstances.

- James Berardinelli (jberardinell@delphi.com)

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
@implementation ChromePushMessaging

@synthesize notificationMessage;

@synthesize callbackId;
@synthesize notificationCallbackId;
@synthesize callback;
@synthesize registrationToken;

- (void) getRegistrationId:(CDVInvokedUrlCommand *)command; {
    self.callbackId = command.callbackId;
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not Registered"];
    if(registrationToken) {
       commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:registrationToken];
    }
    [self.commandDelegate sendPluginResult:commandResult callbackId:self.callbackId];
}

- (void)messageChannel:(CDVInvokedUrlCommand *)command; {
    self.callbackId = command.callbackId;

    UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert;

    [self.commandDelegate runInBackground:^{
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];

        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];

    // check if there is a pending message (probably the message that started the app)
    // if there is, process it.
    // note that there can only be one. If you got several, only the last one is still around.
    if (notificationMessage) [self notificationReceived];
}

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
                      stringByReplacingOccurrencesOfString:@">" withString:@""]
                     stringByReplacingOccurrencesOfString: @" " withString: @""];
          NSLog(@"Register Msg: %@", token);

    // this token needs to be kept and returned to the application so it can be used to send message here
    registrationToken = token;
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token];
    [self.commandDelegate sendPluginResult:commandResult callbackId:self.callbackId];
}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    // something bad happened. No messaging is going to happen

    NSString *message = @"Registration failed";
    NSString *errorMessage = (error) ? [NSString stringWithFormat:@"%@ - %@", message, [error localizedDescription]] : message;
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
    [self.commandDelegate sendPluginResult:commandResult callbackId:self.callbackId];
}

- (void)notificationReceived {

    if (notificationMessage ) {
       NSError *error;
       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notificationMessage options:0 error:&error];
       NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

       NSLog(@"Msg: %@", jsonStr);
       [self writeJavascript: [NSString stringWithFormat:@"chrome.pushMessaging.onMessage.fire({subchannelId:0, payload:'%@'})", jsonStr]];

       self.notificationMessage = nil;
    }
}

@end


text:
from tokens import find_tokens, TokenMap
from base import TransLocObject, _IGNORED_WORDS

class Route(TransLocObject):

  """ Represents a Transloc Route

      color and text_color attributes are included in the JSON response, but removed
      here
  """

  def __init__(self, stops=[], bounds=[], description='',
               id=0, is_hidden=False, long_name='',
               short_name='', type='', url='', **kwargs):
    self.stops = stops
    self.bounds = bounds
    self.description = description
    self.id = id
    self.is_hidden = is_hidden
    self.long_name = long_name.encode('utf-8')
    self.short_name = short_name
    self.name = self.long_name
    self.type = type
    self.url = url
    self.tokens = find_tokens(self.long_name)
    self._stops_token_map = TokenMap.from_list(self.stops)

  def find_stops(self, phrase):
    return self._stops_token_map.find(phrase, ignore=_IGNORED_WORDS)

  @classmethod
  def from_json(cls, json, stops=[]):
    return Route(stops, **json)

  def __repr__(self):
    return str(self)

  def __str__(self):
    return '<Route:: %s,%s>' % (self.id, self.name)


text:
'use strict';
const BufferStreams = require('bufferstreams');
const cssBrowserReporter = require('./css-browser-reporter');
const jsBrowserReporter = require('./js-browser-reporter');
/**
 * 在文件内容上追加错误汇报信息
 * @param  {Vinyl}  file   需要检查的文件
 * @param  {Array}  errors 错误信息
 * @param  {Buffer} [buf=buffile.contents]  文件内容buffer, 默认从file.contents获取
 * @return {Buffer}        新的文件内容
 */
function appendReporter (file, errors, buf) {
	buf = buf || file.contents;

	// 在buffer中的代码中注入报错语句
	let contentReporter;

	if (file.postcss || file.csslint) {
		contentReporter = cssBrowserReporter(errors);
	} else if (file.jshint || file.eslint || file.jscs) {
		contentReporter = `\n;\n(${jsBrowserReporter})(${JSON.stringify(errors, circular())});`;
	}

	if (contentReporter) {
		return Buffer.concat([buf, Buffer.from(contentReporter)]);
	} else {
		return buf;
	}
}

/**
 * 为Vinyl对象追加错误汇报内容
 * @param  {Vinyl}  file     要处理的文件
 * @param  {Array}  [errors] 错误信息
 * @return {undefined}
 */
function browserReporter (file, errors) {
	errors = errors || file.report.errors;
	if (file.isStream()) {
		file.contents = file.contents.pipe(new BufferStreams((err, buf, done) => {
			if (err) {
				done(err, buf);
			} else {
				done(null, appendReporter(file, errors, buf));
			}
		}));
	} else if (file.isBuffer()) {
		file.contents = appendReporter(file, errors);
	}
}

function circular () {
	const cache = [];
	return (key, value) => {
		if (typeof value === 'object' && value !== null) {
			if (cache.indexOf(value) !== -1) {
				// Circular reference found, discard key
				return;
			}
			// Store value in our collection
			cache.push(value);
		}
		return value;
	};
}

module.exports = browserReporter;


text:
import classNames from 'classnames';
import { Component } from 'react';
import Emoji from 'app/components/Emoji';
import Tooltip from 'app/components/Tooltip';
import type { ID } from 'app/models';
import styles from './Reaction.css';

type Props = {
  className?: string;
  emoji: string;
  count: number;
  unicodeString: string;
  addReaction: (arg0: {
    emoji: string;
    contentTarget: string;
    unicodeString?: string;
  }) => Promise<void>;
  deleteReaction: (arg0: {
    reactionId: ID;
    contentTarget: string;
  }) => Promise<void>;
  hasReacted: boolean;
  canReact: boolean;
  reactionId: ID;
  contentTarget: string;
}; // Note: Most use cases won't want to use this class directly. Instead, use
// app/components/LegoReactions.

class Reaction extends Component<Props> {
  render() {
    const {
      className,
      emoji,
      count,
      unicodeString,
      addReaction,
      deleteReaction,
      hasReacted,
      canReact,
      reactionId,
      contentTarget,
    } = this.props;
    const classes = [
      className ? className : styles.reaction,
      canReact && styles.clickable,
    ];

    if (hasReacted) {
      classes.push(styles.reacted);
    }

    if (count === 0) {
      return <></>;
    }

    return (

        <Tooltip content={emoji}>

                    hasReacted
                      ? deleteReaction({
                          reactionId,
                          contentTarget: contentTarget,
                        })
                      : addReaction({
                          emoji,
                          contentTarget,
                          unicodeString,
                        })
                : null
            }
          >

              <Emoji unicodeString={unicodeString} />

{count}

        </Tooltip>

    );
  }
}

export default Reaction;


text:
package com.github.pockethub.core.gist;

import android.accounts.Account;
import android.content.Context;
import android.util.Log;

import com.alorma.github.sdk.bean.dto.response.Gist;
import com.github.pockethub.accounts.AuthenticatedUserTask;
import com.github.pockethub.api.StarGistClient;

/**
 * Task to star a {@link Gist}
 */
public class StarGistTask extends AuthenticatedUserTask<Gist> {

    private static final String TAG = "StarGistTask";

    private final String id;

    /**
     * Create task to star a {@link Gist}
     *
     * @param context
     * @param id
     */
    public StarGistTask(final Context context, final String id) {
        super(context);

        this.id = id;
    }

    @Override
    public Gist run(Account account) throws Exception {
        StarGistClient client = new StarGistClient(id);
        client.observable().toBlocking().first();
        return null;
    }

    @Override
    protected void onException(Exception e) throws RuntimeException {
        super.onException(e);

        Log.d(TAG, "Exception starring gist", e);
    }
}


text:
#ifndef TEST_MAC_VIDEO_RENDERER_MAC_H_
#define TEST_MAC_VIDEO_RENDERER_MAC_H_

#include BOSS_WEBRTC_U_rtc_base__constructormagic_h //original-code:"rtc_base/constructormagic.h"
#include "test/gl/gl_renderer.h"

@class CocoaWindow;

namespace webrtc {
namespace test {

class MacRenderer : public GlRenderer {
 public:
  MacRenderer();
  virtual ~MacRenderer();

  bool Init(const char* window_title, int width, int height);

  // Implements GlRenderer.
  void OnFrame(const VideoFrame& frame) override;

 private:
  CocoaWindow* window_;

  RTC_DISALLOW_COPY_AND_ASSIGN(MacRenderer);
};
}  // test
}  // webrtc

#endif  // TEST_MAC_VIDEO_RENDERER_MAC_H_


text:
var DateTime = require('../DateTime.js');
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  React.createElement(DateTime, {
    viewMode: 'months',
    dateFormat: 'MMMM',
    isValidDate: function(current) {
      return current.isBefore(DateTime.moment().startOf('month'));
    }
  }),
  document.getElementById('datetime')
);


text:
package org.eclipse.om2m.binding.http.constants;

public class HttpParameters {

	/** Private constructor */
	private HttpParameters() {
	}

	public static final String RESPONSE_TYPE = "rt";
	public static final String RESULT_PERSISTENCE = "rp";
	public static final String RESULT_CONTENT = "rcn";
	public static final String DELIVERY_AGGREGATION = "da";
	public static final String CREATED_BEFORE = "crb";
	public static final String CREATED_AFTER = "cra";
	public static final String MODIFIED_SINCE = "ms";
	public static final String UNMODIFIED_SINCE = "us";
	public static final String STATE_TAG_SMALLER = "sts";
	public static final String STATE_TAG_BIGGER = "stb";
	public static final String EXPIRE_BEFORE = "exb";
	public static final String EXPIRE_AFTER = "exa";
	public static final String LABELS = "lbl";
	public static final String RESOURCE_TYPE = "ty";
	public static final String SIZE_ABOVE = "sza";
	public static final String SIZE_BELOW = "szb";
	public static final String CONTENT_TYPE = "cty";
	public static final String LIMIT = "lim";
	public static final String ATTRIBUTE = "atr";
	public static final String FILTER_USAGE = "fu";
	public static final String DISCOVERY_RESULT_TYPE = "drt";
}


text:
<?php

class Application_Cli_CreateUsers
{

    public function __construct($zend = null)
    {
        if (isset($zend)) {
            $this->_zend = $zend->bootstrap();
        }

    }

    public function process($args = null)
    {
        $users = new Application_Model_DBUsers();
        $users->save_item("xpto@mail.com", "testing");
    }
}

// Bootstrap ZendFW1

$cur_dir   = getcwd();
$path_dir  = substr($cur_dir, 0, (strlen($cur_dir) - strlen("/aplication/cli")));
$real_path = realpath($path_dir . "/application");

// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH',
realpath($real_path));

// Define path to basepath directory
defined('BASE_PATH')
|| define('BASE_PATH', realpath($path_dir));

// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV',
(getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
    : 'production'));

// Ensure library/ is on include_path
set_include_path(
    implode(
        PATH_SEPARATOR,
        array(
            realpath(APPLICATION_PATH . '/../library'),
            get_include_path(),
        )
    )
);

$config_path = '/configs/application.ini';
if (PHP_OS == 'WINNT' || PHP_OS == 'WIN32') {
    $config_path = str_replace('/', '\\', $config_path);
}

require_once 'Zend/Application.php';
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . $config_path
);

$me = new Application_Cli_CreateUsers($application);
$me->process($argv);


text:
<?php

namespace Igniter\Flame\Scaffold;

use Illuminate\Support\ServiceProvider;

class ScaffoldServiceProvider extends ServiceProvider
{
    protected $defer = true;

    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [
        'CreateExtension' => 'command.create.extension',
        'CreateComponent' => 'command.create.component',
        'CreateController' => 'command.create.controller',
        'CreateModel' => 'command.create.model',
        'CreateCommand' => 'command.create.command',
    ];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerCommands($this->commands);
    }

    /**
     * Register the given commands.
     *
     * @param  array $commands
     *
     * @return void
     */
    protected function registerCommands(array $commands)
    {
        foreach ($commands as $class => $command) {
            $this->{"register{$class}Command"}($command);
        }

        $this->commands(array_values($commands));
    }

    protected function registerCreateExtensionCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Console\CreateExtension($app['files']);
        });
    }

    protected function registerCreateComponentCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Console\CreateComponent($app['files']);
        });
    }

    protected function registerCreateControllerCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Console\CreateController($app['files']);
        });
    }

    protected function registerCreateModelCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Console\CreateModel($app['files']);
        });
    }

    protected function registerCreateCommandCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Console\CreateCommand($app['files']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_values($this->commands);
    }
}


text:
//
//  SSTwitterTweetsReader.h
//  TwitterConnection
//
//  Created by 冯 鸿杰 on 13-10-24.
//  Copyright (c) 2013年 掌淘科技. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SSTwitterCoordinatesReader.h"
#import "SSTwitterEntitiesReader.h"
#import "SSTwitterPlacesReader.h"

@class SSTwitterUserReader;

/**
 *	@brief	Tweets信息读取器
 */
@interface SSTwitterTweetsReader : NSObject
{
@private
    NSDictionary *_sourceData;
}

/**
 *	@brief	源数据
 */
@property (nonatomic,readonly) NSDictionary *sourceData;

/**
 *	@brief	未使用
 */
@property (nonatomic,readonly) id annotations;

/**
 *	@brief	一个贡献用户对象的集合
 */
@property (nonatomic,readonly) NSArray *contributors;

/**
 *	@brief	表示由用户或客户端应用程序报告该Tweets的地理位置
 */
@property (nonatomic,readonly) SSTwitterCoordinatesReader *coordinates;

/**
 *	@brief	Tweets的创建时间
 */
@property (nonatomic,readonly) NSString *createdAt;

/**
 *	@brief	当前用户转发Tweet,仅当支持include_my_retweet参数的接口中设置该参数为true时显示,
 */
@property (nonatomic,readonly) id currentUserRetweet;

/**
 *	@brief	实体信息
 */
@property (nonatomic,readonly) SSTwitterEntitiesReader *entities;

/**
 *	@brief	是否收藏
 */
@property (nonatomic,readonly) BOOL favorited;

/**
 *	@brief	已过期,用coordinates代替
 */
@property (nonatomic,readonly) id geo;

/**
 *	@brief	Tweet ID
 */
@property (nonatomic,readonly) long long Id;

/**
 *	@brief	Tweet ID字符串
 */
@property (nonatomic,readonly) NSString *idStr;

/**
 *	@brief	源Tweet的用户屏幕名称
 */
@property (nonatomic,readonly) NSString *inReplyToScreenName;

/**
 *	@brief	源Tweet的ID
 */
@property (nonatomic,readonly) long long inReplyToStatusId;

/**
 *	@brief	源Tweet的ID字符串
 */
@property (nonatomic,readonly) NSString *inReplyToStatusIdStr;

/**
 *	@brief	源Tweet的用户ID
 */
@property (nonatomic,readonly) long long inReplyToUserId;

/**
 *	@brief	源Tweet的用户ID字符串
 */
@property (nonatomic,readonly) NSString *inReplyToUserIdStr;

/**
 *	@brief	Tweet关联地点
 */
@property (nonatomic,readonly) SSTwitterPlacesReader *place;

/**
 *	@brief	指示内容是否包含敏感内容
 */
@property (nonatomic,readonly) BOOL possiblySensitive;

/**
 *	@brief	A set of key-value pairs indicating the intended contextual delivery of the containing Tweet. Currently used by Twitter's Promoted Products
 */
@property (nonatomic,readonly) id scopes;

/**
 *	@brief	转推数量
 */
@property (nonatomic,readonly) NSInteger retweetCount;

/**
 *	@brief	转推标识,表示当前用户是否转推该Tweet
 */
@property (nonatomic,readonly) BOOL retweeted;

/**
 *	@brief	Tweet来源
 */
@property (nonatomic,readonly) NSString *source;

/**
 *	@brief	内容
 */
@property (nonatomic,readonly) NSString *text;

/**
 *	@brief	表示text参数的值是否被截断
 */
@property (nonatomic,readonly) BOOL truncated;

/**
 *	@brief	发布用户
 */
@property (nonatomic,readonly) SSTwitterUserReader *user;

/**
 *	@brief	When present and set to "true", it indicates that this piece of content has been withheld due to a DMCA complaint
 */
@property (nonatomic,readonly) BOOL withheldCopyright;

/**
 *	@brief When present, indicates a list of uppercase two-letter country codes this content is withheld from.
 */
@property (nonatomic,readonly) NSArray *withheldInCountries;

/**
 *	@brief	When present, indicates whether the content being withheld is the "status" or a "user."
 */
@property (nonatomic,readonly) NSString *withheldScope;

/**
 *	@brief	初始化读取器
 *
 *	@param 	sourceData 	原数据
 *
 *	@return	读取器实例对象
 */
- (id)initWithSourceData:(NSDictionary *)sourceData;

/**
 *	@brief	创建Tweets信息读取器
 *
 *	@param 	sourceData 	原数据
 *
 *	@return	读取器实例对象
 */
+ (SSTwitterTweetsReader *)readerWithSourceData:(NSDictionary *)sourceData;

@end


text:
title: earlylightmedia.com
date: 2016-09-07 00:00:00 +0000
related_tools:
- tool/spike.md
- tool/contentful.md
website: http://www.earlylightmedia.com
repo: https://github.com/earlylightmedia/www
creator:
- name: Sarah Fox
  role: logo & web design
  url: http://www.thecommonfox.com/#/earlylightmedia/
- name: Kara Redman
  role: branding
  url: http://backroom.io/
- name: Vassilis Terzopoulos
  role: front-end / jekyll development
  url: http://three99.com/
- name: Tom Kraak
  role: 'front-end / jekyll development:'
  url: http://backroom.io/
- name: Tom Kraak
  role: site migration from jekyll to roots & contentful
  url: http://backroom.io/
images:
- "/uploads/showcase-earlylightmedia-roots.jpg"

---


text:
from __future__ import unicode_literals

from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from adminsortable2.admin import SortableAdminMixin
from shop.admin.product import CMSPageAsCategoryMixin, ProductImageInline
from myshop.models import SmartCard

@admin.register(SmartCard)
class SmartCardAdmin(SortableAdminMixin, CMSPageAsCategoryMixin, admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('product_name', 'slug', 'product_code', 'unit_price', 'active', 'description',),
        }),
        (_("Properties"), {
            'fields': ('manufacturer', 'storage', 'card_type', 'speed',)
        }),
    )
    inlines = (ProductImageInline,)
    prepopulated_fields = {'slug': ('product_name',)}
    list_display = ('product_name', 'product_code', 'unit_price', 'active',)
    search_fields = ('product_name',)


text:
This example uses custom transform rules to remove debug code from the source.
Look at the AstNode class in doctor's API documentation for the manipulation
you can do to AST nodes. Here, the remove method is used to remove a function
call if the name of the function is "debug".

```js
rules.push({
  type: 'call',
  match: function (node) {
    return node.nodes[0].value === 'debug';
  },
  transform: function (node) {
    node.remove();
  }
});
```

The ast report rules are used to simply copy the ast into the report. The source
renderer is then used to convert the ast back into source code.

You can run the following command in examples/remove-debug to try it out.

```bash
doctor square.js -t transform.js --render source --report ast
```


text:
//
// FastTemplate
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeff Panici

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System.Reflection.Emit;

namespace PaniciSoftware.FastTemplate.Common
{
    public static class ILGeneratorExtensions
    {
        public static void FastEmitLoadArg(this ILGenerator sink, int index)
        {
            switch (index)
            {
                case 0:
                    sink.Emit(OpCodes.Ldarg_0);
                    break;
                case 1:
                    sink.Emit(OpCodes.Ldarg_1);
                    break;
                case 2:
                    sink.Emit(OpCodes.Ldarg_2);
                    break;
                case 3:
                    sink.Emit(OpCodes.Ldarg_3);
                    break;
                default:
                    sink.Emit(OpCodes.Ldarg, index);
                    break;
            }
        }

        public static void FastEmitConstInt(this ILGenerator sink, int i)
        {
            switch (i)
            {
                case 0:
                    sink.Emit(OpCodes.Ldc_I4_0);
                    break;
                case 1:
                    sink.Emit(OpCodes.Ldc_I4_1);
                    break;
                case 2:
                    sink.Emit(OpCodes.Ldc_I4_2);
                    break;
                case 3:
                    sink.Emit(OpCodes.Ldc_I4_3);
                    break;
                case 4:
                    sink.Emit(OpCodes.Ldc_I4_4);
                    break;
                case 5:
                    sink.Emit(OpCodes.Ldc_I4_5);
                    break;
                case 6:
                    sink.Emit(OpCodes.Ldc_I4_6);
                    break;
                case 7:
                    sink.Emit(OpCodes.Ldc_I4_7);
                    break;
                case 8:
                    sink.Emit(OpCodes.Ldc_I4_8);
                    break;
                default:
                    sink.Emit(OpCodes.Ldc_I4, i);
                    break;
            }
        }

        public static void FastEmitLoadLocal(this ILGenerator sink, int index)
        {
            switch (index)
            {
                case 0:
                    sink.Emit(OpCodes.Ldloc_0);
                    break;
                case 1:
                    sink.Emit(OpCodes.Ldloc_1);
                    break;
                case 2:
                    sink.Emit(OpCodes.Ldloc_2);
                    break;
                case 3:
                    sink.Emit(OpCodes.Ldloc_3);
                    break;
                default:
                    sink.Emit(OpCodes.Ldloc, index);
                    break;
            }
        }

        public static void FastEmitStoreLocal(this ILGenerator sink, int index)
        {
            switch (index)
            {
                case 0:
                    sink.Emit(OpCodes.Stloc_0);
                    break;
                case 1:
                    sink.Emit(OpCodes.Stloc_1);
                    break;
                case 2:
                    sink.Emit(OpCodes.Stloc_2);
                    break;
                case 3:
                    sink.Emit(OpCodes.Stloc_3);
                    break;
                default:
                    sink.Emit(OpCodes.Stloc, index);
                    break;
            }
        }
    }
}


text:
rock.namespace('rock.resource.loader');

/**
 * Class to load an image resource
 *
 * @constructor
 * @extends rock.resource.loader.AbstractResourceLoader
 * @author Luis Alberto Jiménez
 */
rock.resource.loader.ImageResourceLoader = function () {
    rock.super_(this, arguments);
};

rock.extends_(rock.resource.loader.ImageResourceLoader,
    rock.resource.loader.AbstractResourceLoader);

/**
 * @override
 * @see rock.resource.loader.AbstractResourceLoader#loadResource
 */
rock.resource.loader.ImageResourceLoader.prototype.loadResource = function (elem) {
    var HTMLImage = new Image();
    HTMLImage.id = elem.id;

    HTMLImage.onload = rock.createEventHandler(this, this.onLoadImage, [elem,
        HTMLImage]);

    HTMLImage.onerror = rock.createEventHandler(this, this.onErrorImage, [
        elem, HTMLImage]);

    HTMLImage.onabort = rock.createEventHandler(this, this.onAbortImage, [
        elem, HTMLImage]);

    HTMLImage.src = elem.getHTTPParams().getUrl();
};

/*
 * Event handler for an image
 */
rock.resource.loader.ImageResourceLoader.prototype.onLoadImage = function (event, elem, HTMLImage) {
    this.callResourceLoader(event, elem, HTMLImage, true);
};

/*
 * Event handler for an image
 */
rock.resource.loader.ImageResourceLoader.prototype.onErrorImage = function (event, elem, HTMLImage) {
    this.callResourceLoader(event, elem, HTMLImage, false);
};

/*
 * Event handler for an image
 */
rock.resource.loader.ImageResourceLoader.prototype.onAbortImage = function (event, elem, HTMLImage) {
    this.callResourceLoader(event, elem, HTMLImage, false);
};

rock.resource.loader.ImageResourceLoader.prototype.callResourceLoader = function (event, elem, HTMLImage, success) {
    var image = new rock.graphics.Image(HTMLImage);
    this.resourceLoaderManager.onResourceLoadEvent(success, elem, image);
};


text:
<?php namespace Serverfireteam\blog;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Serverfireteam\Panel\libs\dashboard;

class BlogController extends BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /blog
	 *
	 * @return Response
	 */
	public function getIndex()
	{
            $mostRecommended = \App\Blog::mostRecommended();
            $last            = \App\Blog::lastPosts(null,6);
            $featuredEvents  = \App\Blog::featuredEventsPosts();

            return View('blog::index',array('mostRecommended'=>$mostRecommended,'last'=>$last,'featuredEvents'=>$featuredEvents));
	}

    public static function seoUrl($string) {
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }
	/**
	 * Display the specified resource.
	 * GET /blog/{id}/title
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function getPost($id)
	{
            $post = \App\Blog::find($id);
            if($post == NULL){
                App::abort(404);
            }
            return View('blog::post',array('title'=>$post['title'],'post'=>$post));
	}

    /**
     * Add the point to
     *
     *
     */
    public function getShare($id,$social)
    {
        $url = '';
        $post = \App\Blog::find($id);
        if($post == NULL){
            App::abort(404);
        }

        // add social point if it is not robot
        if (!isset($_SERVER['HTTP_USER_AGENT']) && !preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
            $post->socialPoint ++;
            $post->save();
        }
        switch ($social){
            case 'twitter' :
                $url  = 'https://twitter.com/home?status=';
                $url .= $post['title'] . ' ' . $post->getUrl();
            break;
            case 'facebook' :
                $url  = 'https://www.facebook.com/sharer/sharer.php?u=';
                $url .=  $post->getUrl();
            break;
            case 'googlePlus' :
                $url  = 'https://plus.google.com/share?url=';
                $url .= $post->getUrl();
            break;
            case 'linkedIn' :
                $url  = 'https://www.linkedin.com/shareArticle?mini=true&';
                $url .= 'url='.$post->getUrl().'&title='.$post['title'].'&summary=&source=';
            break;
        }
        return \Redirect::to($url);
    }

}