text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

using Xunit;

namespace System.Net.Primitives.Unit.Tests
{
    public class CookieContainerTest
    {
        private const string u1 = ".url1.com"; // Basic domain
        private const string u2 = "127.0.0.1"; // Local domain
        private const string u3 = "url3.com"; // Basic domain without a leading dot
        private static readonly Uri u4 = new Uri("http://url4.com"); // Basic uri
        private static readonly Uri u5 = new Uri("http://url5.com/path"); // Set explicit path
        private static readonly Uri u6 = new Uri("http://url6.com"); // No cookies should be added with this uri

        private static readonly Cookie c1 = new Cookie("name1", "value", "", u1);
        private static readonly Cookie c2 = new Cookie("name2", "value", "", u1) { Secure = true };
        private static readonly Cookie c3 = new Cookie("name3", "value", "", u1) { Port = "\"80, 90, 100, 443\"" };
        private static readonly Cookie c4 = new Cookie("name4", "value", "", u2);
        private static readonly Cookie c5 = new Cookie("name5", "value", "/path", u2);
        private static readonly Cookie c6 = new Cookie("name6", "value", "", "." + u3);
        private static readonly Cookie c7 = new Cookie("name7", "value", "", "." + u3);
        private static readonly Cookie c8 = new Cookie("name8", "value");
        private static readonly Cookie c9 = new Cookie("name9", "value");
        private static readonly Cookie c10 = new Cookie("name10", "value");
        private static readonly Cookie c11 = new Cookie("name11", "value") { Port = "\"80, 90, 100\"" };

        private const string CookieName1 = "CookieName1";
        private const string CookieName2 = "CookieName2";
        private const string CookieValue1 = "CookieValue1";
        private const string CookieValue2 = "CookieValue2";

        private CookieContainer CreateCount11Container()
        {
            CookieContainer cc1 = new CookieContainer();
            // Add(Cookie)
            cc1.Add(c1);
            cc1.Add(c2);
            cc1.Add(c3);
            cc1.Add(c4);

            // Add(CookieCollection)
            CookieCollection cc2 = new CookieCollection();
            cc2.Add(c5);
            cc2.Add(c6);
            cc2.Add(c7);
            cc1.Add(cc2);

            // Add(Uri, Cookie)
            cc1.Add(u4, c8);
            cc1.Add(u4, c9);

            // Add(Uri, CookieCollection)
            cc2 = new CookieCollection();
            cc2.Add(c10);
            cc2.Add(c11);
            cc1.Add(u5, cc2);

            return cc1;
        }

        [Fact]
        public void Add_Cookies_Success()
        {
            CookieContainer cc = CreateCount11Container();
            Assert.Equal(11, cc.Count);
        }

        [Fact]
        public void GetCookies_NonExistent_NoResults()
        {
            CookieContainer cc = CreateCount11Container();
            Assert.Equal(0, cc.GetCookies(new Uri("http://non.existent.uri.com")).Count);
        }

        public static IEnumerable<object[]> GetCookieHeaderData()
        {
            yield return new object[] { new Uri("http://url1.com"), "name1=value; $Version=1; name3=value; $Domain=.url1.com; $Port=\"80, 90, 100, 443\"" };
            yield return new object[] { new Uri("https://url1.com"), "name1=value; name2=value; $Version=1; name3=value; $Domain=.url1.com; $Port=\"80, 90, 100, 443\"" };
            yield return new object[] { new Uri("http://127.0.0.1"), "name4=value" };
            yield return new object[] { new Uri("http://127.0.0.1/path"), "name5=value; name4=value" };
            yield return new object[] { new Uri("http://url3.com"), "name6=value; name7=value" };
            yield return new object[] { u4, "name8=value; name9=value" };
            yield return new object[] { u5, "name10=value; $Version=1; name11=value; $Port=\"80, 90, 100\"" };
            yield return new object[] { u6, string.Empty };
        }

        public static IEnumerable<object[]> SetCookiesData()
        {
            yield return new object[]
            {
                u5,
                "name98=value98, name99=value99",
                new Cookie[]
                {
                    c10,
                    new Cookie("name98", "value98"),
                    new Cookie("name99", "value99"),
                    c11
                }
            }; // Simple

            Uri u = new Uri("http://uri.com");
            Uri uSecure = new Uri("https://uri.com");

            yield return new object[]
            {
                u,
                "name98=value98; path=/; domain=.uri.com; expires=Wed, 09 Jun 2021 10:18:14 GMT, name99=value99",
                new Cookie[]
                {
                    new Cookie("name99", "value99"),
                    new Cookie("name98", "value98", "/", ".uri.com") { Expires = new DateTime(2021, 6, 9, 10, 18, 14) }
                }
            }; // Version0

            yield return new object[]
            {
                uSecure,
                "name98=value98; comment=comment; domain=.uri.com; max-age=400; path=/; secure; port; Version=100, name99=value99",
                new Cookie[]
                {
                    new Cookie("name99", "value99"),
                    new Cookie("name98", "value98", "/", ".uri.com") { Port = "", Version = 100, Secure = true, Comment = "comment" }
                }
            }; // RFC 2109

            yield return new object[]
            {
                uSecure,
                "name98=value98; comment=comment; commentURL=http://url.com; discard; secure; domain=.uri.com; max-age=400; path=/; port=\"80, 90, 443\"; httponly; Version=100, name99=value99",
                new Cookie[]
                {
                    new Cookie("name99", "value99"),
                    new Cookie("name98", "value98", "/", ".uri.com") { Port = "\"80, 90, 443\"", Version = 100, Secure = true, HttpOnly = true, Discard = true, Comment = "comment", CommentUri = new Uri("http://url.com") },
                }
            }; // RFC 2965

            yield return new object[] { u,
                "name98=value98; port=\"80, 90\", name99=value99",
                new Cookie[]
                {
                    new Cookie("name99", "value99"),
                    new Cookie("name98", "value98", "/", ".uri.com") { Port = "\"80, 90\"" },
                }
            }; // RFC 2965 (no path)

            yield return new object[] {
                uSecure,
                "name98=value98; name98=value98; comment=comment; comment=comment2; commentURL=http://url.com; commentURL=commentURL2; discard; discard; domain=.uri.com; domain=domain2; max-age=400; max-age=400; path=/; path=path; port=\"80, 90, 443\"; port=port2; path=path; expires=Wed, 09 Jun 2021 10:18:14 GMT; expires=expires2; secure; secure; httponly; httponly; Version=100; Version=100, name99=value99",
                new Cookie[]
                {
                    new Cookie("name99", "value99"),
                    new Cookie("name98", "value98", "/", ".uri.com") { Port = "\"80, 90, 443\"", Version = 100, Secure = true, HttpOnly = true, Discard = true, Expires = new DateTime(2021, 6, 9, 10, 18, 14), Comment = "comment", CommentUri = new Uri("http://url.com") }
                }
            }; // Double entries

            yield return new object[] {
                u,
                "name98=value98; commentURL=invalidurl",
                new Cookie[]
                {
                    new Cookie("name98", "value98")
                }
            }; // Ignore invalid comment url

            yield return new object[] {
                u6,
                "name98=value98; unknown1; unknown2=unknown",
                new Cookie[]
                {
                    new Cookie("name98", "value98")
                }
            }; // Ignore unknown tokens

            yield return new object[] {
                u6,
                "name98=value98; =; token=",
                new Cookie[]
                {
                    new Cookie("name98", "value98")
                }
            }; // Ignore invalid tokens

            yield return new object[] {
                u6,
                "name98=\"value; domain=\".domain\"; max-age=\"400\"",
                new Cookie[]
                {
                    new Cookie("name98", "\"value; domain=\"")
                }
            }; // Use escaped values (1)

            yield return new object[] {
                u6,
                "name98=\"\"",
                new Cookie[]
                {
                    new Cookie("name98", "\"\"")
                }
            }; // Use escaped values (2)
        }

        [Theory]
        [MemberData(nameof(GetCookieHeaderData))]
        public void GetCookieHeader_Success(Uri uri, string expected)
        {
            CookieContainer cc = CreateCount11Container();
            Assert.Equal(expected, cc.GetCookieHeader(uri));
        }

        [Theory]
        [MemberData(nameof(SetCookiesData))]
        public void SetCookies_Success(Uri uri, string cookieHeader, Cookie[] expected)
        {
            CookieContainer cc = CreateCount11Container();
            cc.SetCookies(uri, cookieHeader);
            // Now that we've set cookie headers, we should now check to see if they're added
            VerifyGetCookies(cc, uri, expected);
        }

        [Fact]
        public void Add_CookieVersion1AndRootDomainWithNoLeadingDot_ThrowsCookieException()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie = new Cookie(CookieName1, CookieValue1) { Version = 1, Domain = OriginalDomain };
            var uri = new Uri(SchemePrefix + OriginalDomain);
            Assert.Throws<CookieException>(() => container.Add(uri, cookie));
        }

        [Fact]
        public void GetCookies_AddCookiesWithImplicitDomain_CookiesReturnedOnlyForExactDomainMatch()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie1 = new Cookie(CookieName1, CookieValue1);
            var cookie2 = new Cookie(CookieName2, CookieValue2) { Version = 1 };
            var uri = new Uri(SchemePrefix + OriginalDomain);
            container.Add(uri, cookie1);
            container.Add(uri, cookie2);

            CookieCollection cookies = container.GetCookies(uri);
            Assert.Equal(2, cookies.Count);
            Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);
            Assert.Equal(OriginalDomain, cookies[CookieName2].Domain);

            uri = new Uri(SchemePrefix + "www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);
        }

        [Fact]
        public void GetCookies_AddCookieVersion0WithExplicitDomain_CookieReturnedForDomainAndSubdomains()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie1 = new Cookie(CookieName1, CookieValue1) { Domain = OriginalDomain };
            container.Add(new Uri(SchemePrefix + OriginalDomain), cookie1);

            var uri = new Uri(SchemePrefix + OriginalDomain);
            CookieCollection cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);
            Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);

            uri = new Uri(SchemePrefix + "www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);
        }

        [Fact]
        public void GetCookies_AddCookieVersion1WithExplicitDomain_CookieReturnedForDomainAndOneLevelSubDomain()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";
            const string OriginalDomainWithLeadingDot = "." + OriginalDomain;

            var container = new CookieContainer();
            var cookie1 = new Cookie(CookieName1, CookieValue1) { Domain = OriginalDomainWithLeadingDot, Version = 1 };
            container.Add(new Uri(SchemePrefix + OriginalDomain), cookie1);

            var uri = new Uri(SchemePrefix + OriginalDomain);
            CookieCollection cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);
            Assert.Equal(OriginalDomainWithLeadingDot, cookies[CookieName1].Domain);

            uri = new Uri(SchemePrefix + "www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);
        }

        [Fact]
        public void Ctor_Capacity_Success()
        {
            CookieContainer cc = new CookieContainer(5);
            Assert.Equal(5, cc.Capacity);
        }

        [Fact]
        public void Ctor_Capacity_Invalid()
        {
            AssertExtensions.Throws<ArgumentException>("Capacity", () => new CookieContainer(0)); // Capacity <= 0
        }

        [Fact]
        public void Ctor_CapacityPerDomainCapacityMaxCookieSize_Success()
        {
            CookieContainer cc = new CookieContainer(5, 4, 3);
            Assert.Equal(5, cc.Capacity);
            Assert.Equal(4, cc.PerDomainCapacity);
            Assert.Equal(3, cc.MaxCookieSize);

            cc = new CookieContainer(10, int.MaxValue, 4); // Even though PerDomainCapacity > Capacity, this shouldn't throw
        }

        [Fact]
        public void Add_ExpiredCookie_NotAdded()
        {
            CookieContainer cc = new CookieContainer();
            Cookie c1 = new Cookie("name1", "value", "", ".domain.com") { Expired = true };
            Cookie c2 = new Cookie("name2", "value", "", ".domain.com");

            cc.Add(c1);
            cc.Add(c2);
            // Ignores adding expired cookies
            Assert.Equal(1, cc.Count);
            Assert.Equal(c2, cc.GetCookies(new Uri("http://domain.com"))[0]);

            // Manually expire cookie
            c2.Expired = true;
            cc.Add(c2);
            Assert.Equal(0, cc.Count);
        }

        [Fact]
        public void Add_ReachedMaxDomainCapacity_NotAdded()
        {
            CookieContainer cc = new CookieContainer() { PerDomainCapacity = 1 };
            cc.Add(c1); // Add a cookie to fill up the capacity
            Assert.Equal(1, cc.Count);
            cc.Add(c2); // Should not be added
            Assert.Equal(1, cc.Count);
        }

        [Fact]
        public void Add_ReachedMaxCount_NotAdded()
        {
            CookieContainer cc = new CookieContainer(4);
            for (int i = 1; i <= 4; i++)
            {
                cc.Add(new Cookie("name" + i.ToString(), "value", "", ".domain.com"));
            }

            Assert.Equal(4, cc.Count);
            cc.Add(new Cookie("name5", "value", "", ".domain.com"));
            Assert.Equal(4, cc.Count);
        }

        [Fact]
        public async Task Add_ReachedMaxCountWithExpiredCookies_Added()
        {
            Cookie c1 = new Cookie("name1", "value", "", ".domain1.com");
            Cookie c2 = new Cookie("name2", "value", "", ".domain2.com");
            Cookie c3 = new Cookie("name3", "value", "", ".domain3.com");
            c1.Expires = DateTime.Now.AddSeconds(1); // The cookie will expire in 1 second

            CookieContainer cc = new CookieContainer(2);
            cc.Add(c1);
            cc.Add(c2);

            await Task.Delay(2000); // Sleep for 2 seconds to wait for the cookie to expire
            cc.Add(c3);
            Assert.Equal(0, cc.GetCookies(new Uri("http://domain1.com")).Count);
            Assert.Equal(c3, cc.GetCookies(new Uri("http://domain3.com"))[0]);
        }

        [Fact]
        public void Add_SameCookieDifferentVairants_OverridesOlderVariant()
        {
            Uri uri = new Uri("http://domain.com");

            Cookie c1 = new Cookie("name1", "value", "", ".domain.com"); // Variant = Plain
            Cookie c2 = new Cookie("name1", "value", "", ".domain.com") { Port = "\"80\"" }; // Variant = RFC2965 (should override)
            Cookie c3 = new Cookie("name1", "value", "", ".domain.com") { Port = "\"80, 90\"" }; // Variant = RFC2965 (should override)
            Cookie c4 = new Cookie("name1", "value", "", ".domain.com") { Version = 1 }; // Variant = RFC2109 (should be rejected)

            CookieContainer cc = new CookieContainer();
            cc.Add(c1);

            // Adding a newer variant should override an older one
            cc.Add(c2);
            Assert.Equal(c2.Port, cc.GetCookies(uri)[0].Port);

            // Adding the same variant should override the existing one
            cc.Add(c3);
            Assert.Equal(c3.Port, cc.GetCookies(uri)[0].Port);

            // Adding an older variant should be rejected
            cc.Add(c4);
            Assert.Equal(c3.Port, cc.GetCookies(uri)[0].Port);

            // Ensure that although we added 3 cookies, only 1 was actually added (the others were overridden or rejected)
            Assert.Equal(1, cc.Count);
        }

        [Fact]
        public void Add_Cookie_Invalid()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Throws<ArgumentNullException>(() => cc.Add((Cookie)null)); // Null cookie
            AssertExtensions.Throws<ArgumentException>("cookie.Domain", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain

            cc.MaxCookieSize = 1;
            Assert.Throws<CookieException>(() => cc.Add(new Cookie("name", "long-text", "", "contoso.com"))); // Value.Length > MaxCookieSize
        }

        [Fact]
        public void Capacity_ShrinkNoneExpired_RemovesAll()
        {
            Cookie c1 = new Cookie("name1", "value", "", ".url1.com");
            Cookie c2 = new Cookie("name2", "value", "", ".url2.com");
            Cookie c3 = new Cookie("name3", "value", "", ".url3.com");
            Cookie c4 = new Cookie("name4", "value", "", ".url4.com");

            CookieContainer cc = new CookieContainer() { PerDomainCapacity = 1 };
            cc.Add(c1);
            cc.Add(c2);
            cc.Add(c3);
            cc.Add(c4);

            // Shrink to a number less than the current count - since we have no cookies that have expired,
            // we should just clear the whole thing except for a single cookie
            cc.Capacity = 2;
            Assert.Equal(2, cc.Capacity);
            Assert.Equal(0, cc.Count);
        }

        [Fact]
        public void Ctor_CapacityPerDomainCapacityMaxCookieSize_Invalid()
        {
            AssertExtensions.Throws<ArgumentException>("Capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0
            Assert.Throws<ArgumentOutOfRangeException>(() => new CookieContainer(5, 0, 5)); // Per domain capacity <= 0
            Assert.Throws<ArgumentOutOfRangeException>(() => new CookieContainer(5, 10, 5)); // Per domain capacity > Capacity

            AssertExtensions.Throws<ArgumentException>("MaxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0
        }

        [Fact]
        public void GetCookies_DifferentPaths_GetsMatchedPathsIncludingEmptyPath()
        {
            // Internally, paths are stored alphabetically sorted - so expect a cookie collection sorted by the path of each cookie
            // This test ensures that all cookies with paths (that the path specified by the uri starts with) are returned
            Cookie c1 = new Cookie("name1", "value", "/aa", ".url.com");
            Cookie c2 = new Cookie("name2", "value", "/a", ".url.com");
            Cookie c3 = new Cookie("name3", "value", "/b", ".url.com"); // Should be ignored - no match with the URL's path
            Cookie c4 = new Cookie("name4", "value", "/", ".url.com"); // Should NOT be ignored (has no path specified)

            CookieContainer cc1 = new CookieContainer();
            cc1.Add(c1);
            cc1.Add(c2);
            cc1.Add(c3);
            cc1.Add(c4);

            CookieCollection cc2 = cc1.GetCookies(new Uri("http://url.com/aaa"));
            Assert.Equal(3, cc2.Count);
            Assert.Equal(c1, cc2[0]);
            Assert.Equal(c2, cc2[1]);
            Assert.Equal(c4, cc2[2]);
        }

        [Fact]
        public async Task GetCookies_RemovesExpired_Cookies()
        {
            Cookie c1 = new Cookie("name1", "value", "", ".url1.com");
            Cookie c2 = new Cookie("name2", "value", "", ".url2.com");
            c1.Expires = DateTime.Now.AddSeconds(1); // The cookie will expire in 1 second

            CookieContainer cc = new CookieContainer();
            cc.Add(c1);
            cc.Add(c2);

            await Task.Delay(2000); // Sleep for 2 seconds to wait for the cookie to expire
            Assert.Equal(0, cc.GetCookies(new Uri("http://url1.com")).Count); // There should no longer be such a cookie
        }

        public static IEnumerable<object[]> InvalidCookies()
        {
            const string DefaultName = "name";
            const string DefaultValue = "value";
            const string DefaultPath = "path";
            const string DefaultDomain = ".domain.com";

            yield return new[] { new Cookie(DefaultName, null, DefaultPath, DefaultDomain) }; // Null value
            yield return new[] { new Cookie(DefaultName, ";", DefaultPath, DefaultDomain) }; // Value contains reserved characters
            yield return new[] { new Cookie(DefaultName, DefaultValue, "\"/a", DefaultDomain) }; // Semi escaped path

            yield return new[] { new Cookie(DefaultName, DefaultValue, ";", DefaultDomain) }; // Path contains reserved characters

            yield return new[] { new Cookie(DefaultName, DefaultValue, DefaultPath, " ") }; // Invalid domain
            yield return new[] { new Cookie(DefaultName, DefaultValue, DefaultPath, "П.com") }; // Invalid domain

            yield return new[] { new Cookie(DefaultName, DefaultValue, DefaultPath, "domain") }; // Plain cookie, explicit domain without version doesn't start with '.'
            yield return new[] { new Cookie(DefaultName, DefaultValue, DefaultPath, "domain") { Version = 100 } }; // Rfc2965 cookie, explicit domain with version doesn't start with '.'

            yield return new[] { new Cookie(DefaultName, DefaultValue, DefaultPath, DefaultDomain) { Comment = ";" } }; // Comment contains reserved characters
        }

        [Theory]
        [MemberData(nameof(InvalidCookies))]
        public void Add_VerificationFailedCookie_Throws(Cookie c)
        {
            CookieContainer cc = new CookieContainer();
            Assert.Throws<CookieException>(() => cc.Add(c));
        }

        [Fact]
        public void Add_NullCookieCollection_Throws()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Throws<ArgumentNullException>(() => cc.Add((CookieCollection)null)); // Null cookie
        }

        public static IEnumerable<object[]> GetCookiesData()
        {
            yield return new object[] { new Uri("http://url1.com"), new Cookie[] { c1, c3 } };
            yield return new object[] { new Uri("https://url1.com"), new Cookie[] { c1, c2, c3 } };
            yield return new object[] { new Uri("http://127.0.0.1"), new Cookie[] { c4 } };
            yield return new object[] { new Uri("http://127.0.0.1/path"), new Cookie[] { c5, c4 } };
            yield return new object[] { new Uri("http://url3.com"), new Cookie[] { c6, c7 } };
            yield return new object[] { u4, new Cookie[] { c8, c9 } };
            yield return new object[] { u5, new Cookie[] { c10, c11 } };
            yield return new object[] { u6, new Cookie[0] };
        }

        [Theory]
        [MemberData(nameof(GetCookiesData))]
        public void GetCookies_Success(Uri uri, Cookie[] expected)
        {
            CookieContainer cc = CreateCount11Container();
            VerifyGetCookies(cc, uri, expected);
        }

        private void VerifyGetCookies(CookieContainer cc1, Uri uri, Cookie[] expected)
        {
            CookieCollection cc2 = cc1.GetCookies(uri);
            Assert.Equal(expected.Length, cc2.Count);

            for (int i = 0; i < expected.Length; i++)
            {
                Cookie c1 = expected[i];
                Cookie c2 = cc2[i];
                Assert.Equal(c1.Name, c2.Name); // Primitive check for equality
                Assert.Equal(c1.Value, c2.Value);
            }
        }
    }
}


text:
<?php include('connectdb.php') ?>
<?php
	// prepare and bind
	$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

	$query = "INSERT INTO genre (genre_name) VALUES
	('" . $_POST['genre_name'] . "')";
	if ($conn->query($query) === TRUE) {
	header('Location: http://web.engr.oregonstate.edu/~johnsma8/irlibrary');
	die();
	} else {
	echo "Error: " . $query . "<br>" . $conn->error;
	}

?>

redpajama_set_name: RedPajamaGithub


text:
require 'integration_spec_helper'

describe 'File integrity' do

  if account?

    before(:all) do
      @storage = login
    end

    context "when a file is renamed" do

      let(:path) { "#{temp_folder}/testfile_#{SecureRandom.hex(6)}" }

      let(:new_name) { "testfile_#{SecureRandom.hex(6)}" }

      it 'it does not get corrupted' do
        File.write(path, SecureRandom.hex(24))
        file = @storage.root.upload(path)
        file.rename(new_name)
        expect(file.name).to eq(new_name)
        file = @storage.nodes.find { |n| n.handle == file.handle }
        file.delete
        expect(file.name).to eq(new_name)
      end
    end

    [12, 6_000].each do |size|

      context "when a file (#{size} bytes) is uploaded and then downloaded" do

        let(:path) { "#{temp_folder}/testfile_#{SecureRandom.hex(6)}" }

        let(:content) { SecureRandom.random_bytes(size) }

        let(:content_hash) { Digest::MD5.hexdigest(content) }

        it 'it does not get corrupted' do
          File.write(path, content)
          file = @storage.root.upload(path)
          file.download("#{path}.downloaded")
          file.delete
          expect(Digest::MD5.file("#{path}.downloaded").hexdigest).to eq(content_hash)
        end
      end
    end
  end
end


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

# include "replication_common.h"
# include "replica_stub.h"

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "replica.service_app"

namespace dsn { namespace replication {

replication_service_app::replication_service_app()
    : service_app()
{
    _stub = new replica_stub();
}

replication_service_app::~replication_service_app(void)
{
}

error_code replication_service_app::start(int argc, char** argv)
{
    replication_options opts;
    opts.initialize();

    _stub->initialize(opts);
    _stub->open_service();

    return ERR_OK;
}

void replication_service_app::stop(bool cleanup)
{
    if (_stub != nullptr)
    {
        _stub->close();
        _stub = nullptr;
    }
}

}}


text:
require 'spec_helper'

describe Magic::AccountsController do

end


text:
namespace boost {

namespace units {

/// Check that a type is a quantity of the specified dimension.
template<class T,class Dim>
struct is_quantity_of_dimension :
    public mpl::false_
{ };

template<class Unit,class Y,class Dim>
struct is_quantity_of_dimension< quantity< Unit,Y>,Dim > :
    public is_unit_of_dimension<Unit, Dim>
{ };

} // namespace units

} // namespace boost

#endif // BOOST_UNITS_IS_QUANTITY_OF_DIMENSION_HPP


text:
module Facts
  module Solaris
    module Dmi
      class Manufacturer
        FACT_NAME = 'dmi.manufacturer'
        ALIASES = 'manufacturer'

        def call_the_resolver
          fact_value = if isa == 'i386'
                         Facter::Resolvers::Solaris::Dmi.resolve(:manufacturer)
                       elsif isa == 'sparc'
                         Facter::Resolvers::Solaris::DmiSparc.resolve(:manufacturer)
                       end
          [Facter::ResolvedFact.new(FACT_NAME, fact_value), Facter::ResolvedFact.new(ALIASES, fact_value, :legacy)]
        end

        def isa
          Facter::Resolvers::Uname.resolve(:processor)
        end
      end
    end
  end
end


text:
package org.jgroups.protocols.raft;

import org.jgroups.Header;

import java.util.function.Supplier;

/**
 * @author Bela Ban
 * @since  0.1
 */
public class VoteRequest extends RaftHeader {

    public VoteRequest() {}
    public VoteRequest(long term) {
        super(term);
    }

    public short getMagicId() {
        return ELECTION.VOTE_REQ;
    }

    public Supplier<? extends Header> create() {
        return VoteRequest::new;
    }

}


text:
//
// Copyright 2020 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//

using System.Diagnostics;

namespace Google.Solutions.Ssh
{
    public static class SshTraceSources
    {
        public static readonly TraceSource Default = new TraceSource(typeof(SshTraceSources).Namespace);
    }
}


text:
package com.facebook.litho.dataflow;

import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import com.facebook.litho.choreographercompat.ChoreographerCompat.FrameCallback;
import com.facebook.litho.testing.testrunner.LithoTestRunner;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.annotation.LooperMode;

@LooperMode(LooperMode.Mode.LEGACY)
@RunWith(LithoTestRunner.class)
public class MockTimingSourceTest {

  private MockTimingSource mTimingSource;

  @Before
  public void setUp() {
    mTimingSource = new MockTimingSource();
    DataFlowGraph.create(mTimingSource);
    mTimingSource.start();
  }

  @Test
  public void testPostFrameCallback() {
    ArrayList<FrameCallback> callbacks = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
      FrameCallback callback = mock(FrameCallback.class);
      callbacks.add(callback);
      mTimingSource.postFrameCallback(callback);
    }

    mTimingSource.step(1);

    for (int i = 0; i < callbacks.size(); i++) {
      Mockito.verify(callbacks.get(i)).doFrame(anyLong());
    }
  }

  @Test
  public void testPostFrameCallbackDelayed() {
    FrameCallback callback1 = mock(FrameCallback.class);
    FrameCallback callback2 = mock(FrameCallback.class);
    FrameCallback delayedCallback = mock(FrameCallback.class);

    mTimingSource.postFrameCallback(callback1);
    mTimingSource.postFrameCallbackDelayed(delayedCallback, 20);
    mTimingSource.postFrameCallback(callback2);

    mTimingSource.step(1);

    verify(callback1).doFrame(anyLong());
    verify(callback2).doFrame(anyLong());
    verify(delayedCallback, never()).doFrame(anyLong());

    mTimingSource.step(1);

    verify(delayedCallback).doFrame(anyLong());
  }

  @Test
  public void testNestedFrameCallbacks() {
    FrameCallback callback =
        new FrameCallback() {
          @Override
          public void doFrame(long frameTimeNanos) {
            mTimingSource.postFrameCallback(
                new FrameCallback() {
                  @Override
                  public void doFrame(long frameTimeNanos) {
                    fail("Nested FrameCallback should not be called in the same step");
                  }
                });
          }
        };

    mTimingSource.postFrameCallback(callback);

    mTimingSource.step(1);
  }
}


text:
package org.jclouds.dynect.v3.parse;

import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;

import org.jclouds.dynect.v3.domain.Job;
import org.jclouds.dynect.v3.internal.BaseDynECTParseTest;
import org.testng.annotations.Test;

@Test(groups = "unit")
public class DeleteZoneChangesResponseTest extends BaseDynECTParseTest<Job> {

   @Override
   public String resource() {
      return "/delete_zone_changes.json";
   }

   @Override
   @Consumes(MediaType.APPLICATION_JSON)
   public Job expected() {
      return Job.success(275625520l);
   }
}


text:
<form role="search" method="get" id="searchform" class="searchform" action="/">

        Pesquisar por:
        <input type="text" value="" name="s" id="s">
        <input type="submit" id="searchsubmit" value="">

</form>


text:
package org.apache.nifi.controller.repository;

import org.apache.nifi.controller.queue.FlowFileQueue;
import org.apache.nifi.controller.repository.claim.StandardResourceClaimManager;
import org.apache.nifi.controller.repository.schema.RepositoryRecordSchema;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.nifi.controller.repository.RepositoryRecordType.SWAP_IN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class SchemaRepositoryRecordSerdeTest {
    public static final String TEST_QUEUE_IDENTIFIER = "testQueueIdentifier";
    private StandardResourceClaimManager resourceClaimManager;
    private SchemaRepositoryRecordSerde schemaRepositoryRecordSerde;
    private Map<String, FlowFileQueue> queueMap;
    private FlowFileQueue flowFileQueue;
    private ByteArrayOutputStream byteArrayOutputStream;
    private DataOutputStream dataOutputStream;

    @Before
    public void setup() {
        resourceClaimManager = new StandardResourceClaimManager();
        schemaRepositoryRecordSerde = new SchemaRepositoryRecordSerde(resourceClaimManager);
        queueMap = new HashMap<>();
        schemaRepositoryRecordSerde.setQueueMap(queueMap);
        flowFileQueue = createMockQueue(TEST_QUEUE_IDENTIFIER);
        byteArrayOutputStream = new ByteArrayOutputStream();
        dataOutputStream = new DataOutputStream(byteArrayOutputStream);
    }

    @After
    public void teardown() {
        resourceClaimManager.purge();
    }

    @Test
    public void testV1CreateCantHandleLongAttributeName() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put(stringBuilder.toString(), "testValue");
        schemaRepositoryRecordSerde.serializeRecord(createCreateFlowFileRecord(attributes), dataOutputStream,
                RepositoryRecordSchema.CREATE_OR_UPDATE_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertNotEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV1CreateCantHandleLongAttributeValue() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put("testName", stringBuilder.toString());
        schemaRepositoryRecordSerde.serializeRecord(createCreateFlowFileRecord(attributes), dataOutputStream,
                RepositoryRecordSchema.CREATE_OR_UPDATE_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertNotEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV2CreateCanHandleLongAttributeName() throws IOException {
        schemaRepositoryRecordSerde.writeHeader(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put(stringBuilder.toString(), "testValue");
        schemaRepositoryRecordSerde.serializeRecord(createCreateFlowFileRecord(attributes), dataOutputStream);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV2CreateCanHandleLongAttributeValue() throws IOException {
        schemaRepositoryRecordSerde.writeHeader(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put("testName", stringBuilder.toString());
        schemaRepositoryRecordSerde.serializeRecord(createCreateFlowFileRecord(attributes), dataOutputStream);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testRoundTripCreateV1ToV2() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        attributes.put("testName", "testValue");
        schemaRepositoryRecordSerde.serializeRecord(createCreateFlowFileRecord(attributes), dataOutputStream,
                RepositoryRecordSchema.CREATE_OR_UPDATE_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV1SwapInCantHandleLongAttributeName() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put(stringBuilder.toString(), "testValue");
        StandardRepositoryRecord record = createCreateFlowFileRecord(attributes);
        record.setSwapLocation("fake");
        assertEquals(SWAP_IN, record.getType());
        schemaRepositoryRecordSerde.serializeRecord(record, dataOutputStream, RepositoryRecordSchema.SWAP_IN_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertNotEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV1SwapInCantHandleLongAttributeValue() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put("testName", stringBuilder.toString());
        StandardRepositoryRecord record = createCreateFlowFileRecord(attributes);
        record.setSwapLocation("fake");
        assertEquals(SWAP_IN, record.getType());
        schemaRepositoryRecordSerde.serializeRecord(record, dataOutputStream, RepositoryRecordSchema.SWAP_IN_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertNotEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV2SwapInCanHandleLongAttributeName() throws IOException {
        schemaRepositoryRecordSerde.writeHeader(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put(stringBuilder.toString(), "testValue");
        StandardRepositoryRecord record = createCreateFlowFileRecord(attributes);
        record.setSwapLocation("fake");
        assertEquals(SWAP_IN, record.getType());
        schemaRepositoryRecordSerde.serializeRecord(record, dataOutputStream);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testV2SwapInCanHandleLongAttributeValue() throws IOException {
        schemaRepositoryRecordSerde.writeHeader(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 65536; i++) {
            stringBuilder.append('a');
        }
        attributes.put("testName", stringBuilder.toString());
        StandardRepositoryRecord record = createCreateFlowFileRecord(attributes);
        record.setSwapLocation("fake");
        assertEquals(SWAP_IN, record.getType());
        schemaRepositoryRecordSerde.serializeRecord(record, dataOutputStream);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
    }

    @Test
    public void testRoundTripSwapInV1ToV2() throws IOException {
        RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1.writeTo(dataOutputStream);
        Map<String, String> attributes = new HashMap<>();
        attributes.put("testName", "testValue");
        StandardRepositoryRecord record = createCreateFlowFileRecord(attributes);
        record.setSwapLocation("fake");
        assertEquals(SWAP_IN, record.getType());
        schemaRepositoryRecordSerde.serializeRecord(record, dataOutputStream, RepositoryRecordSchema.SWAP_IN_SCHEMA_V1, RepositoryRecordSchema.REPOSITORY_RECORD_SCHEMA_V1);

        DataInputStream dataInputStream = createDataInputStream();
        schemaRepositoryRecordSerde.readHeader(dataInputStream);
        RepositoryRecord repositoryRecord = schemaRepositoryRecordSerde.deserializeRecord(dataInputStream, 2);
        assertEquals(attributes, repositoryRecord.getCurrent().getAttributes());
        assertEquals(SWAP_IN, repositoryRecord.getType());
    }

    private DataInputStream createDataInputStream() throws IOException {
        dataOutputStream.flush();
        return new DataInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    }

    private StandardRepositoryRecord createCreateFlowFileRecord(Map<String, String> attributes) {
        StandardRepositoryRecord standardRepositoryRecord = new StandardRepositoryRecord(flowFileQueue);
        StandardFlowFileRecord.Builder flowFileRecordBuilder = new StandardFlowFileRecord.Builder();
        flowFileRecordBuilder.addAttributes(attributes);
        standardRepositoryRecord.setWorking(flowFileRecordBuilder.build());
        return standardRepositoryRecord;
    }

    private FlowFileQueue createMockQueue(String identifier) {
        FlowFileQueue flowFileQueue = mock(FlowFileQueue.class);
        when(flowFileQueue.getIdentifier()).thenReturn(identifier);
        queueMap.put(identifier, flowFileQueue);
        return flowFileQueue;
    }
}


text:
import { Readable } from 'stream';
import { StreamMessage } from '../core/Messages';

/**
 * Simple stream that pipes through a supplied set of stream messages when the `send` method is called.
 */
export class StaticCommandSet extends Readable {
    messages: StreamMessage[];

    constructor(messages: StreamMessage[]) {
        super({ objectMode: true });
        this.messages = messages;
    }

    send() {
        this.messages.forEach((msg: StreamMessage) => {
            this.push(msg);
        });
        this.messages = [];
        this.push(null);
    }

    sendOne() {
        const message: StreamMessage = this.messages.shift();
        if (message) {
            this.push(message);
        }
        if (this.messages.length === 0) {
            this.push(null);
        }
    }

    _read(size: number): void { /* no-op */ }
}


text:
/*
 * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    /// <summary>
    ///
    /// </summary>
    public partial class DescribeVpcsResult : AmazonWebServiceResponse
    {
        private List<Vpc> _vpcs = new List<Vpc>();

        /// <summary>
        /// Gets and sets the property Vpcs.
        /// <para>
        /// Information about one or more VPCs.
        /// </para>
        /// </summary>
        public List<Vpc> Vpcs
        {
            get { return this._vpcs; }
            set { this._vpcs = value; }
        }

        // Check to see if Vpcs property is set
        internal bool IsSetVpcs()
        {
            return this._vpcs != null && this._vpcs.Count > 0;
        }

    }
}


text:
using System.ComponentModel.DataAnnotations;

namespace GestionFacturas.Dominio;

public class SelectorColumnasExcelFactura
{
    public SelectorColumnasExcelFactura()
    {

    }

    public string IdUsuario { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Serie")]
    public string SerieFactura { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Nº Factura")]
    [StringLength(1)]
    public string NumeroFactura { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Formato")]
    [StringLength(50)]
    public string FormatoNumeroFactura { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Fecha emisión")]
    public string FechaEmisionFactura { get; set; } = string.Empty;

    [Display(Name = "Fecha vencimiento")]
    public string FechaVencimientoFactura { get; set; } = string.Empty;

    [Display(Name = "Forma de pago")]
    public string FormaPago { get; set; } = string.Empty;

    [Display(Name = "Detalles forma pago")]
    [StringLength(50)]
    public string FormaPagoDetalles { get; set; } = string.Empty;

    [Display(Name = "Número de referencia")]
    public string IdVendedor { get; set; } = string.Empty;

    [Display(Name = "Identificación fiscal")]
    [StringLength(50)]
    public string VendedorNumeroIdentificacionFiscal { get; set; } = string.Empty;

    [Display(Name = "Nombre o empresa")]
    [StringLength(50)]
    public string VendedorNombreOEmpresa { get; set; } = string.Empty;

    [Display(Name = "Dirección")]
    [StringLength(50)]
    public string VendedorDireccion { get; set; } = string.Empty;

    [Display(Name = "Municipio")]
    [StringLength(50)]
    public string VendedorLocalidad { get; set; } = string.Empty;

    [Display(Name = "Provincia")]
    [StringLength(50)]
    public string VendedorProvincia { get; set; } = string.Empty;

    [Display(Name = "Código postal")]
    [StringLength(10)]
    public string VendedorCodigoPostal { get; set; } = string.Empty;

    [Display(Name = "E-mail")]
    [StringLength(50)]
    public string VendedorEmail { get; set; } = string.Empty;

    [Display(Name = "Número de referencia")]
    public string IdComprador { get; set; } = string.Empty;

    [Display(Name = "Identificación fiscal")]
    [StringLength(50)]
    public string CompradorNumeroIdentificacionFiscal { get; set; } = string.Empty;

    [Display(Name = "Nombre o empresa")]
    [StringLength(50)]
    public string CompradorNombreOEmpresa { get; set; } = string.Empty;

    [Display(Name = "Dirección")]
    [StringLength(50)]
    public string CompradorDireccion { get; set; } = string.Empty;

    [Display(Name = "Municipio")]
    [StringLength(50)]
    public string CompradorLocalidad { get; set; } = string.Empty;

    [Display(Name = "Provincia")]
    [StringLength(50)]
    public string CompradorProvincia { get; set; } = string.Empty;

    [Display(Name = "Código postal")]
    [StringLength(10)]
    public string CompradorCodigoPostal { get; set; } = string.Empty;

    [Display(Name = "E-mail")]
    [StringLength(50)]
    public string CompradorEmail { get; set; } = string.Empty;

    [Display(Name = "Estado")]
    public string EstadoFactura { get; set; } = string.Empty;

    [StringLength(250)]
    public string Comentarios { get; set; } = string.Empty;

    [Display(Name = "Pie")]
    [StringLength(800)]
    public string ComentariosPie { get; set; } = string.Empty;

    [Display(Name = "Nota interna")]
    [StringLength(250)]
    public string ComentarioInterno { get; set; } = string.Empty;

    [Required]
    [StringLength(1)]
    [Display(Name = "Concepto")]
    public string Descripcion { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Cantidad")]
    public string Cantidad { get; set; } = string.Empty;

    [Required]
    [Display(Name = "Precio unitario")]
    [StringLength(1)]
    public string PrecioUnitario { get; set; } = string.Empty;

    [Required]
    [Display(Name = "% IVA")]
    public string PorcentajeImpuesto { get; set; } = string.Empty;
}


text:
require 'spec_helper'

describe FSEvent do

  before(:each) do
    @results = []
    @fsevent = FSEvent.new
    @fsevent.watch @fixture_path.to_s, {:latency => 0.5} do |paths|
      @results += paths
    end
  end

  it "shouldn't pass anything to watch when instantiated without a path" do
    fsevent = FSEvent.new
    fsevent.paths.should be_nil
    fsevent.callback.should be_nil
  end

  it "should pass path and block to watch when instantiated with them" do
    blk = proc { }
    fsevent = FSEvent.new(@fixture_path, &blk)
    fsevent.paths.should == [@fixture_path]
    fsevent.callback.should == blk
  end

  it "should have a watcher_path that resolves to an executable file" do
    File.exists?(FSEvent.watcher_path).should be_true
    File.executable?(FSEvent.watcher_path).should be_true
  end

  it "should work with path with an apostrophe" do
    custom_path = @fixture_path.join("custom 'path")
    file = custom_path.join("newfile.rb").to_s
    File.delete file if File.exists? file
    @fsevent.watch custom_path.to_s do |paths|
      @results += paths
    end
    @fsevent.paths.should == ["#{custom_path}"]
    run
    FileUtils.touch file
    stop
    File.delete file
    @results.should == [custom_path.to_s + '/']
  end

  it "should catch new file" do
    file = @fixture_path.join("newfile.rb")
    File.delete file if File.exists? file
    run
    FileUtils.touch file
    stop
    File.delete file
    @results.should == [@fixture_path.to_s + '/']
  end

  it "should catch file update" do
    file = @fixture_path.join("folder1/file1.txt")
    File.exists?(file).should be_true
    run
    FileUtils.touch file
    stop
    @results.should == [@fixture_path.join("folder1/").to_s]
  end

  it "should catch files update" do
    file1 = @fixture_path.join("folder1/file1.txt")
    file2 = @fixture_path.join("folder1/folder2/file2.txt")
    File.exists?(file1).should be_true
    File.exists?(file2).should be_true
    run
    FileUtils.touch file1
    FileUtils.touch file2
    stop
    @results.should == [@fixture_path.join("folder1/").to_s, @fixture_path.join("folder1/folder2/").to_s]
  end

  def run
    sleep 1
    Thread.new { @fsevent.run }
    sleep 1
  end

  def stop
    sleep 1
    @fsevent.stop
  end

end


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

/**
 * The HOC component to require jwt
 * @type {function(ComposedComponent) }
 */
export default function (ComposedComponent) { //hire order component const Composedcomponent = Authentication(ResourcesComponent)  <ComposedComponent />

    class Authentication extends Component {
        // check if user authenticated if not push to /
        componentWillMount() {
            if (!this.props.authenticated)
                this.context.router.push('/');
        }

        componentWillUpdate(nextProps) {
            if (!nextProps.authenticated)
                this.context.router.push('/');
        }

        render() {
            return <ComposedComponent {...this.props} />;
        }
    }

    Authentication.contextTypes = { // class level property(static) //static contextTypes = { // class level property(static)
        router: React.PropTypes.object
    };
    //how to replace it this.context not stable api?
    // for getting access in this.context

    const mapStateToProps = (state) => {
        return {
            authenticated: state.authentication.authenticated
        };
    };

    return connect(mapStateToProps)(Authentication);
}


text:
<#
.SYNOPSIS
Tests DataLakeStore Account Lifecycle (Create, Update, Get, List, Delete).
#>
function Test-DataLakeStoreAccount
{
    param
	(
		$location = "West US"
	)

	try
	{
		# Creating Account
		$resourceGroupName = Get-ResourceGroupName
		$accountName = Get-DataLakeStoreAccountName
		New-AzureRmResourceGroup -Name $resourceGroupName -Location $location

		# Test to make sure the account doesn't exist
		Assert-False {Test-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
		# Test it without specifying a resource group
		Assert-False {Test-AdlStore -Name $accountName}

		$accountCreated = New-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Location $location

		Assert-AreEqual $accountName $accountCreated.Name
		Assert-AreEqual $location $accountCreated.Location
		Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
		Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}

		# In loop to check if account exists
		for ($i = 0; $i -le 60; $i++)
		{
			[array]$accountGet = Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName
			if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
			{
				Assert-AreEqual $accountName $accountGet[0].Name
				Assert-AreEqual $location $accountGet[0].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
				Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
				break
			}

			Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
			[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
			Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
		}

		# Test to make sure the account does exist
		Assert-True {Test-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
		# Test it without specifying a resource group
		Assert-True {Test-AdlStore -Name $accountName}

		# Updating Account
		$tagsToUpdate = @{"TestTag" = "TestUpdate"}
		$accountUpdated = Set-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Tags $tagsToUpdate

		Assert-AreEqual $accountName $accountUpdated.Name
		Assert-AreEqual $location $accountUpdated.Location
		Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountUpdated.Type
		Assert-True {$accountUpdated.Id -like "*$resourceGroupName*"}

		Assert-NotNull $accountUpdated.Tags "Tags do not exists"
		Assert-NotNull $accountUpdated.Tags["TestTag"] "The updated tag 'TestTag' does not exist"

		# List all accounts in resource group
		[array]$accountsInResourceGroup = Get-AdlStore -ResourceGroupName $resourceGroupName
		Assert-True {$accountsInResourceGroup.Count -ge 1}

		$found = 0
		for ($i = 0; $i -lt $accountsInResourceGroup.Count; $i++)
		{
			if ($accountsInResourceGroup[$i].Name -eq $accountName)
			{
				$found = 1
				Assert-AreEqual $location $accountsInResourceGroup[$i].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountsInResourceGroup[$i].Type
				Assert-True {$accountsInResourceGroup[$i].Id -like "*$resourceGroupName*"}

				break
			}
		}
		Assert-True {$found -eq 1} "Account created earlier is not found when listing all in resource group: $resourceGroupName."

		# List all Data Lake accounts in subscription
		[array]$accountsInSubscription = Get-AdlStore
		Assert-True {$accountsInSubscription.Count -ge 1}
		Assert-True {$accountsInSubscription.Count -ge $accountsInResourceGroup.Count}

		$found = 0
		for ($i = 0; $i -lt $accountsInSubscription.Count; $i++)
		{
			if ($accountsInSubscription[$i].Name -eq $accountName)
			{
				$found = 1
				Assert-AreEqual $location $accountsInSubscription[$i].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountsInSubscription[$i].Type
				Assert-True {$accountsInSubscription[$i].Id -like "*$resourceGroupName*"}

				break
			}
		}
		Assert-True {$found -eq 1} "Account created earlier is not found when listing all in subscription."

		# Delete Data Lake account
		Assert-True {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."

		# Verify that it is gone by trying to get it again
		Assert-Throws {Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
	}
	finally
	{
		# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
		Invoke-HandledCmdlet -Command {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
		Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
	}
}

function Test-DataLakeStoreFileSystem
{
	param
	(
		$fileToCopy,
		$location = "West US"
	)

	try
	{
		# Creating Account
		$resourceGroupName = Get-ResourceGroupName
		$accountName = Get-DataLakeStoreAccountName
		New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
		$accountCreated = New-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Location $location

		Assert-AreEqual $accountName $accountCreated.Name
		Assert-AreEqual $location $accountCreated.Location
		Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
		Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}

		# In loop to check if account exists
		for ($i = 0; $i -le 60; $i++)
		{
			[array]$accountGet = Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName
			if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
			{
				Assert-AreEqual $accountName $accountGet[0].Name
				Assert-AreEqual $location $accountGet[0].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
				Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
				break
			}

			Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
			[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
			Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
		}

		# define all the files and folders to create
		$folderToCreate = "/adlspstestfolder"
		$emptyFilePath = "$folderToCreate\emptyfile.txt" # have one where the slash is in the wrong direction to make sure they get fixed.
		$contentFilePath = "$folderToCreate/contentfile.txt"
		$concatFile = "$folderToCreate/concatfile.txt"
		$moveFile = "$folderToCreate/movefile.txt"
		$movefolder = "/adlspstestmovefolder"
		$importFile = "$folderToCreate/importfile.txt"
		$content = "Test file content! @ Azure PsTest01?"

		# Create and get Empty folder
		$result = New-AdlStoreItem -Account $accountName -path $folderToCreate -Folder
		Assert-NotNull $result "No value was returned on folder creation"
		$result = Get-AdlStoreItem -Account $accountName -path $folderToCreate
		Assert-NotNull $result "No value was returned on folder get"
		Assert-AreEqual "Directory" $result.Type
		# Create and get Empty File
		$result = New-AdlStoreItem -Account $accountName -path $emptyFilePath
		Assert-NotNull $result "No value was returned on empty file creation"
		$result = Get-AdlStoreItem -Account $accountName -path $emptyFilePath
		Assert-NotNull $result "No value was returned on empty file get"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual 0 $result.Length
		# Create and get file with content
		$result = New-AdlStoreItem -Account $accountName -path $contentFilePath -Value $content
		Assert-NotNull $result "No value was returned on content file creation"
		$result = Get-AdlStoreItem -Account $accountName -path $contentFilePath
		Assert-NotNull $result "No value was returned on content file get"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual $content.length $result.Length
		# list files
		$result = Get-AdlStoreChildItem -Account $accountName -path $folderToCreate
		Assert-NotNull $result "No value was returned on folder list"
		Assert-AreEqual 2 $result.length
		# add content to empty file
		Add-AdlStoreItemContent -Account $accountName -Path $emptyFilePath -Value $content
		$result = Get-AdlStoreItem -Account $accountName -path $emptyFilePath
		Assert-NotNull $result "No value was returned on empty file get with content added"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual $content.length $result.Length
		# concat files
		$result = Join-AdlStoreItem -Account $accountName -Paths $emptyFilePath,$contentFilePath -Destination $concatFile
		Assert-NotNull $result "No value was returned on concat file"
		$result = Get-AdlStoreItem -Account $accountName -path $concatFile
		Assert-NotNull $result "No value was returned on concat file get"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual $($content.length*2) $result.Length

		# Preview content from the file
		$previewContent = Get-AdlStoreItemContent -Account $accountName -Path $concatFile
		Assert-AreEqual $($content.length*2) $previewContent.Length

		# Preview a subset of the content
		$previewContent = Get-AdlStoreItemContent -Account $accountName -Path $concatFile -Offset 2
		Assert-AreEqual $(($content.length*2) - 2) $previewContent.Length

		# Preview a subset with a specific length
		$previewContent = Get-AdlStoreItemContent -Account $accountName -Path $concatFile -Offset 2 -Length $content.Length
		Assert-AreEqual $content.length $previewContent.Length

		# Import and get file
		$localFileInfo = Get-ChildItem $fileToCopy
		$result = Import-AdlStoreItem -Account $accountName -Path $fileToCopy -Destination $importFile
		Assert-NotNull $result "No value was returned on import file"
		$result = Get-AdlStoreItem -Account $accountName -path $importFile
		Assert-NotNull $result "No value was returned on import file get"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual $localFileInfo.length $result.Length
		# download file
		$currentDir = Split-Path $fileToCopy
		$targetFile = Join-Path $currentDir "adlspstestdownload.txt"
		if(Test-Path $targetFile)
		{
			Remove-Item -path $targetFile -force -confirm:$false
		}

		Export-AdlStoreItem -Account $accountName -Path $concatFile -Destination $targetFile
		$downloadedFileInfo = Get-ChildItem $targetFile
		Assert-AreEqual $($content.length*2) $downloadedFileInfo.length
		Remove-Item -path $targetFile -force -confirm:$false

		# move a file
		$result = Move-AdlStoreItem -Account $accountName -Path $concatFile -Destination $moveFile
		Assert-NotNull $result "No value was returned on move file"
		$result = Get-AdlStoreItem -Account $accountName -path $moveFile
		Assert-NotNull $result "No value was returned on move file get"
		Assert-AreEqual "File" $result.Type
		Assert-AreEqual $($content.length*2) $result.Length
		Assert-Throws {Get-AdlStoreItem -Account $accountName -path $concatFile}
		# move a folder
		$result = Move-AdlStoreItem -Account $accountName -Path $folderToCreate -Destination $moveFolder
		Assert-NotNull $result "No value was returned on move folder"
		$result = Get-AdlStoreItem -Account $accountName -path $moveFolder
		Assert-NotNull $result "No value was returned on move folder get"
		Assert-AreEqual "Directory" $result.Type
		Assert-AreEqual 0 $result.Length
		Assert-Throws {Get-AdlStoreItem -Account $accountName -path $folderToCreate}
		# delete a file
		Assert-True {Remove-AdlStoreItem -Account $accountName -paths "$moveFolder/movefile.txt" -force -passthru } "Remove File Failed"
		Assert-Throws {Get-AdlStoreItem -Account $accountName -path $moveFile}
		# delete a folder
		Assert-True {Remove-AdlStoreItem -Account $accountName -paths $moveFolder -force -recurse -passthru} "Remove folder failed"
		Assert-Throws {Get-AdlStoreItem -Account $accountName -path $moveFolder}

		# Delete Data Lake account
		Assert-True {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."

		# Verify that it is gone by trying to get it again
		Assert-Throws {Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
	}
	finally
	{
		# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
		Invoke-HandledCmdlet -Command {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
		Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
	}
}

function Test-DataLakeStoreFileSystemPermissions
{
	param
	(
		$location = "West US"
	)

	try
	{
		# Creating Account
		$resourceGroupName = Get-ResourceGroupName
		$accountName = Get-DataLakeStoreAccountName
		New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
		$accountCreated = New-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Location $location

		Assert-AreEqual $accountName $accountCreated.Name
		Assert-AreEqual $location $accountCreated.Location
		Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
		Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}

		# In loop to check if account exists
		for ($i = 0; $i -le 60; $i++)
		{
			[array]$accountGet = Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName
			if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
			{
				Assert-AreEqual $accountName $accountGet[0].Name
				Assert-AreEqual $location $accountGet[0].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
				Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
				break
			}

			Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
			[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
			Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
		}

		# define the permissions to add/remove
		$aceUserId = "027c28d5-c91d-49f0-98c5-d10134b169b3"

		# Set and get all the permissions
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-NotNull $result "Did not get any result from ACL get"
		Assert-True {$result.Count -ge 0} "UserAces is negative or null"
 		$currentCount = $result.Count
 		$result.Add("user:$aceUserId`:rwx")
 		$toRemove = $result[$result.Count -1]
		Assert-AreEqual $aceUserId $toRemove.Id

		Set-AdlStoreItemAcl -Account $accountName -path "/" -Acl $result
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $($currentCount+1) $result.Count
 		$found = $false
 		for($i = 0; $i -lt $result.Count; $i++)
 		{
 			if($result[$i].Id -like $aceUserId)
 			{
 				$found = $true
 				$result.RemoveAt($i)
 				break
 			}
 		}

 		Assert-True { $found } "Failed to remove the element: $($toRemove.Entry)"

		# remove the account
		Set-AdlStoreItemAcl -Account $accountName -path "/" -Acl $result
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $currentCount $result.Count

		# Set and get a specific permission with friendly sets
		Set-AdlStoreItemAclEntry -Account $accountName -path "/" -AceType User -Id $aceUserId -Permissions All
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $($currentCount+1) $result.Count
		# remove a specific permission with friendly remove
		Remove-AdlStoreItemAclEntry -Account $accountName -path "/" -AceType User -Id $aceUserId
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $currentCount $result.Count
		# set and get a specific permission with the ACE string
		Set-AdlStoreItemAclEntry -Account $accountName -path "/" -Acl $([string]::Format("user:{0}:rwx", $aceUserId))
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $($currentCount+1) $result.Count
		# remove a specific permission with the ACE string
		Remove-AdlStoreItemAclEntry -Account $accountName -path "/" -Acl $([string]::Format("user:{0}:---", $aceUserId))
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual $currentCount $result.Count

		# Validate full ACL removal
		Remove-AdlStoreItemAcl -Account $accountName -Path "/" -Force -Default
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual 4 $result.Count
		Remove-AdlStoreItemAcl -Account $accountName -Path "/" -Force
		$result = Get-AdlStoreItemAclEntry -Account $accountName -path "/"
		Assert-AreEqual 3 $result.Count

		# validate permissions
		$permission = Get-AdlStoreItemPermission -Account $accountName -path "/"
		Assert-AreEqual 770 $permission
		Set-AdlStoreItemPermission -Account $accountName -path "/" -Permission 777 | Out-Null
		$permission = Get-AdlStoreItemPermission -Account $accountName -path "/"
		Assert-AreEqual 777 $permission

		# Delete Data Lake account
		Assert-True {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."

		# Verify that it is gone by trying to get it again
		Assert-Throws {Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
	}
	finally
	{
		# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
		Invoke-HandledCmdlet -Command {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
		Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
	}
}

<#
.SYNOPSIS
Tests DataLakeStore Account Lifecycle Failure scenarios (Create, Update, Get, Delete).
#>
function Test-NegativeDataLakeStoreAccount
{
    param
	(
		$location = "West US",
		$fakeaccountName = "psfakedataLakeaccounttest"
	)

	try
	{
		# Creating Account
		$resourceGroupName = Get-ResourceGroupName
		$accountName = Get-DataLakeStoreAccountName
		New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
		$accountCreated = New-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Location $location

		Assert-AreEqual $accountName $accountCreated.Name
		Assert-AreEqual $location $accountCreated.Location
		Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
		Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}

		# In loop to check if account exists
		for ($i = 0; $i -le 60; $i++)
		{

			[array]$accountGet = Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName
			if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
			{
				Assert-AreEqual $accountName $accountGet[0].Name
				Assert-AreEqual $location $accountGet[0].Location
				Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
				Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
				break
			}

			Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
			[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
			Assert-False {$i -eq 60} " Data Lake Store account not in succeeded state even after 30 min."
		}

		# attempt to recreate the already created account
		Assert-Throws {New-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Location $location}

		# attempt to update a non-existent account
		$tagsToUpdate = @{"TestTag" = "TestUpdate"}
		Assert-Throws {Set-AdlStore -ResourceGroupName $resourceGroupName -Name $fakeaccountName -Tags $tagsToUpdate}

		# attempt to get a non-existent account
		Assert-Throws {Get-AdlStore -ResourceGroupName $resourceGroupName -Name $fakeaccountName}

		# Delete Data Lake account
		Assert-True {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."

		# Delete Data Lake account again should throw.
		Assert-Throws {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru}

		# Verify that it is gone by trying to get it again
		Assert-Throws {Get-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName}
	}
	finally
	{
		# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
		Invoke-HandledCmdlet -Command {Remove-AdlStore -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
		Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
	}
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>

#include "trousers/tss.h"
#include "trousers_types.h"
#include "trousers_types.h"
#include "tcs_tsp.h"
#include "tcs_utils.h"
#include "tcs_int_literals.h"
#include "capabilities.h"
#include "tcsps.h"
#include "tcslog.h"

void
UnloadBlob_COUNTER_VALUE(UINT64 *offset, BYTE *blob, TPM_COUNTER_VALUE *ctr)
{
	if (!ctr) {
		UnloadBlob_UINT16(offset, NULL, blob);
		UnloadBlob(offset, 4, blob, NULL);
		UnloadBlob_UINT32(offset, NULL, blob);
		return;
	}

	UnloadBlob_UINT16(offset, &ctr->tag, blob);
	UnloadBlob(offset, 4, blob, (BYTE *)&ctr->label);
	UnloadBlob_UINT32(offset, &ctr->counter, blob);
}

void
LoadBlob_COUNTER_VALUE(UINT64 *offset, BYTE *blob, TPM_COUNTER_VALUE *ctr)
{
	LoadBlob_UINT16(offset, ctr->tag, blob);
	LoadBlob(offset, 4, blob, (BYTE *)&ctr->label);
	LoadBlob_UINT32(offset, ctr->counter, blob);
}


text:
#import <Foundation/Foundation.h>

//! Project version number for RxLifxApi.
FOUNDATION_EXPORT double RxLifxApiVersionNumber;

//! Project version string for RxLifxApi.
FOUNDATION_EXPORT const unsigned char RxLifxApiVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <RxLifxApi/PublicHeader.h>


text:
CHANGES
=======

Please start with the most recent changes and add your initials.

2020-05-04 (AF)
- added template/PAM50_small_label_discPosterior.nii.gz

2019-10-31 (CG)
- correct template/template/info_label.txt IDs

2016-11-22
- updated info_label

2016-10-05
- added t2s


text:
using System;
using System.Linq;
using Genesis.Net.Common;
using Genesis.Net.Entities;
using Genesis.Net.Validations;

namespace Genesis.Net.Specs.Validation
{
    class describe_month_validation : describe_entity_property_validation
    {
        public describe_month_validation(Entity entity, string monthPropertyName)
            : base(entity, monthPropertyName) { }

        public void it_should_report_invalid_month_on_validation()
        {
            propertyInfo.SetValue(entity, Constants.MinMonthValue - 1);

            var expectedErrorsCount = 1;
            var expectedMemberNames = new string[] { propertyName };
            var expectedErrorMessages = new string[] { ValidationMessages.MonthOutOfRange(propertyName) };

            entity.on_validation_should_have(expectedErrorsCount, expectedMemberNames, expectedErrorMessages);
        }

        public void it_should_report_month_out_of_range_on_validation()
        {
            propertyInfo.SetValue(entity, Constants.MaxMonthValue + 1);

            var expectedErrorsCount = 1;
            var expectedMemberNames = new string[] { propertyName };
            var expectedErrorMessages = new string[] { ValidationMessages.MonthOutOfRange(propertyName) };

            entity.on_validation_should_have(expectedErrorsCount, expectedMemberNames, expectedErrorMessages);
        }

        public void it_should_report_valid_month_on_validation()
        {
            propertyInfo.SetValue(entity, Constants.MinMonthValue);
            entity.should_be_valid();
        }

        public void it_should_report_valid_month_on_validation_2()
        {
            propertyInfo.SetValue(entity, Constants.MaxMonthValue);
            entity.should_be_valid();
        }
    }
}


text:
/*
Title: Free media
Description: Tons of free images, sounds and videos to fuel your bot.
Date: July 23, 2015

Nav: hidden
*/

![ART!](/content/images/illustrations/studio-work.png){.float-right}

### [¶](#free-images){.pilcrow} Free images {#free-images}
- [Old Book Illustrations](http://www.oldbookillustrations.com/) -- illustrations from old books; this very site uses it extensively!
- [Flickr](https://www.flickr.com/search/?q=&l=commderiv&ct=0&mt=all&adv=1) -- CC-licensed content for commercial use on Flickr
- [Clipart](https://openclipart.org/) -- free clipart images
- [The Digital Comic Museum](http://digitalcomicmuseum.com/) -- public domain Golden Age Comics
- [Smithsonian](http://www.asia.si.edu/collections/edan/default.cfm) -- 40,000 works of Asian and American art, can be used for all non-commercial purposes
- [New York Public Library Public Domain Images](http://digitalcollections.nypl.org/search/index?utf8=%E2%9C%93&keywords=&filters[rights][]=pd) -- exactly what it says :-)
- [Project Apollo Archive](https://www.flickr.com/photos/projectapolloarchive/) -- "more than 8,400 high-resolution photographs taken by Apollo astronauts during trips to the moon"

### [¶](#free-videos){.pilcrow} Free videos {#free-videos}
These are not always downloadable, but you can at least freely link to them.

- [British Pathé](https://www.youtube.com/user/britishpathe/videos) -- historical footage
- [AP Archive](https://www.youtube.com/c/aparchive) -- the film and video archive of The Associated Press
- [British Movietone](https://www.youtube.com/channel/UCHq777_waKMJw6SZdABmyaA) -- *arguably the world's greatest newsreel archive, spanning the period 1895 to 1986*
- [Beachfront B-Roll](http://www.beachfrontbroll.com/) -- HD stock video footage and animated backgrounds
- [mazwai.com](http://mazwai.com/#/videos) -- a small collection of stock videos
- [coverr.co](http://www.coverr.co/) -- more stock videos
- [Macaulay Library](http://macaulaylibrary.org/) -- archive of wildlife sounds and videos

[Back to all resources.](/resources)


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # pylint: disable=unused-import, redefined-builtin

import copy

from flexget.api.app import base_message
from flexget.api.plugins.pending_list import ObjectsContainer as OC
from flexget.entry import Entry
from flexget.manager import Session
from flexget.plugins.list.pending_list import PendingListList, PendingListEntry
from flexget.utils import json

class TestPendingListAPI(object):
    config = 'tasks: {}'

    def test_pending_list_list(self, api_client, schema_match):
        # No params
        rsp = api_client.get('/pending_list/')
        assert rsp.status_code == 200

        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_return_lists, data)
        assert not errors

        payload = {'name': 'test_list'}

        # Create list
        rsp = api_client.json_post('/pending_list/', data=json.dumps(payload))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_base_object, data)
        assert not errors

        for field, value in payload.items():
            assert data.get(field) == value

        # Named param
        rsp = api_client.get('/pending_list/?name=test_list')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_return_lists, data)
        assert not errors

        for field, value in payload.items():
            assert data[0].get(field) == value

        # Try to Create list again
        rsp = api_client.json_post('/pending_list/', data=json.dumps(payload))
        assert rsp.status_code == 409
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

    def test_pending_list_list_id(self, api_client, schema_match):
        payload = {'name': 'test_list'}

        # Create list
        rsp = api_client.json_post('/pending_list/', data=json.dumps(payload))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_base_object, data)
        assert not errors

        for field, value in payload.items():
            assert data.get(field) == value

        # Get list
        rsp = api_client.get('/pending_list/1/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_base_object, data)
        assert not errors

        for field, value in payload.items():
            assert data.get(field) == value

        # Delete list
        rsp = api_client.delete('/pending_list/1/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        # Try to get list
        rsp = api_client.get('/pending_list/1/')
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        # Try to Delete list
        rsp = api_client.delete('/pending_list/1/')
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

    def test_pending_list_entries(self, api_client, schema_match):
        # Get non existent list
        rsp = api_client.get('/pending_list/1/entries/')
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        payload = {'name': 'test_list'}

        # Create list
        rsp = api_client.json_post('/pending_list/', data=json.dumps(payload))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_base_object, data)
        assert not errors

        for field, value in payload.items():
            assert data.get(field) == value

        entry_data = {'title': 'title', 'original_url': 'http://test.com'}

        # Add entry to list
        rsp = api_client.json_post('/pending_list/1/entries/', data=json.dumps(entry_data))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

        for field, value in entry_data.items():
            assert data.get(field) == value

        # Get entries from list
        rsp = api_client.get('/pending_list/1/entries/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_lists_entries_return_object, data)
        assert not errors

        for field, value in entry_data.items():
            assert data[0].get(field) == value

        # Try to re-add entry to list
        rsp = api_client.json_post('/pending_list/1/entries/', data=json.dumps(entry_data))
        assert rsp.status_code == 409
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

        # Try to post to non existing list
        rsp = api_client.json_post('/pending_list/10/entries/', data=json.dumps(entry_data))
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

    def test_pending_list_entry(self, api_client, schema_match):
        payload = {'name': 'test_list'}

        # Create list
        rsp = api_client.json_post('/pending_list/', data=json.dumps(payload))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_base_object, data)
        assert not errors

        for field, value in payload.items():
            assert data.get(field) == value

        entry_data = {'title': 'title', 'original_url': 'http://test.com'}

        # Add entry to list
        rsp = api_client.json_post('/pending_list/1/entries/', data=json.dumps(entry_data))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

        for field, value in entry_data.items():
            assert data.get(field) == value

        # Get entries from list
        rsp = api_client.get('/pending_list/1/entries/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_lists_entries_return_object, data)
        assert not errors

        for field, value in entry_data.items():
            assert data[0].get(field) == value

        # Get specific entry from list
        rsp = api_client.get('/pending_list/1/entries/1/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

        for field, value in entry_data.items():
            assert data.get(field) == value

        new_entry_data = {'operation': 'approve'}

        # Change specific entry from list
        rsp = api_client.json_put('/pending_list/1/entries/1/', data=json.dumps(new_entry_data))
        assert rsp.status_code == 201
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(OC.pending_list_entry_base_object, data)
        assert not errors

        assert data['approved']

        # Try to change non-existent entry from list
        rsp = api_client.json_put('/pending_list/1/entries/10/', data=json.dumps(new_entry_data))
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        # Delete specific entry from list
        rsp = api_client.delete('/pending_list/1/entries/1/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        # Get non existent entry from list
        rsp = api_client.get('/pending_list/1/entries/1/')
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

        # Delete non existent entry from list
        rsp = api_client.delete('/pending_list/1/entries/1/')
        assert rsp.status_code == 404
        data = json.loads(rsp.get_data(as_text=True))

        errors = schema_match(base_message, data)
        assert not errors

class TestPendingListPagination(object):
    config = 'tasks: {}'

    def test_pending_list_pagination(self, api_client, link_headers):
        base_entry = dict(title='test_title_', original_url='url_')
        number_of_entries = 200

        with Session() as session:
            pending_list = PendingListList(name='test list')
            session.add(pending_list)

            for i in range(number_of_entries):
                entry = copy.deepcopy(base_entry)
                for k, v in entry.items():
                    entry[k] = v + str(i)
                e = Entry(entry)
                pending_list.entries.append(PendingListEntry(e, pending_list.id))

        # Default values
        rsp = api_client.get('/pending_list/1/entries/')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert len(data) == 50
        assert int(rsp.headers['total-count']) == 200
        assert int(rsp.headers['count']) == 50

        links = link_headers(rsp)
        assert links['last']['page'] == 4
        assert links['next']['page'] == 2

        # Change page size
        rsp = api_client.get('/pending_list/1/entries/?per_page=100')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert len(data) == 100
        assert int(rsp.headers['total-count']) == 200
        assert int(rsp.headers['count']) == 100

        links = link_headers(rsp)
        assert links['last']['page'] == 2
        assert links['next']['page'] == 2

        # Get different page
        rsp = api_client.get('/pending_list/1/entries/?page=2')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert len(data) == 50
        assert int(rsp.headers['total-count']) == 200
        assert int(rsp.headers['count']) == 50

        links = link_headers(rsp)
        assert links['last']['page'] == 4
        assert links['next']['page'] == 3
        assert links['prev']['page'] == 1

    def test_pending_list_sorting(self, api_client):
        base_entry_1 = dict(title='test_title_1', original_url='url_c')
        base_entry_2 = dict(title='test_title_2', original_url='url_b')
        base_entry_3 = dict(title='test_title_3', original_url='url_a')

        with Session() as session:
            pending_list = PendingListList(name='test list')
            session.add(pending_list)

            e1 = Entry(base_entry_1)
            e2 = Entry(base_entry_2)
            e3 = Entry(base_entry_3)

            pending_list.entries.append(PendingListEntry(e1, pending_list.id))
            pending_list.entries.append(PendingListEntry(e2, pending_list.id))
            pending_list.entries.append(PendingListEntry(e3, pending_list.id))

        # Sort by title
        rsp = api_client.get('/pending_list/1/entries/?sort_by=title')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert data[0]['title'] == 'test_title_3'

        rsp = api_client.get('/pending_list/1/entries/?sort_by=title&order=asc')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert data[0]['title'] == 'test_title_1'

        # Sort by original url
        rsp = api_client.get('/pending_list/1/entries/?sort_by=original_url')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert data[0]['original_url'] == 'url_c'

        rsp = api_client.get('/pending_list/1/entries/?sort_by=original_url&order=asc')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert data[0]['original_url'] == 'url_a'

        # Combine sorting and pagination
        rsp = api_client.get('/pending_list/1/entries/?sort_by=title&per_page=2&page=2')
        assert rsp.status_code == 200
        data = json.loads(rsp.get_data(as_text=True))

        assert data[0]['title'] == 'test_title_1'


text:
<?php

namespace Blog\Db;

use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Description of TableAbstractFactory
 *
 * @author claude
 */
class TableAbstractFactory implements AbstractFactoryInterface
{

    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) {
        //echo "<br>".$requestedName;
        return ((substr($requestedName, 0, strlen('application.db.')) == 'application.db.') && !(strpos($requestedName, 'TableGateway')));
    }

    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) {
        $explodedName = explode('.', $requestedName);
        $className = ucfirst(array_pop($explodedName));

        $tableGateway = $serviceLocator->get("application.db.".lcfirst($className).'GatewayFactory');

        //$table = new UserTable($tableGateway);
        $className = "\\Blog\\Db\\".$className;
        $table = new $className($tableGateway);

        return $table;
    }

}