text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Build.Engine.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Immutable;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.IO;
    using System.Reflection;

    using Newtonsoft.Json.Linq;
    using Xunit;

    using Microsoft.DocAsCode.Build.ConceptualDocuments;
    using Microsoft.DocAsCode.Build.ManagedReference;
    using Microsoft.DocAsCode.Build.ResourceFiles;
    using Microsoft.DocAsCode.Build.TableOfContents;
    using Microsoft.DocAsCode.Common;
    using Microsoft.DocAsCode.DataContracts.Common;
    using Microsoft.DocAsCode.Dfm.MarkdownValidators;
    using Microsoft.DocAsCode.Plugins;
    using Microsoft.DocAsCode.Tests.Common;

    [Trait("Owner", "zhyan")]
    [Trait("EntityType", "DocumentBuilder")]
    [Collection("docfx STA")]
    public class DocumentBuilderTest : TestBase
    {
        private const string RawModelFileExtension = ".raw.json";

        private readonly string _inputFolder;
        private readonly string _outputFolder;
        private readonly string _templateFolder;
        private TestLoggerListener Listener { get; set; }

        public DocumentBuilderTest()
        {
            _inputFolder = GetRandomFolder();
            _outputFolder = GetRandomFolder();
            _templateFolder = GetRandomFolder();
            EnvironmentContext.SetBaseDirectory(Directory.GetCurrentDirectory());
            EnvironmentContext.SetOutputDirectory(_outputFolder);
        }

        public override void Dispose()
        {
            EnvironmentContext.Clean();
            base.Dispose();
        }

        [Fact]
        public void TestBuild()
        {
            #region Prepare test data
            var resourceFile = Path.GetFileName(typeof(DocumentBuilderTest).Assembly.Location);
            var resourceMetaFile = resourceFile + ".meta";

            CreateFile("conceptual.html.primary.tmpl", "{{{conceptual}}}", _templateFolder);

            var tocFile = CreateFile("toc.md",
                new[]
                {
                    "# [test1](test.md)",
                    "## [test2](test/test.md)",
                    "# Api",
                    "## [Console](@System.Console)",
                    "## [ConsoleColor](xref:System.ConsoleColor)",
                },
                _inputFolder);
            var conceptualFile = CreateFile("test.md",
                new[]
                {
                    "---",
                    "uid: XRef1",
                    "a: b",
                    "b:",
                    "  c: e",
                    "---",
                    "",
                    "",
                    "",
                    "# Hello World",
                    "Test XRef: @XRef1",
                    "Test link: [link text](test/test.md)",
                    "Test link: [link text 2](../" + resourceFile + ")",
                    "Test link style xref: [link text 3](xref:XRef2 \"title\")",
                    "Test link style xref with anchor: [link text 4](xref:XRef2#anchor \"title\")",
                    "Test encoded link style xref with anchor: [link text 5](xref:%58%52%65%66%32#anchor \"title\")",
                    "Test invalid link style xref with anchor: [link text 6](xref:invalid#anchor \"title\")",
                    "Test autolink style xref: <xref:XRef2>",
                    "Test autolink style xref with anchor: <xref:XRef2#anchor>",
                    "Test encoded autolink style xref with anchor: <xref:%58%52%65%66%32#anchor>",
                    "Test invalid autolink style xref with anchor: <xref:invalid#anchor>",
                    "Test short xref: @XRef2",
                    "Test xref with query string: <xref href=\"XRef2?text=Foo%3CT%3E\"/>",
                    "Test invalid xref with query string: <xref href=\"invalid?alt=Foo%3CT%3E\"/>",
                    "Test xref with attribute: <xref href=\"XRef2\" text=\"Foo<T>\"/>",
                    "Test xref with attribute: <xref href=\"XRef2\" name=\"Foo<T>\"/>",
                    "Test invalid xref with attribute: <xref href=\"invalid\" alt=\"Foo<T>\"/>",
                    "Test invalid xref with attribute: <xref href=\"invalid\" fullname=\"Foo<T>\"/>",
                    "Test external xref with absolute URL and anchor: @str",
                    "Test invalid autolink xref: <xref:?displayProperty=fullName>",
                    "
",
                    "test",
                },
                _inputFolder);
            var conceptualFile2 = CreateFile("test/test.md",
                new[]
                {
                    "---",
                    "uid: XRef2",
                    "a: b",
                    "b:",
                    "  c: e",
                    "---",
                    "# Hello World",
                    "Test XRef: @XRef2",
                    "Test link: [link text](../test.md)",
                    "
",
                    "test",
                },
                _inputFolder);

            File.WriteAllText(resourceMetaFile, @"{ abc: ""xyz"", uid: ""r1"" }");
            File.WriteAllText(MarkdownSytleConfig.MarkdownStyleFileName, @"{
rules : [
    ""foo"",
    { name: ""bar"", disable: true}
],
tagRules : [
    {
        tagNames: [""p""],
        behavior: ""Warning"",
        messageFormatter: ""Tag {0} is not valid."",
        openingTagOnly: true
    }
]
}");

            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { tocFile, conceptualFile, conceptualFile2 });
            files.Add(DocumentType.Article, new[] { "TestData/System.Console.csyml", "TestData/System.ConsoleColor.csyml" }, "TestData/", null);
            files.Add(DocumentType.Resource, new[] { resourceFile });
            #endregion

            Init(MarkdownValidatorBuilder.MarkdownValidatePhaseName);
            try
            {
                using (new LoggerPhaseScope(nameof(DocumentBuilderTest)))
                {
                    BuildDocument(
                        files,
                        new Dictionary<string, object>
                        {
                            ["meta"] = "Hello world!",
                        },
                        templateFolder: _templateFolder);

                }

                {
                    // check log for markdown stylecop.
                    Assert.Equal(2, Listener.Items.Count);

                    Assert.Equal("Tag p is not valid.", Listener.Items[0].Message);
                    Assert.Equal(LogLevel.Warning, Listener.Items[0].LogLevel);

                    Assert.Equal("Tag p is not valid.", Listener.Items[1].Message);
                    Assert.Equal(LogLevel.Warning, Listener.Items[1].LogLevel);
                }

                {
                    // check toc.
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension))));
                    var model = JsonUtility.Deserialize<TocItemViewModel>(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension))).Items;
                    Assert.NotNull(model);
                    Assert.Equal("test1", model[0].Name);
                    Assert.Equal("test.html", model[0].Href);
                    Assert.NotNull(model[0].Items);
                    Assert.Equal("test2", model[0].Items[0].Name);
                    Assert.Equal("test/test.html", model[0].Items[0].Href);
                    Assert.Equal("Api", model[1].Name);
                    Assert.Null(model[1].Href);
                    Assert.NotNull(model[1].Items);
                    Assert.Equal("Console", model[1].Items[0].Name);
                    Assert.Equal("../System.Console.csyml", model[1].Items[0].Href);
                    Assert.Equal("ConsoleColor", model[1].Items[1].Name);
                    Assert.Equal("../System.ConsoleColor.csyml", model[1].Items[1].Href);
                }

                {
                    // check conceptual.
                    var conceptualOutputPath = Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, ".html"));
                    Assert.True(File.Exists(conceptualOutputPath));
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension))));
                    var model = JsonUtility.Deserialize<Dictionary<string, object>>(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension)));
                    Assert.Equal(
                        $"
Hello World
",
                        model["rawTitle"]);
                    Assert.Equal(
                        string.Join(
                            "\n",
                            "",
                            "",
                            "",
                            "",
                            $"
Test XRef: <xref href=\"XRef1\" data-throw-if-not-resolved=\"False\" data-raw-source=\"@XRef1\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"11\" sourceendlinenumber=\"11\"></xref>",
                            $"Test link: link text",
                            $"Test link: link text 2",
                            $"Test link style xref: link text 3",
                            $"Test link style xref with anchor: link text 4",
                            $"Test encoded link style xref with anchor: link text 5",
                            $"Test invalid link style xref with anchor: link text 6",
                            $"Test autolink style xref: <xref href=\"XRef2\" data-throw-if-not-resolved=\"True\" data-raw-source=\"<xref:XRef2>\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"18\" sourceendlinenumber=\"18\"></xref>",
                            $"Test autolink style xref with anchor: <xref href=\"XRef2#anchor\" data-throw-if-not-resolved=\"True\" data-raw-source=\"<xref:XRef2#anchor>\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"19\" sourceendlinenumber=\"19\"></xref>",
                            $"Test encoded autolink style xref with anchor: <xref href=\"%58%52%65%66%32#anchor\" data-throw-if-not-resolved=\"True\" data-raw-source=\"<xref:%58%52%65%66%32#anchor>\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"20\" sourceendlinenumber=\"20\"></xref>",
                            $"Test invalid autolink style xref with anchor: <xref href=\"invalid#anchor\" data-throw-if-not-resolved=\"True\" data-raw-source=\"<xref:invalid#anchor>\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"21\" sourceendlinenumber=\"21\"></xref>",
                            $"Test short xref: <xref href=\"XRef2\" data-throw-if-not-resolved=\"False\" data-raw-source=\"@XRef2\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"22\" sourceendlinenumber=\"22\"></xref>",
                            "Test xref with query string: <xref href=\"XRef2?text=Foo%3CT%3E\"></xref>",
                            "Test invalid xref with query string: <xref href=\"invalid?alt=Foo%3CT%3E\"></xref>",
                            "Test xref with attribute: <xref href=\"XRef2\" text=\"Foo<T>\"></xref>",
                            "Test xref with attribute: <xref href=\"XRef2\" name=\"Foo<T>\"></xref>",
                            "Test invalid xref with attribute: <xref href=\"invalid\" alt=\"Foo<T>\"></xref>",
                            "Test invalid xref with attribute: <xref href=\"invalid\" fullname=\"Foo<T>\"></xref>",
                            $"Test external xref with absolute URL and anchor: <xref href=\"str\" data-throw-if-not-resolved=\"False\" data-raw-source=\"@str\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"29\" sourceendlinenumber=\"29\"></xref>",
                            $"Test invalid autolink xref: <xref href=\"?displayProperty=fullName\" data-throw-if-not-resolved=\"True\" data-raw-source=\"<xref:?displayProperty=fullName>\" sourcefile=\"{_inputFolder}/test.md\" sourcestartlinenumber=\"30\" sourceendlinenumber=\"30\"></xref>",
                            "
",
                            @"test
",
                            ""),
                        model[Constants.PropertyName.Conceptual]);
                    Assert.Equal(
                        string.Join(
                            "\n",
                            "",
                            "",
                            "",
                            "",
                            "
Test XRef: Hello World",
                            "Test link: link text",
                            "Test link: link text 2",
                            "Test link style xref: link text 3",
                            "Test link style xref with anchor: link text 4",
                            "Test encoded link style xref with anchor: link text 5",
                            "Test invalid link style xref with anchor: link text 6",
                            "Test autolink style xref: Hello World",
                            "Test autolink style xref with anchor: Hello World",
                            "Test encoded autolink style xref with anchor: Hello World",
                            "Test invalid autolink style xref with anchor: <xref:invalid#anchor>",
                            "Test short xref: Hello World",
                            "Test xref with query string: Foo<T>",
                            "Test invalid xref with query string: Foo<T>",
                            "Test xref with attribute: Foo<T>",
                            "Test xref with attribute: Foo<T>",
                            "Test invalid xref with attribute: Foo<T>",
                            "Test invalid xref with attribute: Foo<T>",
                            "Test external xref with absolute URL and anchor: str",
                            "Test invalid autolink xref: <xref:?displayProperty=fullName>",
                            "
",
                            "test
",
                            ""),
                        File.ReadAllText(conceptualOutputPath));
                    Assert.Equal("Conceptual", model["type"]);
                    Assert.Equal("Hello world!", model["meta"]);
                    Assert.Equal("b", model["a"]);
                }

                {
                    // check mref.
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension("System.Console.csyml", RawModelFileExtension))));
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension("System.ConsoleColor.csyml", RawModelFileExtension))));
                }

                {
                    // check resource.
                    Assert.True(File.Exists(Path.Combine(_outputFolder, resourceFile)));
                    Assert.True(File.Exists(Path.Combine(_outputFolder, resourceFile + RawModelFileExtension)));
                    var meta = JsonUtility.Deserialize<Dictionary<string, object>>(Path.Combine(_outputFolder, resourceFile + RawModelFileExtension));
                    Assert.Equal(4, meta.Count);
                    Assert.True(meta.ContainsKey("meta"));
                    Assert.Equal("Hello world!", meta["meta"]);
                    Assert.True(meta.ContainsKey("abc"));
                    Assert.Equal("xyz", meta["abc"]);
                    Assert.True(meta.ContainsKey(Constants.PropertyName.Uid));
                    Assert.Equal("r1", meta[Constants.PropertyName.Uid]);
                }
            }
            finally
            {
                CleanUp();
                File.Delete(resourceMetaFile);
            }
        }

        [Fact]
        public void TestMarkdownStyleInPlugins()
        {
            #region Prepare test data
            var resourceFile = Path.GetFileName(typeof(DocumentBuilderTest).Assembly.Location);
            var resourceMetaFile = resourceFile + ".meta";

            CreateFile("conceptual.html.primary.tmpl", "{{{conceptual}}}", _templateFolder);

            var tocFile = CreateFile("toc.md",
                new[]
                {
                    "# [test1](test.md)",
                    "## [test2](test/test.md)",
                    "# Api",
                    "## [Console](@System.Console)",
                    "## [ConsoleColor](xref:System.ConsoleColor)",
                },
                _inputFolder);
            var conceptualFile = CreateFile("test.md",
                new[]
                {
                    "---",
                    "uid: XRef1",
                    "a: b",
                    "b:",
                    "  c: e",
                    "---",
                    "# Hello World",
                    "Test XRef: @XRef1",
                    "Test link: [link text](test/test.md)",
                    "Test link: [link text 2](../" + resourceFile + ")",
                    "Test link style xref: [link text 3](xref:XRef2 \"title\")",
                    "Test link style xref with anchor: [link text 4](xref:XRef2#anchor \"title\")",
                    "Test encoded link style xref with anchor: [link text 5](xref:%58%52%65%66%32#anchor \"title\")",
                    "Test invalid link style xref with anchor: [link text 6](xref:invalid#anchor \"title\")",
                    "Test autolink style xref: <xref:XRef2>",
                    "Test autolink style xref with anchor: <xref:XRef2#anchor>",
                    "Test encoded autolink style xref with anchor: <xref:%58%52%65%66%32#anchor>",
                    "Test invalid autolink style xref with anchor: <xref:invalid#anchor>",
                    "Test short xref: @XRef2",
                    "
",
                    "test",
                },
                _inputFolder);
            var conceptualFile2 = CreateFile("test/test.md",
                new[]
                {
                    "---",
                    "uid: XRef2",
                    "a: b",
                    "b:",
                    "  c: e",
                    "---",
                    "# Hello World",
                    "Test XRef: @XRef2",
                    "Test link: [link text](../test.md)",
                    "

",
                    "test",
                },
                _inputFolder);

            File.WriteAllText(resourceMetaFile, @"{ abc: ""xyz"", uid: ""r1"" }");
            File.WriteAllText(MarkdownSytleConfig.MarkdownStyleFileName, @"{
settings : [
    { category: ""div"", disable: true},
    { category: ""p"", id: ""p-3"", disable: true}
],
}");
            CreateFile(
                MarkdownSytleDefinition.MarkdownStyleDefinitionFolderName + "/p" + MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix,
                @"{
    tagRules : {
        ""p-1"": {
            tagNames: [""p""],
            behavior: ""Warning"",
            messageFormatter: ""Tag {0} is not valid."",
            openingTagOnly: true
        },
        ""p-2"": {
            tagNames: [""p""],
            behavior: ""Warning"",
            messageFormatter: ""Tag {0} is not valid."",
            openingTagOnly: false,
            disable: true
        },
        ""p-3"": {
            tagNames: [""p""],
            behavior: ""Warning"",
            messageFormatter: ""Tag {0} is not valid."",
            openingTagOnly: false,
        }
    }
}
", _templateFolder);
            CreateFile(
                MarkdownSytleDefinition.MarkdownStyleDefinitionFolderName + "/div" + MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix,
                @"{
    tagRules : {
        ""div-1"": {
            tagNames: [""div""],
            behavior: ""Warning"",
            messageFormatter: ""Tag {0} is not valid."",
            openingTagOnly: true
        }
    }
}
", _templateFolder);

            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { tocFile, conceptualFile, conceptualFile2 });
            files.Add(DocumentType.Article, new[] { "TestData/System.Console.csyml", "TestData/System.ConsoleColor.csyml" }, "TestData/", null);
            files.Add(DocumentType.Resource, new[] { resourceFile });
            #endregion

            Init(MarkdownValidatorBuilder.MarkdownValidatePhaseName);
            try
            {
                using (new LoggerPhaseScope(nameof(DocumentBuilderTest)))
                {
                    BuildDocument(
                        files,
                        new Dictionary<string, object>
                        {
                            ["meta"] = "Hello world!",
                        },
                        templateFolder: _templateFolder);
                }

                {
                    // check log for markdown stylecop.
                    Assert.Equal(2, Listener.Items.Count);

                    Assert.Equal("Tag p is not valid.", Listener.Items[0].Message);
                    Assert.Equal(LogLevel.Warning, Listener.Items[0].LogLevel);

                    Assert.Equal("Tag p is not valid.", Listener.Items[1].Message);
                    Assert.Equal(LogLevel.Warning, Listener.Items[1].LogLevel);
                }
            }
            finally
            {
                CleanUp();
                File.Delete(resourceMetaFile);
            }
        }

        [Fact]
        public void TestBuildConceptualWithTemplateShouldSucceed()
        {
            CreateFile("conceptual.html.js", @"
exports.transform = function (model){
  return JSON.stringify(model, null, '  ');
};
exports.xref = null;
", _templateFolder);
            CreateFile("toc.tmpl.js", @"
exports.getOptions = function (){
    return {
        isShared: true
    };
};
", _templateFolder);
            CreateFile("conceptual.html.tmpl", "{{.}}", _templateFolder);
            var conceptualFile = CreateFile("test.md",
                new[]
                {
                    "---",
                    "uid: XRef1",
                    "---",
                    "# Hello World",
                    "Test link: [link text](test/test.md)",
                    "test",
                },
                _inputFolder);
            var conceptualFile2 = CreateFile("test/test.md",
                new[]
                {
                    "---",
                    "uid: XRef2",
                    "---",
                    "test",
                },
                _inputFolder);
            var tocFile = CreateFile("toc.md", new[]
                {
                    "#[Test](test.md)"
                },
                _inputFolder);
            var tocFile2 = CreateFile("test/toc.md", new[]
                {
                    "#[Test](test.md)"
                },
                _inputFolder);
            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { conceptualFile, conceptualFile2, tocFile, tocFile2 });
            BuildDocument(
                files,
                new Dictionary<string, object>
                {
                    ["meta"] = "Hello world!",
                },
                templateFolder: _templateFolder);

            {
                // check toc.
                Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension))));
                var model = JsonUtility.Deserialize<Dictionary<string, object>>(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension)));
                var expected = new Dictionary<string, object>
                {
                    ["_lang"] = "csharp",
                    ["_tocPath"] = $"{_inputFolder}/toc",
                    ["_rel"] = "../",
                    ["_path"] = $"{_inputFolder}/toc",
                    ["_key"] = $"{_inputFolder}/toc.md",
                    ["_tocRel"] = "toc",
                    ["_tocKey"] = $"~/{_inputFolder}/toc.md",
                    ["items"] = new object[]
                    {
                        new {
                            name = "Test",
                            href = "test.html",
                            topicHref = "test.html"
                        }
                    },
                    ["__global"] = new
                    {
                        _shared = new Dictionary<string, object>
                        {
                            [$"~/{_inputFolder}/toc.md"] = new Dictionary<string, object>
                            {
                                ["_lang"] = "csharp",
                                ["_tocPath"] = $"{_inputFolder}/toc",
                                ["_rel"] = "../",
                                ["_path"] = $"{_inputFolder}/toc",
                                ["_key"] = $"{_inputFolder}/toc.md",
                                ["_tocRel"] = "toc",
                                ["_tocKey"] = $"~/{_inputFolder}/toc.md",
                                ["items"] = new object[]
                                {
                                    new {
                                        name = "Test",
                                        href = "test.html",
                                        topicHref = "test.html"
                                    }
                                },
                            },
                            [$"~/{_inputFolder}/test/toc.md"] = new Dictionary<string, object>
                            {
                                ["_lang"] = "csharp",
                                ["_tocPath"] = $"{_inputFolder}/test/toc",
                                ["_rel"] = "../../",
                                ["_path"] = $"{_inputFolder}/test/toc",
                                ["_key"] = $"{_inputFolder}/test/toc.md",
                                ["_tocRel"] = "toc",
                                ["_tocKey"] = $"~/{_inputFolder}/test/toc.md",
                                ["items"] = new object[]
                                {
                                    new {
                                        name = "Test",
                                        href = "test.html",
                                        topicHref = "test.html"
                                    }
                                },
                            }
                        }
                    }
                };
                AssertMetadataEqual(expected, model);
            }

            {
                // check conceptual.
                var conceptualOutputPath = Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, ".html"));
                Assert.True(File.Exists(conceptualOutputPath));
                Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension))));
                var model = JsonUtility.Deserialize<Dictionary<string, object>>(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension)));
                var expected = new Dictionary<string, object>
                {
                    ["_lang"] = "csharp",
                    ["_tocPath"] = $"{_inputFolder}/toc",
                    ["_rel"] = "../",
                    ["_path"] = $"{_inputFolder}/test.html",
                    ["_key"] = $"{_inputFolder}/test.md",
                    ["_tocRel"] = "toc",
                    ["_tocKey"] = $"~/{_inputFolder}/toc.md",
                    ["_systemKeys"] = new[] {
                        "conceptual",
                        "type",
                        "source",
                        "path",
                        "documentation",
                        "title",
                        "rawTitle",
                        "wordCount"
                    },
                    ["conceptual"] = $"\n
Test link: link text\ntest
\n",
                    ["type"] = "Conceptual",
                    ["source"] = model["source"], // reuse model's source, not testing this
                    ["documentation"] = model["source"],
                    ["path"] = $"{_inputFolder}/test.md",
                    ["meta"] = "Hello world!",
                    ["title"] = "Hello World",
                    ["rawTitle"] = $"
Hello World
",
                    ["uid"] = "XRef1",
                    ["wordCount"] = 5,
                    ["__global"] = new
                    {
                        _shared = new Dictionary<string, object>
                        {
                            [$"~/{_inputFolder}/toc.md"] = new Dictionary<string, object>
                            {
                                ["_lang"] = "csharp",
                                ["_tocPath"] = $"{_inputFolder}/toc",
                                ["_rel"] = "../",
                                ["_path"] = $"{_inputFolder}/toc",
                                ["_key"] = $"{_inputFolder}/toc.md",
                                ["_tocRel"] = "toc",
                                ["_tocKey"] = $"~/{_inputFolder}/toc.md",
                                ["items"] = new object[]
                                {
                                    new {
                                        name = "Test",
                                        href = "test.html",
                                        topicHref = "test.html"
                                    }
                                },
                            },
                            [$"~/{_inputFolder}/test/toc.md"] = new Dictionary<string, object>
                            {
                                ["_lang"] = "csharp",
                                ["_tocPath"] = $"{_inputFolder}/test/toc",
                                ["_rel"] = "../../",
                                ["_path"] = $"{_inputFolder}/test/toc",
                                ["_key"] = $"{_inputFolder}/test/toc.md",
                                ["_tocRel"] = "toc",
                                ["_tocKey"] = $"~/{_inputFolder}/test/toc.md",
                                ["items"] = new object[]
                                {
                                    new {
                                        name = "Test",
                                        href = "test.html",
                                        topicHref = "test.html"
                                    }
                                },
                            }
                        }
                    }
                };
                AssertMetadataEqual(expected, model);
            }
        }

        [Fact]
        public void TestBuildWithInvalidPath()
        {
            #region Prepare test data
            var resourceFile = Path.GetFileName(typeof(DocumentBuilderTest).Assembly.Location);
            var resourceMetaFile = resourceFile + ".meta";

            CreateFile("conceptual.html.primary.tmpl", "{{{conceptual}}}", _templateFolder);

            var tocFile = CreateFile("toc.md",
                new[]
                {
                    "# [test1](test.md)",
                    "## [test2](test/test.md)",
                },
                _inputFolder);
            var conceptualFile = CreateFile("test.md",
                new[]
                {
                    "# Hello World",
                    "Test link: [link 1](test/test.md)",
                    "Test link: [link 2](http://www.microsoft.com)",
                    "Test link: [link 3](a b c.md)",
                    "Test link: [link 4](c:\\a.md)",
                    "Test link: [link 5](\\a.md)",
                    "Test link: [link 6](urn:a.md)",
                    "Test link: [link 7](bad urn:a.md)",
                    "Test link: [link 8](test/test.md#top)",
                    "Test link: [link 9](a.md#top)",
                    "Test link: [link 10](#top)",
                },
                _inputFolder);
            var conceptualFile2 = CreateFile("test/test.md",
                new[]
                {
                    "# Hello World",
                    "Test link: [link 1](../test.md)",
                },
                _inputFolder);

            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { tocFile, conceptualFile, conceptualFile2 });
            #endregion

            try
            {
                using (new LoggerPhaseScope(nameof(DocumentBuilderTest)))
                {
                    BuildDocument(
                        files,
                        new Dictionary<string, object>
                        {
                            ["meta"] = "Hello world!",
                        },
                        templateFolder: _templateFolder);

                }

                {
                    // check toc.
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension))));
                    var model = JsonUtility.Deserialize<TocItemViewModel>(Path.Combine(_outputFolder, Path.ChangeExtension(tocFile, RawModelFileExtension))).Items;
                    Assert.NotNull(model);
                    Assert.Equal("test1", model[0].Name);
                    Assert.Equal("test.html", model[0].Href);
                    Assert.NotNull(model[0].Items);
                    Assert.Equal("test2", model[0].Items[0].Name);
                    Assert.Equal("test/test.html", model[0].Items[0].Href);
                }

                {
                    // check conceptual.
                    var conceptualOutputPath = Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, ".html"));
                    Assert.True(File.Exists(conceptualOutputPath));
                    Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension))));
                    var model = JsonUtility.Deserialize<Dictionary<string, object>>(Path.Combine(_outputFolder, Path.ChangeExtension(conceptualFile, RawModelFileExtension)));
                    Assert.Equal(
                        $"
Hello World
",
                        model["rawTitle"]);
                    Assert.Equal(
                        string.Join(
                            "\n",
                            "",
                            $"
Test link: link 1",
                            $"Test link: link 2",
                            $"Test link: link 3",
                            $"Test link: link 4",
                            $"Test link: link 5",
                            $"Test link: link 6",
                            $"Test link: link 7",
                            $"Test link: link 8",
                            $"Test link: link 9",
                            $"Test link: link 10
",
                            ""),
                        model[Constants.PropertyName.Conceptual]);
                    Assert.Equal(
                        string.Join(
                            "\n",
                            "",
                            "
Test link: link 1",
                            $"Test link: link 2",
                            $"Test link: link 3",
                            $"Test link: link 4",
                            $"Test link: link 5",
                            $"Test link: link 6",
                            $"Test link: link 7",
                            $"Test link: link 8",
                            $"Test link: link 9",
                            $"Test link: link 10
",
                            ""),
                        File.ReadAllText(conceptualOutputPath));
                    Assert.Equal("Conceptual", model["type"]);
                    Assert.Equal("Hello world!", model["meta"]);
                }
            }
            finally
            {
            }
        }

        [Fact]
        public void TestBuildWithInvalidPathWithTokenAndMapping()
        {
            #region Prepare test data
            CreateFile("conceptual.html.primary.tmpl", "{{{conceptual}}}", _templateFolder);

            var conceptualFile = CreateFile("a/a.md",
                new[]
                {
                    "[link a](invalid-a.md)",
                    "[link b](../b/invalid-b.md)",
                    "[!include[](../b/token.md)]",
                },
                _inputFolder);
            var tokenFile = CreateFile("b/token.md",
                new[]
                {
                    "[link a](../a/invalid-a.md)",
                    "[link b](invalid-b.md)",
                },
                _inputFolder);

            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { conceptualFile }, Path.Combine(_inputFolder, "a"), ".");
            #endregion

            using (new LoggerPhaseScope(nameof(DocumentBuilderTest)))
            {
                BuildDocument(
                    files,
                    new Dictionary<string, object>(),
                    templateFolder: _templateFolder);
            }
            {
                // check conceptual.
                var conceptualOutputPath = Path.Combine(_outputFolder, "a.html");
                Assert.True(File.Exists(conceptualOutputPath));
                Assert.True(File.Exists(Path.Combine(_outputFolder, Path.ChangeExtension("a.md", RawModelFileExtension))));
                Assert.Equal(
                    string.Join(
                        "\n",
                        "
link a",
                        "link b
",
                        $"
link a",
                        "link b
", ""),
                    File.ReadAllText(conceptualOutputPath));
            }
        }

        private class FakeResponseHandler : DelegatingHandler
        {
            private readonly Dictionary<Uri, HttpResponseMessage> _fakeResponses = new Dictionary<Uri, HttpResponseMessage>();

            public void AddFakeResponse(Uri uri, HttpResponseMessage responseMessage)
            {
                _fakeResponses.Add(uri, responseMessage);
            }

            protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                if (_fakeResponses.ContainsKey(request.RequestUri))
                {
                    return _fakeResponses[request.RequestUri];
                }
                else
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound) { RequestMessage = request };
                }
            }
        }

        [Fact]
        public void TestBuildWithXrefService()
        {
            var fakeResponseHandler = new FakeResponseHandler();
            fakeResponseHandler.AddFakeResponse(new Uri("http://example.org/test1"), new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent("[]")
            });
            fakeResponseHandler.AddFakeResponse(new Uri("http://example.org/test2"), new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent("[{'uid':'csharp_coding_standards', 'name':'C# Coding Standards', 'href':'http://dotnet.github.io/docfx/guideline/csharp_coding_standards.html'}]")
            });

            var httpClient = new HttpClient(fakeResponseHandler);
            var dbc= new DocumentBuildContext("");

            var result = dbc.QueryByHttpRequestAsync(httpClient, "http://example.org/test1", "xx").Result;
            Assert.Equal(0, result.Count);
            result = dbc.QueryByHttpRequestAsync(httpClient, "http://example.org/test2", "xx").Result;
            Assert.Equal("csharp_coding_standards", result[0].Uid);
        }

        [Fact]
        public void TestBuildWithMultipleVersion()
        {
            #region Prepare test data
            var conceptualFile = CreateFile("a.md", "*test*", _inputFolder);
            var conceptualFileWithFileMapping = CreateFile("b.md", "output to `sub` folder", _inputFolder);
            var versionDir = "v0.1";
            var subDir = "sub";

            FileCollection files = new FileCollection(Directory.GetCurrentDirectory());
            files.Add(DocumentType.Article, new[] { conceptualFile }, _inputFolder, ".");
            files.Add(DocumentType.Article, new[] { conceptualFileWithFileMapping }, _inputFolder, subDir);
            #endregion

            using (new LoggerPhaseScope(nameof(DocumentBuilderTest)))
            {
                BuildDocument(
                    files,
                    new Dictionary<string, object>(),
                    templateFolder: _templateFolder,
                    versionDir: versionDir);
            }

            var conceptualOutputPath = Path.Combine(_outputFolder, versionDir, Path.ChangeExtension("a.md", RawModelFileExtension));
            Assert.True(File.Exists(conceptualOutputPath));
            var conceptualWithFileMappingOutputPath = Path.Combine(_outputFolder, versionDir, subDir, Path.ChangeExtension("b.md", RawModelFileExtension));
            Assert.True(File.Exists(conceptualWithFileMappingOutputPath));
        }

        private static void AssertMetadataEqual(object expected, object actual)
        {
            var expectedJObject = JObject.FromObject(expected);
            var actualJObject = JObject.FromObject(actual);
            var equal = JObject.DeepEquals(expectedJObject, actualJObject);
            Assert.True(equal, $"Expected: {expectedJObject.ToJsonString()};{Environment.NewLine}Actual: {actualJObject.ToJsonString()}.");
        }

        private void BuildDocument(FileCollection files, Dictionary<string, object> metadata = null, ApplyTemplateSettings applyTemplateSettings = null, string templateFolder = null, string versionDir = null)
        {
            using (var builder = new DocumentBuilder(LoadAssemblies(), ImmutableArray<string>.Empty, null))
            {
                if (applyTemplateSettings == null)
                {
                    applyTemplateSettings = new ApplyTemplateSettings(_inputFolder, _outputFolder);
                    applyTemplateSettings.RawModelExportSettings.Export = true;
                }
                var parameters = new DocumentBuildParameters
                {
                    Files = files,
                    OutputBaseDir = Path.Combine(Directory.GetCurrentDirectory(), _outputFolder),
                    ApplyTemplateSettings = applyTemplateSettings,
                    Metadata = metadata?.ToImmutableDictionary(),
                    TemplateManager = new TemplateManager(null, null, new List<string> { _templateFolder }, null, null),
                    TemplateDir = templateFolder,
                    VersionDir = versionDir,
                    XRefMaps = ImmutableArray.Create("TestData/xrefmap.yml")
                };
                builder.Build(parameters);
            }
        }

        private IEnumerable<Assembly> LoadAssemblies()
        {
            yield return typeof(ConceptualDocumentProcessor).Assembly;
            yield return typeof(ManagedReferenceDocumentProcessor).Assembly;
            yield return typeof(ResourceDocumentProcessor).Assembly;
            yield return typeof(TocDocumentProcessor).Assembly;
        }

        private void Init(string phaseName)
        {
            Listener = TestLoggerListener.CreateLoggerListenerWithPhaseEndFilter(phaseName);
            Logger.RegisterListener(Listener);
        }

        private void CleanUp()
        {
            Logger.UnregisterListener(Listener);
            Listener = null;
        }
    }
}


text:
package azure_file

import (
	"fmt"
	"strings"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kubernetes/pkg/volume"
)

const (
	fileMode        = "file_mode"
	dirMode         = "dir_mode"
	gid             = "gid"
	vers            = "vers"
	defaultFileMode = "0755"
	defaultDirMode  = "0755"
	defaultVers     = "3.0"
)

// Abstract interface to azure file operations.
type azureUtil interface {
	GetAzureCredentials(host volume.VolumeHost, nameSpace, secretName string) (string, string, error)
	SetAzureCredentials(host volume.VolumeHost, nameSpace, accountName, accountKey string) (string, error)
}

type azureSvc struct{}

func (s *azureSvc) GetAzureCredentials(host volume.VolumeHost, nameSpace, secretName string) (string, string, error) {
	var accountKey, accountName string
	kubeClient := host.GetKubeClient()
	if kubeClient == nil {
		return "", "", fmt.Errorf("Cannot get kube client")
	}

	keys, err := kubeClient.CoreV1().Secrets(nameSpace).Get(secretName, metav1.GetOptions{})
	if err != nil {
		return "", "", fmt.Errorf("Couldn't get secret %v/%v", nameSpace, secretName)
	}
	for name, data := range keys.Data {
		if name == "azurestorageaccountname" {
			accountName = string(data)
		}
		if name == "azurestorageaccountkey" {
			accountKey = string(data)
		}
	}
	if accountName == "" || accountKey == "" {
		return "", "", fmt.Errorf("Invalid %v/%v, couldn't extract azurestorageaccountname or azurestorageaccountkey", nameSpace, secretName)
	}
	return accountName, accountKey, nil
}

func (s *azureSvc) SetAzureCredentials(host volume.VolumeHost, nameSpace, accountName, accountKey string) (string, error) {
	kubeClient := host.GetKubeClient()
	if kubeClient == nil {
		return "", fmt.Errorf("Cannot get kube client")
	}
	secretName := "azure-storage-account-" + accountName + "-secret"
	secret := &v1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: nameSpace,
			Name:      secretName,
		},
		Data: map[string][]byte{
			"azurestorageaccountname": []byte(accountName),
			"azurestorageaccountkey":  []byte(accountKey),
		},
		Type: "Opaque",
	}
	_, err := kubeClient.CoreV1().Secrets(nameSpace).Create(secret)
	if errors.IsAlreadyExists(err) {
		err = nil
	}
	if err != nil {
		return "", fmt.Errorf("Couldn't create secret %v", err)
	}
	return secretName, err
}

// check whether mountOptions contain file_mode, dir_mode, vers, gid, if not, append default mode
func appendDefaultMountOptions(mountOptions []string, fsGroup *int64) []string {
	fileModeFlag := false
	dirModeFlag := false
	versFlag := false
	gidFlag := false

	for _, mountOption := range mountOptions {
		if strings.HasPrefix(mountOption, fileMode) {
			fileModeFlag = true
		}
		if strings.HasPrefix(mountOption, dirMode) {
			dirModeFlag = true
		}
		if strings.HasPrefix(mountOption, vers) {
			versFlag = true
		}
		if strings.HasPrefix(mountOption, gid) {
			gidFlag = true
		}
	}

	allMountOptions := mountOptions
	if !fileModeFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", fileMode, defaultFileMode))
	}

	if !dirModeFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", dirMode, defaultDirMode))
	}

	if !versFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", vers, defaultVers))
	}

	if !gidFlag && fsGroup != nil {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%d", gid, *fsGroup))
	}
	return allMountOptions
}

redpajama_set_name: RedPajamaGithub


text:
package com.manuelmaly.hn.parser;

import android.graphics.Color;

import com.manuelmaly.hn.App;
import com.manuelmaly.hn.Settings;
import com.manuelmaly.hn.model.HNComment;
import com.manuelmaly.hn.model.HNPostComments;
import com.manuelmaly.hn.util.HNHelper;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;

public class HNCommentsParser extends BaseHTMLParser<HNPostComments> {

    @Override
    public HNPostComments parseDocument(Element doc) throws Exception {
        if (doc == null)
            return new HNPostComments();

        ArrayList<HNComment> comments = new ArrayList<HNComment>();

        Elements tableRows = doc.select("table tr table tr:has(table)");

        String currentUser = Settings.getUserName(App.getInstance());

        String text = null;
        String author = null;
        int level = 0;
        String timeAgo = null;
        String url = null;
        Boolean isDownvoted = false;
        String upvoteUrl = null;
        String downvoteUrl = null;

        boolean endParsing = false;
        for (int row = 0; row < tableRows.size(); row++) {
            Element mainRowElement = tableRows.get(row).select("td:eq(2)").first();
            Element rowLevelElement = tableRows.get(row).select("td:eq(0)").first();
            if (mainRowElement == null)
                continue;

            // The not portion of this query is meant to remove the reply link
            // from the text.  As far as I can tell that is the only place
            // where size=1 is used.  If that turns out to not be the case then
            // searching for u tags is also a pretty decent option - @jmaltz
            Element mainCommentDiv = mainRowElement.select("div.comment > span").first();
            if (mainCommentDiv == null)
                continue;

            mainCommentDiv.select("div.reply").remove();

            // Parse the class attribute to get the comment color
            int commentColor = Color.rgb(0, 0, 0);
            if (mainCommentDiv.attributes().hasKey("class")) {
                commentColor = getCommentColor(mainCommentDiv.attributes().get("class"));
            }

            // In order to eliminate whitespace at the end of multi-line comments,
            //
 tags are replaced with double
 tags.
            text = mainCommentDiv.html()
                    .replace(" ", "")
                    .replace("
", "

")
                    .replace("
", "");

            Element comHeadElement = mainRowElement.select("span.comhead").first();
            author = comHeadElement.select("a[href*=user]").text();
            timeAgo = comHeadElement.select("a[href*=item").text();//getFirstTextValueInElementChildren(comHeadElement);
//            if (timeAgoRaw.length() > 0)
//                timeAgo = timeAgoRaw.substring(0, timeAgoRaw.indexOf("|"));
            Element urlElement = comHeadElement.select("a[href*=item]").first();
            if (urlElement != null)
                url = urlElement.attr("href");

            String levelSpacerWidth = rowLevelElement.select("img").first().attr("width");
            if (levelSpacerWidth != null)
                level = Integer.parseInt(levelSpacerWidth) / 40;

            Elements voteElements = tableRows.get(row).select("td:eq(1) a");
            upvoteUrl = getVoteUrl(voteElements.first());

            // We want to test for size because unlike first() calling .get(1)
            // Will throw an error if there are not two elements
            if (voteElements.size() > 1)
                downvoteUrl = getVoteUrl(voteElements.get(1));

            comments.add(new HNComment(timeAgo, author, url, text, commentColor, level, isDownvoted, upvoteUrl, downvoteUrl));

            if (endParsing)
                break;
        }

        // Just using table:eq(0) would return an extra table, so we use
        // get(0) instead, which only returns only the one we want
        Element header = doc.select("body table:eq(0)  tbody > tr:eq(2) > td:eq(0) > table").get(0);
        String headerHtml = null;

        // Five table rows is what it takes for the title, post information
        // And other boilerplate stuff.  More than five means we have something
        // Special
        if (header.select("tr").size() > 5) {
            HeaderParser headerParser = new HeaderParser();
            headerHtml = headerParser.parseDocument(header);
        }

        return new HNPostComments(comments, headerHtml, currentUser);
    }

    /**
     * Parses out the url for voting from a given element
     * @param voteElement The element from which to parse out the voting url
     * @return The relative url to vote in the given direction for that comment
     */
    private String getVoteUrl(Element voteElement) {
        if (voteElement != null) {
            return voteElement.attr("href").contains("auth=") ?
                HNHelper.resolveRelativeHNURL(voteElement.attr("href")) : null;
        }

        return null;
    }

    private int getCommentColor(String className) {
        if ("c5a".equals(className)) {
            return Color.rgb(0x5A, 0x5A, 0x5A);
        } else if ("c73".equals(className)) {
            return Color.rgb(0x73, 0x73, 0x73);
        } else if ("c82".equals(className)) {
            return Color.rgb(0x82, 0x82, 0x82);
        } else if ("c88".equals(className)) {
            return Color.rgb(0x88, 0x88, 0x88);
        } else if ("c9c".equals(className)) {
            return Color.rgb(0x9C, 0x9C, 0x9C);
        } else if ("cae".equals(className)) {
            return Color.rgb(0xAE, 0xAE, 0xAE);
        } else if ("cbe".equals(className)) {
            return Color.rgb(0xBE, 0xBE, 0xBE);
        } else if ("cce".equals(className)) {
            return Color.rgb(0xCE, 0xCE, 0xCE);
        } else if ("cdd".equals(className)) {
            return Color.rgb(0xDD, 0xDD, 0xDD);
        } else {
            return Color.rgb(0, 0, 0);
        }
    }
}


text:
require_relative 'base'

module Whois
  module Scanners

    class Verisign < Base

      self.tokenizers += [
          :skip_empty_line,
          :scan_response_unavailable,
          :scan_available,
          :scan_disclaimer,
          :scan_notice,
          :scan_keyvalue_indented,
          :skip_ianaservice,
          :skip_lastupdate,
          :skip_fuffa,
      ]

      tokenizer :scan_response_unavailable do
        # Check if the string starts with /*
        # If it does, match until the end of all /* lines
        #  or the end of the file and check for the content.
        #
        # Flag the block as visited to force the scanner to ignore this tokenizer
        #  if already used and the content didn't match the unavailable message.
        if @input.match?(/^\*\n/) && !visited?
          p = /^[^*]|\z/
          y = @input.check_until(p) =~ /^\* Sorry, the Whois database is currently down/

          if y
            @input.skip_until(p)
            @ast["response:unavailable"] = true
          else
            visited!
          end
        end
      end

      tokenizer :scan_available do
        if @input.scan(/No match for "(.+?)"\.\n/)
          @ast["Domain Name"] = @input[1].strip
        end
      end

      tokenizer :scan_disclaimer do
        if @input.match?(/^TERMS OF USE:/)
          @ast["Disclaimer"] = _scan_lines_to_array(/(.+)\n/).join(" ")
        end
      end

      tokenizer :scan_notice do
        if @input.match?(/^NOTICE:/)
          @ast["Notice"] = _scan_lines_to_array(/(.+)\n/).join(" ")
        end
      end

      tokenizer :scan_keyvalue_indented do
        if @input.scan(/\s+(.+?):(.*?)\n/)
          key, value = @input[1].strip, @input[2].strip
          if @ast[key].nil?
            @ast[key] = value
          else
            @ast[key] = [@ast[key]] unless @ast[key].is_a?(Array)
            @ast[key] << value
          end
        end
      end

      tokenizer :skip_lastupdate do
        @input.skip(/>>>(.+?)<<<\n/)
      end

      tokenizer :skip_fuffa do
        @input.scan(/^\S(.+)(?:\n|\z)/)
      end

      tokenizer :skip_ianaservice do
        if @input.match?(/IANA Whois Service/)
          @ast["IANA"] = true
          @input.terminate
        end
      end

      private

      def visited?
        !!@tmp["visited:#{@input.pos}"]
      end

      def visited!
        @tmp["visited:#{@input.pos}"] = true
        nil
      end

    end

  end
end


text:
Loading...

            <alerts alerts="alerts" hide-close-button="true"></alerts>
            <osc-image-summary resource="resource"></osc-image-summary>

Source code from {{createDetails.sourceURI}} will be built and deployed unless otherwise specified in the next step.

Create a New Project

                <create-project alerts="alerts" redirect-action="createWithProject"></create-project>

Choose a Project

                <form name="forms.selectProjectForm">

                    <ui-select ng-model="selected.project" name="selectProject" on-select="canIAddToSelectedProject($item)">
                      <ui-select-match placeholder="Project name">
                        {{$select.selected | displayName}}
                      </ui-select-match>
                      <ui-select-choices repeat="project in projects | searchProjects : $select.search">

                          –

                      </ui-select-choices>
                    </ui-select>

                        You are not authorized to add to this project.

                      <button
                        type="submit"
                        class="btn btn-primary"
                        ng-click="createWithProject()"
                        ng-disabled="!(selected.project) || !canIAddToProject"
                        value="">Next</button>
                      Cancel

                </form>

                <uib-tabset>
                  <uib-tab>
                    <uib-tab-heading>Choose Existing Project</uib-tab-heading>
                    <form name="forms.selectProjectForm">

                        <ui-select ng-model="selected.project" name="selectProject" on-select="canIAddToSelectedProject($item)">
                          <ui-select-match placeholder="Project name">
                            {{$select.selected | displayName}}
                          </ui-select-match>
                          <ui-select-choices repeat="project in projects | searchProjects : $select.search">

                              –

                          </ui-select-choices>
                        </ui-select>

                            You are not authorized to add to this project.

                          <button
                            type="submit"
                            class="btn btn-primary"
                            ng-click="createWithProject()"
                            ng-disabled="!(selected.project) || !canIAddToProject"
                            value="">Next</button>
                          Cancel

                    </form>
                  </uib-tab>
                  <uib-tab>
                    <uib-tab-heading>Create a New Project</uib-tab-heading>
                    <create-project alerts="alerts" redirect-action="createWithProject"></create-project>
                  </uib-tab>
                </uib-tabset>

                A project is required in order to complete the installation.
                <ng-include src="'views/_cannot-create-project.html'"></ng-include>


text:
// This file is in charge of the build process:
// Running tests, checking code quality, minifying the code, etc.

'use strict';

// Include gulp
var gulp = require('gulp');

// Include some of our plug-ins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var fs = require('fs');
var inject = require('gulp-inject');
var copy = require('gulp-copy');
var merge = require('merge-stream');
var cssmin = require('gulp-cssmin');
var exists = require('path-exists').sync;
var less = require('gulp-less');
var gutil = require('gulp-util');
var Set = require('collections/set');

// Fix for Bootstrap, that does not embed all the dist files...
var allMainBowerFiles = require('main-bower-files')({
  'overrides': {
    'bootstrap': {
      'main': [
               'dist/fonts/*',
               'dist/css/*',
               'js/dropdown.js']
    }
  }
});

/*
 * QUALITY tasks.
 */
gulp.task('lint', function() {
  var jshint = require('gulp-jshint');
  var gjslint = require('gulp-gjslint');

  // 80 characters per line is too restrictive!
  var lintOptions = {flags: ['--nojsdoc', '--max_line_length 120']};

  return gulp.src([ './src/app/**/*.js', './tests/**/*.js' ])
    .pipe( jshint())
    .pipe( jshint.reporter('default'))
    .pipe( gjslint(lintOptions))
    .pipe( gjslint.reporter('console'));
});

/*
 * Tasks for UNIT tests.
 */
var Server = require('karma').Server;
gulp.task('test', function(done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function() {
    done();
  }).start();
});

/*
 * DEV tasks.
 * These tasks are used to build a dev directory with the right scripts
 * and CSS files. There should be used in development mode. Their output is used
 * to build the final distribution.
 *
 * Tasks workflow:
 *
 * 1. clean-dev
 * 2. build-dev
 * 3. prepare-dev
 */

// Clean all the output directories
gulp.task('clean-dev', function( cb ) {
  del([
       './target/dev/js',
       './target/dev/css',
       './target/dev/templates',
       './target/dev/misc',
       './target/dev/img',
       './target/dev/i18n',
       './target/dev/index.html'
       ], cb);
});

// Shortcut for all the DEV tasks
gulp.task('build-dev', [ 'clean-dev' ], buildDevDirectory );
gulp.task('prepare-dev', [ 'build-dev' ], injectScriptsInDev );

// Watch the files and update the DEV directory
gulp.task('watch-dev', [ 'prepare-dev' ], function () {
  var watch = require('gulp-watch');
  var webserver = require('gulp-webserver');

  // Run a web server
  gulp.src('./target/dev').pipe( webserver());

  // Watch changes in our SRC directory and update the DEV one
  gulp.watch( 'src/**/*', [ 'prepare-watch-dev' ]);
});

// These tasks do not aim at being invoked manually
gulp.task('prepare-watch-dev', [ 'build-watch-dev' ], injectScriptsInDev );
gulp.task('build-watch-dev', buildDevDirectory );

// DEV functions
function injectScriptsInDev() {

  var bowerSources = gulp.src( allMainBowerFiles );
  var roboconfSources = gulp.src([
                                  './target/dev/js/**/*.module.js',
                                  './target/dev/js/**/*.js',
                                  './target/dev/css/**/*.css'], {read: false});

  return gulp.src('./target/dev/index.html')
    .pipe( inject( bowerSources, {name: 'bower', relative: true}))
    .pipe( inject( roboconfSources, {name: 'roboconf', relative: true}))
    .pipe( gulp.dest('./target/dev'));
}

function buildDevDirectory() {

  var changed = require('gulp-changed');
  var html = gulp.src( './src/index.html' ).pipe( gulp.dest( './target/dev/' ));
  var favicon = gulp.src( './src/favicon.ico' )
    .pipe( changed( './target/dev/' ))
    .pipe( gulp.dest( './target/dev/' ));

  var css = gulp.src([ './src/roboconf.less' ])
    .pipe( less())
    .pipe( gulp.dest('./target/dev/css'))
    .pipe( changed( './target/dev/css' ))
    .pipe( copy('./target/dev/css', {'prefix': 1}));

  var js = gulp.src([ './src/app/**/*.js' ])
    .pipe( changed( './target/dev/js' ))
    .pipe( copy('./target/dev/js', {'prefix': 2}));

  var devJs = gulp.src([ './target/dev.config/**/*.js' ])
    .pipe( changed( './target/dev/js' ))
    .pipe( copy('./target/dev/js', {'prefix': 1}));

  var tpl = gulp.src([ './src/app/**/*.html' ])
    .pipe( changed( './target/dev/templates' ))
    .pipe( copy('./target/dev/templates', {'prefix': 2}));

  var misc = gulp.src([ './src/app/**/*.properties' ])
    .pipe( changed( './target/dev/misc' ))
    .pipe( copy('./target/dev/misc', {'prefix': 2}));

  var img = gulp.src([ './src/img/*' ])
    .pipe( changed( './target/dev/img' ))
    .pipe( copy('./target/dev/img', {'prefix': 2}));

  var i18n = gulp.src([ './src/i18n/*' ])
  .pipe( changed( './target/dev/i18n' ))
  .pipe( copy('./target/dev/i18n', {'prefix': 2}));

  return merge( html, favicon, js, devJs, tpl, img, css, misc, i18n );
}

/*
 * DIST tasks.
 * These tasks create a 'target/dist' directory that contain
 * minified resources and all the required Bower dependencies.
 *
 * Therefore, it builds what should be embedded in the Roboconf distribution.
 */
gulp.task('clean-dist', function(done) {
  console.log('Cleaning target/dist' );
  del( 'target/dist', done );
});

gulp.task('prepare-dist', [ 'clean-dist', 'lint', 'check_i18n', 'test' ], prepareDist);
gulp.task('dist', [ 'prepare-dist' ], completeDist);

gulp.task('watch-dist', [ 'dist' ], function () {
  var watch = require('gulp-watch');
  var webserver = require('gulp-webserver');

  // Run a web server
  gulp.src('./target/dist').pipe( webserver());

  // Watch changes in our SRC directory and update the DIST one
  gulp.watch( 'src/**/*', function() {
    prepareDist();
    completeDist();
  });
});

// DIST functions
function prepareDist() {

  var html = gulp.src( './src/index.html' ).pipe( gulp.dest( './target/dist/' ));
  var favicon = gulp.src( './src/favicon.ico' ).pipe( gulp.dest( './target/dist/' ));
  var css = gulp.src([ './src/roboconf.less' ]).pipe( less()).pipe( cssmin()).pipe( rename( 'roboconf.min.css' )).pipe( gulp.dest( './target/dist/' ));
  var tpl = gulp.src([ './src/app/**/*.html' ]).pipe( copy('./target/dist/templates', {'prefix': 2}));
  var img = gulp.src([ './src/img/*' ]).pipe( copy('./target/dist/img', {'prefix': 2}));
  var misc = gulp.src([ './src/app/**/*.properties' ]).pipe( copy('./target/dist/misc', {'prefix': 2}));
  var i18n = gulp.src([ './src/i18n/*' ]).pipe( copy('./target/dist/i18n', {'prefix': 2}));

  var minifyJs = gulp.src(['./src/app/**/*.module.js', './src/app/**/*.js'])
    .pipe( concat('roboconf.min.js'))
    .pipe( uglify())
    .pipe( gulp.dest('target/dist'));

  var devJs = gulp.src([ './target/dev.config/**/*.js' ])
    .pipe( copy('./target/dist', {'prefix': 2}));

  var flags = gulp.src( './target/dev/dependencies/flag-icon-css/flags/**' ).pipe( gulp.dest( './target/dist/lib/flag-icon-css/flags/' ));

  return merge( html, favicon, tpl, misc, img, css, minifyJs, devJs, i18n, flags );
}

function completeDist() {
  // Find Bower dependencies with minified versions when available
  var bowerWithMin = allMainBowerFiles.map( function(path, index, arr) {
    var newPath = path.replace(/.([^.]+)$/g, '.min.$1');
    return exists( newPath ) ? newPath : path;
  });

  var bowerSourcesWithMin = gulp.src( bowerWithMin, {base: './target/dev/dependencies'})
    .pipe( gulp.dest( './target/dist/lib' ));

  // List our own resources
  var roboconfSources = gulp.src([
    './target/dist/*.min.js',
    './target/dist/*.js',
    './target/dist/roboconf.min.css'], {read: false});

  var devJs = gulp.src(['./target/dist/'], {read: false});

  // And inject...
  return gulp.src('./target/dist/index.html')
    .pipe( inject( bowerSourcesWithMin, {name: 'bower', ignorePath: 'target/dist/', addRootSlash: false}))
    .pipe( inject( roboconfSources, {name: 'roboconf', relative: true}))
    .pipe( gulp.dest('./target/dist'));
}

/*
 * Production tasks.
 * Those we will run from Maven.
 */
gulp.task('no-dev-config', function () {

  if (exists('./target/dev.config')) {
    throw new gutil.PluginError({
      plugin: 'no-dev-config',
      message: 'The embed task cannot work as long as "target/dev.config" exists. Please, delete or rename this directory.'
    });
  }
});

gulp.task('prepare-embed', [ 'clean-dist', 'no-dev-config' ], prepareDist);
gulp.task('complete-embed', [ 'prepare-embed' ], completeDist);
gulp.task('embed', [ 'prepare-embed', 'complete-embed' ]);
gulp.task('clean', [ 'clean-dist', 'clean-dev' ]);

/*
 * i18n verifications.
 */
var qual = require('angular-translate-quality');
gulp.task('check_i18n', function() {

  // A call back to search keys in JS files when they are not found in HTML files.
  var external_keys_cb = function(errorCallback, notFoundKeys) {

    var found = [];
    var jsFiles = [
      'instances/instances.controller.listing.js',
      'instances/instances.controller.new.js',
      'commands/commands.controller.listing.js',
      'commands/commands.directive.history.js',
      'application-bindings/application-bindings.controller.js'
    ];

    jsFiles.forEach(function(f) {
      var content = fs.readFileSync('./src/app/' + f).toString();
      notFoundKeys.forEach(function(key) {
        if (content.indexOf(key) !== -1) {
          found.push(key);
        }
      });
    });

    var errors = false;
    notFoundKeys.forEach(function(key) {
      if (found.indexOf(key) === -1) {
        errorCallback('Key ' + key + ' was not found anywhere.');
        errors = true;
      }
    });

    return errors;
  };

  // Validation options.
  var options = {
    loc_i18n: './src/i18n/**/',
    loc_html: './src/app/**/',
    fail_on_warning: true,
    ignore_order: false,
    external_keys_cb: external_keys_cb,
    forbidden_patterns: {},
    exclusions: ['...', 'Roboconf', 'x', '-', '.']
  };

  options.forbidden_patterns.en_US = [
    {regex: '\\s[,.;:?!]', msg: '[EN] All the punctuation marks refuse any preceding white space character.'},
    {regex: '[,.;:?!]([^.\\s]|\\s{2,})', msg: '[EN] All the punctuation marks accept a single white space after.'},
    {regex: '\\.\\.\\.(\\S|\\s{2,})', msg: '[EN] Dots accept a single white space after.'}
  ];

  options.forbidden_patterns.fr_FR = [
    {regex: '\\s[,.]', msg: '[FR] Commas and dots do not accept any preceding white space character.'},
    {regex: '\\S[;:?!]', msg: '[FR] All the punctuation marks (except commas and full stops) accept a single white space before.'},
    {regex: '[,.;:?!]([^.\\s]|\\s{2,})', msg: '[FR] All the punctuation marks accept a single white space after.'},
    {regex: '\\.\\.\\.(\\S|\\s{2,})', msg: '[FR] Dots accept a single white space after.'}
  ];

  options.forbidden_patterns_cb = function(errorCallback, key, value, errorMsg, lineNumber, filename) {
    var invalid = key !== 'COMMON_DATE_PATTERN';
    if (invalid) {
      errorCallback(lineNumber + ': ' + errorMsg);
    }

    return invalid;
  };

  // Fail the task if an error was found.
  var res = qual.validate(options);
  if (! res) {
    throw new gutil.PluginError({
      plugin: 'check_i18n',
      message: 'Errors were found about internationalization.'
    });
  }
});


text:
package com.abooc.emoji.chat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.abooc.emoji.EmojiCache;
import com.abooc.emoji.R;
import com.abooc.emoji.widget.PointIndicator;

/**
 * 表情
 */
public class EmojiFragment extends Fragment implements GridViewer, OnItemClickListener, AdapterView.OnItemLongClickListener {

    public EmojiFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_emoji, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        ViewPager viewPager = (ViewPager) view.findViewById(R.id.ViewPager);

        ViewAdapter pagerAdapter = new ViewAdapter(getContext());
        pagerAdapter.setData(EmojiCache.getEmojiArrays());
        viewPager.setOffscreenPageLimit(2);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);

        PointIndicator iPointIndicator = (PointIndicator) getActivity().findViewById(R.id.PointIndicator);
        iPointIndicator.setViewPager(viewPager);
    }

    private OnItemClickListener mOnItemClickListener;
    private AdapterView.OnItemLongClickListener mOnItemLongClickListener;

    @Override
    public void setOnItemClickListener(OnItemClickListener l) {
        mOnItemClickListener = l;
    }

    @Override
    public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener l) {
        mOnItemLongClickListener = l;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(parent, view, position, id);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (mOnItemLongClickListener != null) {
            return mOnItemLongClickListener.onItemLongClick(parent, view, position, id);
        }
        return false;
    }

    class ViewAdapter extends PagerAdapter {

        Context mContext;
        Emoji[] mArray;
        int mCount;
        int mPage = 0;
        int pageSize = 20;

        ViewAdapter(Context context) {
            mContext = context;
        }

        int getPage(int count, int pageSize) {
            int page = (count + (pageSize - 1)) / pageSize;
            return page;
        }

        public void setData(Emoji[] array) {
            mArray = array;
            mCount = array.length;
            mPage = getPage(mCount, pageSize);
        }

        public Emoji[] getGroup(int page) {
            int thisPageSize = page < (mPage - 1) ? pageSize : (mCount % pageSize);
            int start = (page * pageSize);
            int end = start + thisPageSize;

            Emoji[] newArray = new Emoji[thisPageSize + 1];
            System.arraycopy(mArray, start, newArray, 0, thisPageSize);

            Drawable drawable = getResources().getDrawable(R.drawable.emoji_backspace);
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            newArray[thisPageSize] = new Emoji("删除键", "[-d]", bitmap);
            return newArray;
        }

        @Override
        public int getCount() {
            return mPage;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            Emoji[] emojis = getGroup(position);
            EmojiAdapter adapter = new EmojiAdapter(mContext, R.layout.emoji_item, emojis);

            LayoutInflater inflater = LayoutInflater.from(mContext);
            GridView gridView = (GridView) inflater.inflate(R.layout.emoji, container, false);
            gridView.setTag(position);
            gridView.setOnItemClickListener(EmojiFragment.this);
            gridView.setOnItemLongClickListener(EmojiFragment.this);
            gridView.setAdapter(adapter);

            container.addView(gridView);
            return gridView;
        }

    }

    static class EmojiAdapter extends ArrayAdapter<Emoji> {

        private int resId;

        public EmojiAdapter(Context context, int resource, Emoji[] objects) {
            super(context, resource, objects);
            resId = resource;
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(getContext());
                convertView = inflater.inflate(resId, parent, false);
            }
            Emoji item = getItem(position);

            ImageView imageView = (ImageView) convertView;
            imageView.setImageBitmap(item.icon);
            return imageView;
        }

    }

}


text:
using NSubstitute;
using SIM.Sitecore9Installer.Validation;
using System.Collections.Generic;
using SIM.Sitecore9Installer.Tasks;
using SIM.Sitecore9Installer.Validation.Validators;
using Xunit;

namespace SIM.Sitecore9Installer.Tests.Validation.Validators
{
  public class LicenseFileValidatorTests
  {
    [Theory]
    [InlineData(true, ValidatorState.Success)]
    [InlineData(false, ValidatorState.Error)]
    public void ReturnsValidValidationResults(bool fileExists, ValidatorState expectedResult)
    {
      //Arrange
      Task task = Substitute.For<Task>("", 0, null, null, new Dictionary<string, string>());
      GlobalParameters globals = new GlobalParameters();
      task.LocalParams.Returns(new LocalParameters(new List<InstallParam>(),globals));

      task.LocalParams.AddOrUpdateParam("LicenseFile", @"C:\license.xml",InstallParamType.String);

      List<Task> tasks = Substitute.For<List<Task>>();
      tasks.Add(task);

      LicenseFileValidator val = Substitute.ForPartsOf<LicenseFileValidator>();
      val.FileExists(string.Empty).ReturnsForAnyArgs(fileExists);

      val.Data["LicenseFileVariable"] = "LicenseFile";

      //Act
      IEnumerable<ValidationResult> results = val.Evaluate(tasks);

      //Assert
      Assert.Contains(results, r => r.State == expectedResult);
    }
  }
}


text:
import { getRootBasedUrl } from '@resolve-js/core'
import { extractErrorHttpCode, extractRequestBody } from '../utils'

import type { ResolveRequest, ResolveResponse } from '../types'

export const queryHandler = async (
  req: ResolveRequest,
  res: ResolveResponse
) => {
  const segment = req.resolve.performanceTracer.getSegment()
  const subSegment = segment.addNewSubsegment('query')

  try {
    const baseQueryUrl = getRootBasedUrl(req.resolve.rootPath, '/api/query/')
    const paramsPath = req.path.substring(baseQueryUrl.length)
    const [modelName, modelOptions] = paramsPath.split('/')

    if (modelName == null || modelOptions == null) {
      const error = new Error(
        'Invalid "modelName" and/or "modelOptions" parameters'
      ) as any
      error.code = 400
      throw error
    }

    const modelArgs = extractRequestBody(req)

    const result = await req.resolve.executeQuery.read(
      {
        modelName,
        modelOptions,
        modelArgs,
        jwt: req.jwt,
      },
      // TODO ????
      { req: req as any, res }
    )

    subSegment.addAnnotation('modelName', modelName)
    subSegment.addAnnotation('origin', 'resolve:query')

    res.status(200)
    res.setHeader('Content-Type', 'application/json')

    if (
      (result.meta?.aggregateIds != null || result.meta?.eventTypes != null) &&
      modelArgs.origin != null
    ) {
      const { aggregateIds } = result.meta || {}

      const subscriptionAggregateIds =
        Array.isArray(aggregateIds) ||
        aggregateIds === '*' ||
        aggregateIds == null
          ? aggregateIds
          : [aggregateIds]

      const subscribeOptions = await req.resolve.getReactiveSubscription(
        modelArgs.origin,
        result.meta.eventTypes,
        subscriptionAggregateIds
      )

      res.setHeader(
        'X-Resolve-View-Model-Subscription',
        JSON.stringify(subscribeOptions)
      )
    }

    res.end(
      await req.resolve.executeQuery.serializeState({
        modelName,
        state: result,
        jwt: req.jwt,
      })
    )
  } catch (error) {
    const errorCode = extractErrorHttpCode(error)
    res.status(errorCode)
    res.setHeader('Content-Type', 'text/plain')
    res.end(error.message)
    subSegment.addError(error)
  } finally {
    subSegment.close()
  }
}


text:
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.WebEncoders;
using System;
using System.IO;

namespace OAuth.AspNet.AuthServer
{

    /// <summary>
    /// Authorization Server middleware component which is added to an OWIN pipeline. This class is not
    /// created by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
    /// extension method.
    /// </summary>
    public class OAuthAuthorizationServerMiddleware : AuthenticationMiddleware<OAuthAuthorizationServerOptions>
    {
        /// <summary>
        /// Authorization Server middleware component which is added to an OWIN pipeline. This constructor is not
        /// called by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
        /// extension method.
        /// </summary>
        public OAuthAuthorizationServerMiddleware(RequestDelegate next, OAuthAuthorizationServerOptions options, ILoggerFactory loggerFactory, IDataProtectionProvider dataProtectionProvider, IUrlEncoder encoder) : base(next, options, loggerFactory, encoder)
        {
            if (Options.Provider == null)
            {
                Options.Provider = new OAuthAuthorizationServerProvider();
            }

            if (Options.AuthorizationCodeFormat == null)
            {
                IDataProtector dataProtecter = dataProtectionProvider.CreateProtector(typeof(OAuthAuthorizationServerMiddleware).FullName, "Authentication_Code", "v1");

                Options.AuthorizationCodeFormat = new TicketDataFormat(dataProtecter);
            }

            if (Options.RefreshTokenFormat == null)
            {
                IDataProtector dataProtecter = dataProtectionProvider.CreateProtector(typeof(OAuthAuthorizationServerMiddleware).FullName, "Refresh_Token", "v1");

                Options.RefreshTokenFormat = new TicketDataFormat(dataProtecter);
            }

            if (Options.TokenDataProtector == null)
            {
               #if DNXCORE50
                Options.TokenDataProtector = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
               #else
                Options.TokenDataProtector = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.Machine))).CreateProtector("OAuth.AspNet.AuthServer");
               #endif
            }

            if (Options.AccessTokenFormat == null)
            {
                IDataProtector dataProtecter = Options.TokenDataProtector.CreateProtector("Access_Token", "v1");

                Options.AccessTokenFormat = new TicketDataFormat(dataProtecter);
            }

            if (Options.AuthorizationCodeProvider == null)
            {
                Options.AuthorizationCodeProvider = new AuthenticationTokenProvider();
            }

            if (Options.AccessTokenProvider == null)
            {
                Options.AccessTokenProvider = new AuthenticationTokenProvider();
            }

            if (Options.RefreshTokenProvider == null)
            {
                Options.RefreshTokenProvider = new AuthenticationTokenProvider();
            }
        }

        /// <summary>
        /// Called by the AuthenticationMiddleware base class to create a per-request handler.
        /// </summary>
        /// <returns>A new instance of the request handler</returns>
        protected override AuthenticationHandler<OAuthAuthorizationServerOptions> CreateHandler()
        {
            return new OAuthAuthorizationServerHandler();
        }
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/a9cb8cae/css/bootstrap.css" rel="stylesheet">
<link href="./assets/a408446c/solarized_light.css" rel="stylesheet">
<link href="./assets/64f80fce/style.css" rel="stylesheet">

    <title>Friendly API</title>

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w178-collapse">Toggle navigation

</button>Friendly API

Class reference

Guide

    <input id="searchbox" type="text" class="form-control" placeholder="Search">

app\assets
AppAsset

app\commands
ConectadosController
HelloController
TokenController

app\controllers
AjaxController
AmigosController
ConectadosController
EstadosController
PoblacionController
PrivadosController
ProvinciasController
PublicosController
SiteController
UsuariosController

app\models
Amigo
AmigoSearch
Conectado
ConectadoSearch
ContactForm
Estado
EstadoSearch
LoginForm
Privado
PrivadoSearch
Publico
PublicoSearch
Usuario
UsuarioSearch

Class Reference

    <colgroup>
        <col class="col-package" />
        <col class="col-class" />
        <col class="col-description" />
    </colgroup>

        Class
        Description

        app\assets\AppAsset
        Clase donde añadir archivos css, javascript, dependencias, etc.

        app\commands\ConectadosController
        Este comando muestra la cadena pasada como parámetro.

        app\commands\HelloController
        Este comando muestra la cadena pasada como parámetro.

        app\commands\TokenController
        Acciones relacionadas con el token de un usuario.

        app\controllers\AjaxController
        AjaxController, controlador que se encarga de todas las acciones que
tienen que var con la tecnología ajax.

        app\controllers\AmigosController
        AmigosController implementa el CRUD y más acciones para el modelo amigos.

        app\controllers\ConectadosController
        ConectadosController implementa el CRUD y más acciones para el modelo conectados.

        app\controllers\EstadosController
        EstadosController implementa el CRUD y más acciones para el modelo Estado.

        app\controllers\PoblacionController
        PoblacionController, controlador que se encarga de todas las acciones que
tienen que var con las poblaciones.

        app\controllers\PrivadosController
        PrivadosController implementa el CRUD y más acciones para el modelo Privados.

        app\controllers\ProvinciasController
        ProvinciasController, controlador que se encarga de todas las acciones que
tienen que var con las provincias.

        app\controllers\PublicosController
        PublicosController implementa el CRUD y más acciones para el modelo Publico.

        app\controllers\SiteController
        SiteController, controlador que se encarga de todas las acciones que
tienen que ver con la web en general.

        app\controllers\UsuariosController
        UsuariosController implementa el CRUD y más acciones para el modelo Usuario.

        app\models\Amigo
        Modelo de la tabla "amigos".

        app\models\AmigoSearch
        AmigoSearch representa el modelo de búsqueda para app\models\Amigo.

        app\models\Conectado
        Modelo de la tabla "Conectado".

        app\models\ConectadoSearch
        ConectadoSearch representa el modelo de búsqueda para app\models\Conectado.

        app\models\ContactForm
        ContactForm es el modelo para el formulario de contacto.

        app\models\Estado
        Modelo de la tabla "estados".

        app\models\EstadoSearch
        EstadoSearch representa el modelo de búsqueda para app\models\Estado.

        app\models\LoginForm
        LoginForm es el modelo para el formulario de login.

        app\models\Privado
        Modelo de la tabla "privados".

        app\models\PrivadoSearch
        PrivadoSearch representa el modelo de búsqueda para app\models\Privado.

        app\models\Publico
        TModelo de la tabla "publicos".

        app\models\PublicoSearch
        PublicoSearch representa el modelo de búsqueda para  app\models\Publico.

        app\models\Usuario
        Modelo de la tabla "usuarios".

        app\models\UsuarioSearch
        UsuarioSearch representa el modelo de búsqueda para app\models\Usuario.

Page generated on Mon, 12 Jun 2017 19:32:58 +0000

    Powered by Yii Framework


text:
module Capistrano
  module Scm
    module Strategy

      VERSION = '0.2.0'.freeze

    end
  end
end


text: Please enable JavaScript to view the comments powered by Disqus.


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Preview\Understand\Service\Intent;

use Twilio\InstanceContext;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 */
class SampleContext extends InstanceContext {
    /**
     * Initialize the SampleContext
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param string $serviceSid The service_sid
     * @param string $intentSid The intent_sid
     * @param string $sid The sid
     * @return \Twilio\Rest\Preview\Understand\Service\Intent\SampleContext
     */
    public function __construct(Version $version, $serviceSid, $intentSid, $sid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array('serviceSid' => $serviceSid, 'intentSid' => $intentSid, 'sid' => $sid, );

        $this->uri = '/Services/' . rawurlencode($serviceSid) . '/Intents/' . rawurlencode($intentSid) . '/Samples/' . rawurlencode($sid) . '';
    }

    /**
     * Fetch a SampleInstance
     *
     * @return SampleInstance Fetched SampleInstance
     */
    public function fetch() {
        $params = Values::of(array());

        $payload = $this->version->fetch(
            'GET',
            $this->uri,
            $params
        );

        return new SampleInstance(
            $this->version,
            $payload,
            $this->solution['serviceSid'],
            $this->solution['intentSid'],
            $this->solution['sid']
        );
    }

    /**
     * Update the SampleInstance
     *
     * @param array|Options $options Optional Arguments
     * @return SampleInstance Updated SampleInstance
     */
    public function update($options = array()) {
        $options = new Values($options);

        $data = Values::of(array(
            'Language' => $options['language'],
            'TaggedText' => $options['taggedText'],
        ));

        $payload = $this->version->update(
            'POST',
            $this->uri,
            array(),
            $data
        );

        return new SampleInstance(
            $this->version,
            $payload,
            $this->solution['serviceSid'],
            $this->solution['intentSid'],
            $this->solution['sid']
        );
    }

    /**
     * Deletes the SampleInstance
     *
     * @return boolean True if delete succeeds, false otherwise
     */
    public function delete() {
        return $this->version->delete('delete', $this->uri);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Preview.Understand.SampleContext ' . implode(' ', $context) . ']';
    }
}


text:
package net.quetzi.morpheus.api;

public interface IMorpheusAPI {

    /**
     * Register your INewDayHandler with MorpheusRegistry
     *
     * @param newdayhandler
     * @param dimension
     */
    void registerHandler(INewDayHandler newdayhandler, int dimension);
    void unregisterHandler(int dimension);
}


text:
package net.i2p.data;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import net.i2p.I2PAppContext;
import net.i2p.util.LHMCache;
import net.i2p.util.SimpleByteCache;
import net.i2p.util.SystemVersion;

/**
 *  A least recently used cache with a max size, for SimpleDataStructures.
 *  The index to the cache is the first 4 bytes of the data, so
 *  the data must be sufficiently random.
 *
 *  This caches the SDS objects, and also uses SimpleByteCache to cache
 *  the unused byte arrays themselves
 *
 *  Following is sample usage:
 *  <pre>

    private static final SDSCache<Foo> _cache = new SDSCache(Foo.class, LENGTH, 1024);

    public static Foo create(byte[] data) {
        return _cache.get(data);
    }

    public static Foo create(byte[] data, int off) {
        return _cache.get(data, off);
    }

    public static Foo create(InputStream in) throws IOException {
        return _cache.get(in);
    }

 *  </pre>
 *  @since 0.8.3
 *  @author zzz
 */
public class SDSCache<V extends SimpleDataStructure> {
    //private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(SDSCache.class);

    private static final Class[] conArg = new Class[] { byte[].class };
    private static final double MIN_FACTOR = 0.20;
    private static final double MAX_FACTOR = 5.0;
    private static final double FACTOR;
    static {
        long maxMemory = SystemVersion.getMaxMemory();
        FACTOR = Math.max(MIN_FACTOR, Math.min(MAX_FACTOR, maxMemory / (128*1024*1024d)));
    }

    /** the LRU cache */
    private final Map<Integer, WeakReference<V>> _cache;
    /** the byte array length for the class we are caching */
    private final int _datalen;
    /** the constructor for the class we are caching */
    private final Constructor<V> _rvCon;
    private final String _statName;

    /**
     *  @param rvClass the class that we are storing, i.e. an extension of SimpleDataStructure
     *  @param len the length of the byte array in the SimpleDataStructure
     *  @param max maximum size of the cache assuming 128MB of mem.
     *             The actual max size will be scaled based on available memory.
     */
    public SDSCache(Class<V> rvClass, int len, int max) {
        int size = (int) (max * FACTOR);
        _cache = new LHMCache<Integer, WeakReference<V>>(size);
        _datalen = len;
        try {
            _rvCon = rvClass.getConstructor(conArg);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("SDSCache init error", e);
        }
        _statName = "SDSCache." + rvClass.getSimpleName();
        //if (_log.shouldLog(Log.DEBUG))
        //    _log.debug("New SDSCache for " + rvClass + " data size: " + len +
        //               " max: " + size + " max mem: " + (len * size));
        I2PAppContext.getGlobalContext().statManager().createRateStat(_statName, "Hit rate", "Router", new long[] { 10*60*1000 });
        I2PAppContext.getGlobalContext().addShutdownTask(new Shutdown());
    }

    /**
     * @since 0.8.8
     */
    private class Shutdown implements Runnable {
        public void run() {
            synchronized(_cache) {
                _cache.clear();
            }
        }
    }

    /**
     *  WARNING - If the SDS is found in the cache, the passed-in
     *  byte array will be returned to the SimpleByteCache for reuse.
     *  Do NOT save a reference to the passed-in data, or use or modify it,
     *  after this call.
     *
     *  @param data non-null, the byte array for the SimpleDataStructure
     *  @return the cached value if available, otherwise
     *          makes a new object and returns it
     *  @throws IllegalArgumentException if data is not the correct number of bytes
     *  @throws NPE
     */
    public V get(byte[] data) {
        if (data == null)
            throw new NullPointerException("Don't pull null data from the cache");
        int found;
        V rv;
        Integer key = hashCodeOf(data);
        synchronized(_cache) {
            WeakReference<V> ref = _cache.get(key);
            if (ref != null)
                rv = ref.get();
            else
                rv = null;
            if (rv != null && DataHelper.eq(data, rv.getData())) {
                // found it, we don't need the data passed in any more
                SimpleByteCache.release(data);
                found = 1;
            } else {
                // make a new one
                try {
                    rv = _rvCon.newInstance(new Object[] { data } );
                } catch (InstantiationException e) {
                    throw new RuntimeException("SDSCache error", e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("SDSCache error", e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException("SDSCache error", e);
                }
                _cache.put(key, new WeakReference<V>(rv));
               found = 0;
            }
        }
        I2PAppContext.getGlobalContext().statManager().addRateData(_statName, found);
        return rv;
    }

    /*
     *  @param b non-null byte array containing the data, data will be copied to not hold the reference
     *  @param off offset in the array to start reading from
     *  @return the cached value if available, otherwise
     *          makes a new object and returns it
     *  @throws AIOOBE if not enough bytes
     *  @throws NPE
     */
    public V get(byte[] b, int off) {
        byte[] data = SimpleByteCache.acquire(_datalen);
        System.arraycopy(b, off, data, 0, _datalen);
        return get(data);
    }

    /*
     *  @param in a stream from which the bytes will be read
     *  @return the cached value if available, otherwise
     *          makes a new object and returns it
     *  @throws IOException if not enough bytes
     */
    public V get(InputStream in) throws IOException {
        byte[] data = SimpleByteCache.acquire(_datalen);
        int read = DataHelper.read(in, data);
        if (read != _datalen)
            throw new EOFException("Not enough bytes to read the data");
        return get(data);
    }

    /**
     * We assume the data has enough randomness in it, so use the first 4 bytes for speed.
     */
    private static Integer hashCodeOf(byte[] data) {
        int rv = data[0];
        for (int i = 1; i < 4; i++)
            rv ^= (data[i] << (i*8));
        return Integer.valueOf(rv);
    }
}


text:
<?php

$socketServer = stream_socket_server('127.0.0.1:19999');
$client       = stream_socket_accept($socketServer);

fclose($client);