//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Filters;

namespace NLog.UnitTests.Layouts
{
    using NLog.LayoutRenderers;
    using NLog.LayoutRenderers.Wrappers;
    using NLog.Layouts;
    using NLog.Targets;
    using System;
    using Xunit;
    using static Config.TargetConfigurationTests;

    public class SimpleLayoutParserTests : NLogTestBase
    {
        [Fact]
        public void SimpleTest()
        {
            SimpleLayout l = "${message}";
            Assert.Single(l.Renderers);
            Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
        }

        [Fact]
        public void UnclosedTest()
        {
            new SimpleLayout("${message");
        }

        [Fact]
        public void SingleParamTest()
        {
            SimpleLayout l = "${mdc:item=AAA}";
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("AAA", mdc.Item);
        }

        [Fact]
        public void ValueWithColonTest()
        {
            SimpleLayout l = "${mdc:item=AAA\\:}";
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("AAA:", mdc.Item);
        }

        [Fact]
        public void ValueWithBracketTest()
        {
            SimpleLayout l = "${mdc:item=AAA\\}\\:}";
            Assert.Equal("${mdc:item=AAA\\}\\:}", l.Text);
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("AAA}:", mdc.Item);
        }

        [Fact]
        public void DefaultValueTest()
        {
            SimpleLayout l = "${mdc:BBB}";
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("BBB", mdc.Item);
        }

        [Fact]
        public void DefaultValueWithBracketTest()
        {
            SimpleLayout l = "${mdc:AAA\\}\\:}";
            Assert.Equal("${mdc:AAA\\}\\:}", l.Text);
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("AAA}:", mdc.Item);
        }

        [Fact]
        public void DefaultValueWithOtherParametersTest()
        {
            SimpleLayout l = "${exception:message,type:separator=x}";
            Assert.Single(l.Renderers);
            ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
            Assert.NotNull(elr);
            Assert.Equal("message,type", elr.Format);
            Assert.Equal("x", elr.Separator);
        }

        [Fact]
        public void EmptyValueTest()
        {
            SimpleLayout l = "${mdc:item=}";
            Assert.Single(l.Renderers);
            MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
            Assert.NotNull(mdc);
            Assert.Equal("", mdc.Item);
        }

        [Fact]
        public void NestedLayoutTest()
        {
            SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}";
            Assert.Single(l.Renderers);
            var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
            Assert.NotNull(lr);
            var nestedLayout = lr.Inner as SimpleLayout;
            Assert.NotNull(nestedLayout);
            Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
            Assert.Single(nestedLayout.Renderers);
            var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
            Assert.NotNull(ndcLayoutRenderer);
            Assert.Equal(3, ndcLayoutRenderer.TopFrames);
            Assert.Equal("x", ndcLayoutRenderer.Separator);
        }

        [Fact]
        public void DoubleNestedLayoutTest()
        {
            SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}";
            Assert.Single(l.Renderers);
            var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
            Assert.NotNull(lr);
            var nestedLayout0 = lr.Inner as SimpleLayout;
            Assert.NotNull(nestedLayout0);
            Assert.Equal("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
            var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
            var nestedLayout = innerRot13.Inner as SimpleLayout;
            Assert.NotNull(nestedLayout);
            Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
            Assert.Single(nestedLayout.Renderers);
            var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
            Assert.NotNull(ndcLayoutRenderer);
            Assert.Equal(3, ndcLayoutRenderer.TopFrames);
            Assert.Equal("x", ndcLayoutRenderer.Separator);
        }

        [Fact]
        public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
        {
            SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}";
            Assert.Single(l.Renderers);
            var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
            Assert.NotNull(lr);
            var nestedLayout0 = lr.Inner as SimpleLayout;
            Assert.NotNull(nestedLayout0);
            Assert.Equal("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
            var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
            var nestedLayout = innerRot13.Inner as SimpleLayout;
            Assert.NotNull(nestedLayout);
            Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
            Assert.Single(nestedLayout.Renderers);
            var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
            Assert.NotNull(ndcLayoutRenderer);
            Assert.Equal(3, ndcLayoutRenderer.TopFrames);
            Assert.Equal("x", ndcLayoutRenderer.Separator);
        }

        [Fact]
        public void AmbientPropertyTest()
        {
            SimpleLayout l = "${message:padding=10}";
            Assert.Single(l.Renderers);
            var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
            Assert.NotNull(pad);
            var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
            Assert.NotNull(message);
        }

        [Fact]
        public void MissingLayoutRendererTest()
        {
            LogManager.ThrowConfigExceptions = true;
            Assert.Throws<NLogConfigurationException>(() =>
            {
                SimpleLayout l = "${rot13:${foobar}}";
            });
        }

        [Fact]
        public void DoubleAmbientPropertyTest()
        {
            SimpleLayout l = "${message:uppercase=true:padding=10}";
            Assert.Single(l.Renderers);
            var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
            Assert.NotNull(upperCase);
            var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
            Assert.NotNull(pad);
            var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
            Assert.NotNull(message);
        }

        [Fact]
        public void ReverseDoubleAmbientPropertyTest()
        {
            SimpleLayout l = "${message:padding=10:uppercase=true}";
            Assert.Single(l.Renderers);
            var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
            Assert.NotNull(pad);
            var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
            Assert.NotNull(upperCase);
            var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
            Assert.NotNull(message);
        }

        [Fact]
        public void EscapeTest()
        {
            AssertEscapeRoundTrips(string.Empty);
            AssertEscapeRoundTrips("hello ${${}} world!");
            AssertEscapeRoundTrips("hello $");
            AssertEscapeRoundTrips("hello ${");
            AssertEscapeRoundTrips("hello $${{");
            AssertEscapeRoundTrips("hello ${message}");
            AssertEscapeRoundTrips("hello ${${level}}");
            AssertEscapeRoundTrips("hello ${${level}${message}}");
        }

        [Fact]
        public void EvaluateTest()
        {
            var logEventInfo = LogEventInfo.CreateNullEvent();
            logEventInfo.Level = LogLevel.Warn;
            Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
        }

        [Fact]
        public void EvaluateTest2()
        {
            Assert.Equal("Off", SimpleLayout.Evaluate("${level}"));
            Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}"));
            Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}"));
        }

        private static void AssertEscapeRoundTrips(string originalString)
        {
            string escapedString = SimpleLayout.Escape(originalString);
            SimpleLayout l = escapedString;
            string renderedString = l.Render(LogEventInfo.CreateNullEvent());
            Assert.Equal(originalString, renderedString);
        }

        [Fact]
        public void LayoutParserEscapeCodesForRegExTestV1()
        {
            MappedDiagnosticsContext.Clear();

            var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
    <variable name=""searchExp""
              value=""(?<!\\d[ -]*)(?\u003a(?<digits>\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))""
              />

    <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />

    <targets>
      <target name=""d1"" type=""Debug"" layout=""${message1}"" />
    </targets>

    <rules>
      <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
    </rules>
</nlog>");

            var d1 = configuration.FindTargetByName("d1") as DebugTarget;
            Assert.NotNull(d1);
            var layout = d1.Layout as SimpleLayout;
            Assert.NotNull(layout);

            var c = layout.Renderers.Count;
            Assert.Equal(1, c);

            var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;

            Assert.NotNull(l1);
            Assert.True(l1.Regex);
            Assert.True(l1.IgnoreCase);
            Assert.Equal(@"::", l1.ReplaceWith);
            Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
        }

        [Fact]
        public void LayoutParserEscapeCodesForRegExTestV2()
        {
            MappedDiagnosticsContext.Clear();

            var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
    <variable name=""searchExp""
              value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))""
              />

    <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />

    <targets>
      <target name=""d1"" type=""Debug"" layout=""${message1}"" />
    </targets>

    <rules>
      <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
    </rules>
</nlog>");

            var d1 = configuration.FindTargetByName("d1") as DebugTarget;
            Assert.NotNull(d1);
            var layout = d1.Layout as SimpleLayout;
            Assert.NotNull(layout);

            var c = layout.Renderers.Count;
            Assert.Equal(1, c);

            var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;

            Assert.NotNull(l1);
            Assert.True(l1.Regex);
            Assert.True(l1.IgnoreCase);
            Assert.Equal(@"::", l1.ReplaceWith);
            Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
        }

        [Fact]
        public void InnerLayoutWithColonTest_with_workaround()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test: Hello", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithColonTest()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test: Hello", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithSlashSingleTest()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test\\Hello", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithSlashTest()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test\\Hello", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test{Hello}", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest2()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal(@"Test{Hello\}", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_reverse()
        {
            SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test{Hello}", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_no_escape()
        {
            SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Test{Hello}", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithHashTest()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("Log_{#}.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithHashTest_need_escape()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("L}.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_needEscape()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("}{.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_needEscape2()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("{}}{.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_needEscape3()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("{}}}.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_needEscape4()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("{}}}.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithBracketsTest_needEscape5()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("}{a}.log", l.Render(le));
        }

        [Fact]
        public void InnerLayoutWithHashTest_and_layoutrender()
        {
            SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            Assert.Equal("1/Log_{#}.log", l.Render(le));
        }

        [Fact]
        public void InvalidLayoutWillParsePartly()
        {
            using (new NoThrowNLogExceptions())
            {
                SimpleLayout l = @"aaa ${iDontExist} bbb";

                var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
                Assert.Equal("aaa  bbb", l.Render(le));
            }
        }

        [Fact]
        public void InvalidLayoutWillThrowIfExceptionThrowingIsOn()
        {
            LogManager.ThrowConfigExceptions = true;
            Assert.Throws<ArgumentException>(() =>
            {
                SimpleLayout l = @"aaa ${iDontExist} bbb";
            });

        }

        /// <summary>
        ///
        /// Test layout with Generic List type. - is the separator
        ///
        ///
        /// </summary>
        /// <remarks>
        /// comma escape is backtick (cannot use backslash due to layout parse)
        /// </remarks>
        /// <param name="input"></param>
        /// <param name="propname"></param>
        /// <param name="expected"></param>
        [Theory]
        [InlineData("2,3,4", "numbers", "2-3-4")]
        [InlineData("a,b,c", "Strings", "a-b-c")]
        [InlineData("a,b,c", "Objects", "a-b-c")]
        [InlineData("a,,b,c", "Strings", "a--b-c")]
        [InlineData("a`b,c", "Strings", "a`b-c")]
        [InlineData("a\'b,c", "Strings", "a'b-c")]
        [InlineData("'a,b',c", "Strings", "a,b-c")]
        [InlineData("2.0,3.0,4.0", "doubles", "2-3-4")]
        [InlineData("2.1,3.2,4.3", "doubles", "2.1-3.2-4.3")]
        [InlineData("Ignore,Neutral,Ignore", "enums", "Ignore-Neutral-Ignore")]
        [InlineData("ASCII,ISO-8859-1, UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
        [InlineData("ASCII,ISO-8859-1,UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
        [InlineData("Value1,Value3,Value2", "FlagEnums", "Value1-Value3-Value2")]
        [InlineData("2,3,4", "IEnumerableNumber", "2-3-4")]
        [InlineData("2,3,4", "IListNumber", "2-3-4")]
        [InlineData("2,3,4", "HashsetNumber", "2-3-4")]
#if !NET3_5
        [InlineData("2,3,4", "ISetNumber", "2-3-4")]
#endif
        [InlineData("a,b,c", "IEnumerableString", "a-b-c")]
        [InlineData("a,b,c", "IListString", "a-b-c")]
        [InlineData("a,b,c", "HashSetString", "a-b-c")]
#if !NET3_5
        [InlineData("a,b,c", "ISetString", "a-b-c")]
#endif
        public void LayoutWithListParamTest(string input, string propname, string expected)
        {
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
            SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";

            var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
            var actual = l.Render(le);
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData("2,,3,4", "numbers")]
        [InlineData("a,bc", "numbers")]
        [InlineData("value1,value10", "FlagEnums")]
        public void LayoutWithListParamTest_incorrect(string input, string propname)
        {
            //note flags enum already supported

            //can;t convert empty to int
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
            Assert.Throws<NLogConfigurationException>(() =>
            {
                SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";

            });
        }

        [Theory]
        [InlineData(@"                                    ${literal:text={0\} {1\}}")]
        [InlineData(@"                           ${cached:${literal:text={0\} {1\}}}")]
        [InlineData(@"                  ${cached:${cached:${literal:text={0\} {1\}}}}")]
        [InlineData(@"         ${cached:${cached:${cached:${literal:text={0\} {1\}}}}}")]
        [InlineData(@"${cached:${cached:${cached:${cached:${literal:text={0\} {1\}}}}}}")]
        public void Render_EscapedBrackets_ShouldRenderAllBrackets(string input)
        {
            SimpleLayout simple = input.Trim();
            var result = simple.Render(LogEventInfo.CreateNullEvent());
            Assert.Equal("{0} {1}", result);
        }

        [Fact]
        void FuncLayoutRendererRegisterTest1()
        {
            LayoutRenderer.Register("the-answer", (info) => "42");
            Layout l = "${the-answer}";
            var result = l.Render(LogEventInfo.CreateNullEvent());
            Assert.Equal("42", result);
        }

        [Fact]
        void FuncLayoutRendererFluentMethod_ThreadSafe_Test()
        {
            // Arrange
            var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadSafe);
            // Act
            var result = layout.Render(LogEventInfo.CreateNullEvent());
            // Assert
            Assert.Equal("42", result);
            Assert.True(layout.ThreadSafe);
            Assert.False(layout.ThreadAgnostic);
        }

        [Fact]
        void FuncLayoutRendererFluentMethod_ThreadAgnostic_Test()
        {
            // Arrange
            var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadAgnostic);
            // Act
            var result = layout.Render(LogEventInfo.CreateNullEvent());
            // Assert
            Assert.Equal("42", result);
            Assert.True(layout.ThreadSafe);
            Assert.True(layout.ThreadAgnostic);
        }

        [Fact]
        void FuncLayoutRendererFluentMethod_ThreadUnsafe_Test()
        {
            // Arrange
            var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.None);
            // Act
            var result = layout.Render(LogEventInfo.CreateNullEvent());
            // Assert
            Assert.Equal("42", result);
            Assert.False(layout.ThreadSafe);
            Assert.False(layout.ThreadAgnostic);
        }

        [Fact]
        void FuncLayoutRendererFluentMethod_NullThrows_Test()
        {
            // Arrange
            Assert.Throws<ArgumentNullException>(() => Layout.FromMethod(null));
        }

        [Fact]
        void FuncLayoutRendererRegisterTest1WithXML()
        {
            LayoutRenderer.Register("the-answer", (info) => 42);

            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>

                <targets>
                    <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetCurrentClassLogger();
            logger.Debug("test1");
            AssertDebugLastMessage("debug", "TheAnswer=042");
        }

        [Fact]
        void FuncLayoutRendererRegisterTest2()
        {
            LayoutRenderer.Register("message-length", (info) => info.Message.Length);
            Layout l = "${message-length}";
            var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890"));
            Assert.Equal("10", result);
        }

        [Fact]
        void SimpleLayout_FromString_ThrowConfigExceptions()
        {
            Assert.Throws<NLogConfigurationException>(() => Layout.FromString("${evil}", true));
        }

        [Fact]
        void SimpleLayout_FromString_NoThrowConfigExceptions()
        {
            Assert.NotNull(Layout.FromString("${evil}", false));
        }

        [Theory]
        [InlineData("", true)]
        [InlineData(null, true)]
        [InlineData("'a'", true)]
        [InlineData("${gdc:a}", false)]
        public void FromString_isFixedText(string input, bool expected)
        {
            // Act
            var layout = (SimpleLayout)Layout.FromString(input);
            layout.Initialize(null);

            // Assert
            Assert.Equal(expected, layout.IsFixedText);
        }

        [Theory]
        [InlineData("", true)]
        [InlineData(null, true)]
        [InlineData("'a'", true)]
        [InlineData("${gdc:a}", true)]
        public void FromString_isThreadSafe(string input, bool expected)
        {
            // Act
            var layout = (SimpleLayout)Layout.FromString(input);
            layout.Initialize(null);

            // Assert
            Assert.Equal(expected, layout.ThreadSafe);
        }

        [Theory]
        [InlineData("", "")]
        [InlineData(null, "")]
        [InlineData("'a'", "'a'")]
        [InlineData("${gdc:a}", "")]
        public void Render(string input, string expected)
        {
            var layout = (SimpleLayout)Layout.FromString(input);

            // Act
            var result = layout.Render(LogEventInfo.CreateNullEvent());

            // Assert
            Assert.Equal(expected, result);
        }

        [Fact]
        public void Parse_AppDomainFixedOutput_ConvertToLiteral()
        {
            // Arrange
            var input = "${newline}";

            // Act
            var layout = (SimpleLayout)Layout.FromString(input);

            // Assert
            var single = Assert.Single(layout.Renderers);
            Assert.IsType<LiteralLayoutRenderer>(single);
        }

        [Fact]
        public void Parse_MultipleAppDomainFixedOutput_ConvertSingleToLiteral()
        {
            // Arrange
            var input = "${newline}${machinename}";

            // Act
            var layout = (SimpleLayout)Layout.FromString(input);

            // Assert
            var single = Assert.Single(layout.Renderers);
            Assert.IsType<LiteralLayoutRenderer>(single);
        }

        [Fact]
        public void Parse_AppDomainFixedOutputWithRawValue_ConvertSingleToLiteralAndKeepRawValue()
        {
            // Arrange
            var input = "${processid}";

            // Act
            var layout = (SimpleLayout)Layout.FromString(input);

            // Assert
            var single = Assert.Single(layout.Renderers);
            var singleRaw = Assert.IsType<LiteralWithRawValueLayoutRenderer>(single);
            var succeeded = singleRaw.TryGetRawValue(LogEventInfo.CreateNullEvent(), out var rawValue);
            Assert.True(succeeded);
            var rawValueInt = Assert.IsType<int>(rawValue);
            Assert.True(rawValueInt > 0);

        }

        /// <summary>
        /// Combined literals should not support rawValue
        /// </summary>
        [Theory]
        [InlineData("${newline}${processid}")]
        [InlineData("${processid}${processid}")]
        [InlineData("${processid}${processname}")]
        [InlineData("${processname}${processid}")]
        [InlineData("${processname}-${processid}")]
        public void Parse_Multiple_ConvertSingleToLiteralWithoutRaw(string input)
        {
            // Act
            var layout = (SimpleLayout)Layout.FromString(input);

            // Assert
            var single = Assert.Single(layout.Renderers);
            Assert.IsType<LiteralLayoutRenderer>(single);
        }

        private class LayoutRendererWithListParam : LayoutRenderer
        {
            public List<double> Doubles { get; set; }

            public List<FilterResult> Enums { get; set; }

            public List<MyFlagsEnum> FlagEnums { get; set; }

            public List<int> Numbers { get; set; }

            public List<string> Strings { get; set; }

            public List<object> Objects { get; set; }

            public List<Encoding> Encodings { get; set; }

            public IEnumerable<string> IEnumerableString { get; set; }

            public IEnumerable<int> IEnumerableNumber { get; set; }

            public IList<string> IListString { get; set; }

            public IList<int> IListNumber { get; set; }

#if !NET3_5
            public ISet<string> ISetString { get; set; }

            public ISet<int> ISetNumber { get; set; }

#endif

            public HashSet<int> HashSetNumber { get; set; }

            public HashSet<string> HashSetString { get; set; }

            /// <summary>
            /// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />.
            /// </summary>
            /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
            /// <param name="logEvent">Logging event.</param>
            protected override void Append(StringBuilder builder, LogEventInfo logEvent)
            {
                Append(builder, Strings);
                AppendFormattable(builder, Numbers);
                AppendFormattable(builder, Enums);
                AppendFormattable(builder, FlagEnums);
                AppendFormattable(builder, Doubles);
                Append(builder, Encodings?.Select(e => e.BodyName).ToList());
                Append(builder, Objects);
                Append(builder, IEnumerableString);
                AppendFormattable(builder, IEnumerableNumber);
                Append(builder, IListString);
                AppendFormattable(builder, IListNumber);
#if !NET3_5
                Append(builder, ISetString);
                AppendFormattable(builder, ISetNumber);

#endif
                Append(builder, HashSetString);
                AppendFormattable(builder, HashSetNumber);
            }

            private void Append<T>(StringBuilder builder, IEnumerable<T> items)
            {
                if (items != null) builder.Append(string.Join("-", items.ToArray()));
            }

            private void AppendFormattable<T>(StringBuilder builder, IEnumerable<T> items)
                where T : IFormattable
            {
                if (items != null) builder.Append(string.Join("-", items.Select(it => it.ToString(null, CultureInfo.InvariantCulture)).ToArray()));
            }
        }
    }
}

{'repo_name': 'NLog/NLog', 'stars': '4586', 'repo_language': 'C#', 'file_name': 'ManuallyLoadedTarget.cs', 'mime_type': 'text/x-c++', 'hash': 4463834617783733021, 'source_dataset': 'data'}


/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 */

package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.DatasetResourceInner;
import com.microsoft.azure.arm.model.Indexable;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.DataFactoryManager;
import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.DatasetInner;
import java.util.Map;
import java.util.List;

/**
 * Type representing DatasetResource.
 */
public interface DatasetResource extends HasInner<DatasetResourceInner>, Indexable, Refreshable<DatasetResource>, Updatable<DatasetResource.Update>, HasManager<DataFactoryManager> {
    /**
     * @return the etag value.
     */
    String etag();

    /**
     * @return the id value.
     */
    String id();

    /**
     * @return the name value.
     */
    String name();

    /**
     * @return the properties value.
     */
    DatasetInner properties();

    /**
     * @return the type value.
     */
    String type();

    /**
     * The entirety of the DatasetResource definition.
     */
    interface Definition extends DefinitionStages.Blank, DefinitionStages.WithFactory, DefinitionStages.WithIfMatch, DefinitionStages.WithProperties, DefinitionStages.WithCreate {
    }

    /**
     * Grouping of DatasetResource definition stages.
     */
    interface DefinitionStages {
        /**
         * The first stage of a DatasetResource definition.
         */
        interface Blank extends WithFactory {
        }

        /**
         * The stage of the datasetresource definition allowing to specify Factory.
         */
        interface WithFactory {
           /**
            * Specifies resourceGroupName, factoryName.
            * @param resourceGroupName The resource group name
            * @param factoryName The factory name
            * @return the next definition stage
            */
            WithIfMatch withExistingFactory(String resourceGroupName, String factoryName);
        }

        /**
         * The stage of the datasetresource definition allowing to specify IfMatch.
         */
        interface WithIfMatch {
           /**
            * Specifies ifMatch.
            * @param ifMatch ETag of the dataset entity.  Should only be specified for update, for which it should match existing entity or can be * for unconditional update
            * @return the next definition stage
            */
            WithProperties withIfMatch(String ifMatch);
        }

        /**
         * The stage of the datasetresource definition allowing to specify Properties.
         */
        interface WithProperties {
           /**
            * Specifies properties.
            * @param properties Dataset properties
            * @return the next definition stage
            */
            WithCreate withProperties(DatasetInner properties);
        }

        /**
         * The stage of the definition which contains all the minimum required inputs for
         * the resource to be created (via {@link WithCreate#create()}), but also allows
         * for any other optional settings to be specified.
         */
        interface WithCreate extends Creatable<DatasetResource> {
        }
    }
    /**
     * The template for a DatasetResource update operation, containing all the settings that can be modified.
     */
    interface Update extends Appliable<DatasetResource>, UpdateStages.WithIfMatch, UpdateStages.WithProperties {
    }

    /**
     * Grouping of DatasetResource update stages.
     */
    interface UpdateStages {
        /**
         * The stage of the datasetresource update allowing to specify IfMatch.
         */
        interface WithIfMatch {
            /**
             * Specifies ifMatch.
             * @param ifMatch ETag of the dataset entity.  Should only be specified for update, for which it should match existing entity or can be * for unconditional update
             * @return the next update stage
             */
            Update withIfMatch(String ifMatch);
        }

        /**
         * The stage of the datasetresource update allowing to specify Properties.
         */
        interface WithProperties {
            /**
             * Specifies properties.
             * @param properties Dataset properties
             * @return the next update stage
             */
            Update withProperties(DatasetInner properties);
        }

    }
}

{'repo_name': 'Azure/azure-sdk-for-java', 'stars': '587', 'repo_language': 'Java', 'file_name': 'MetricSpecification.java', 'mime_type': 'text/x-java', 'hash': 1516191143232654511, 'source_dataset': 'data'}


using System.Collections.Generic;
using MVCMovie.Models;

namespace MVCMovie.Controllers
{
    public class MVCMovieContext
    {
        public IList<Movie> Movies { get; } = new List<Movie>();

        public void AddMovie(Movie movie)
        {
            movie.Id = Movies.Count;
            Movies.Add(movie);
        }

        public void SaveChanges()
        {
            // No-op. In real world, this would save to a backing store e.g. SQL Server.
        }
    }
}

{'repo_name': 'dotnetcore/aspnetcore-doc-cn', 'stars': '525', 'repo_language': 'C#', 'file_name': 'FixSite.exe.config', 'mime_type': 'text/xml', 'hash': -815362922305936159, 'source_dataset': 'data'}


/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2020 - Raw Material Software Limited

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
static String jucePermissionToAndroidPermission (RuntimePermissions::PermissionID permission)
{
    switch (permission)
    {
        case RuntimePermissions::recordAudio:            return "android.permission.RECORD_AUDIO";
        case RuntimePermissions::bluetoothMidi:          return "android.permission.ACCESS_COARSE_LOCATION";
        case RuntimePermissions::readExternalStorage:    return "android.permission.READ_EXTERNAL_STORAGE";
        case RuntimePermissions::writeExternalStorage:   return "android.permission.WRITE_EXTERNAL_STORAGE";
        case RuntimePermissions::camera:                 return "android.permission.CAMERA";
    }

    // invalid permission
    jassertfalse;
    return {};
}

static RuntimePermissions::PermissionID androidPermissionToJucePermission (const String& permission)
{
    if      (permission == "android.permission.RECORD_AUDIO")             return RuntimePermissions::recordAudio;
    else if (permission == "android.permission.ACCESS_COARSE_LOCATION")   return RuntimePermissions::bluetoothMidi;
    else if (permission == "android.permission.READ_EXTERNAL_STORAGE")    return RuntimePermissions::readExternalStorage;
    else if (permission == "android.permission.WRITE_EXTERNAL_STORAGE")   return RuntimePermissions::writeExternalStorage;
    else if (permission == "android.permission.CAMERA")                   return RuntimePermissions::camera;

    return static_cast<RuntimePermissions::PermissionID> (-1);
}

//==============================================================================
struct PermissionsRequest
{
    PermissionsRequest() {}

    // using "= default" on the following method triggers an internal compiler error
    // in Android NDK 17
    PermissionsRequest (const PermissionsRequest& o)
        : callback (o.callback), permission (o.permission)
    {}

    PermissionsRequest (PermissionsRequest&& o)
        : callback (std::move (o.callback)), permission (o.permission)
    {
        o.permission = static_cast<RuntimePermissions::PermissionID> (-1);
    }

    PermissionsRequest (RuntimePermissions::Callback && callbackToUse,
                        RuntimePermissions::PermissionID permissionToRequest)
        : callback (std::move (callbackToUse)), permission (permissionToRequest)
    {}

    PermissionsRequest& operator= (const PermissionsRequest & o)
    {
        callback   = o.callback;
        permission = o.permission;
        return *this;
    }

    PermissionsRequest& operator= (PermissionsRequest && o)
    {
        callback   = std::move (o.callback);
        permission = o.permission;
        return *this;
    }

    RuntimePermissions::Callback callback;
    RuntimePermissions::PermissionID permission;
};

//==============================================================================
struct PermissionsOverlay   : FragmentOverlay
{
    PermissionsOverlay (CriticalSection& cs) : overlayGuard (cs) {}
    ~PermissionsOverlay() override = default;

    struct PermissionResult
    {
        PermissionsRequest request;
        bool granted;
    };

    void onStart() override    { onRequestPermissionsResult (0, {}, {}); }

    void onRequestPermissionsResult (int /*requestCode*/,
                                     const StringArray& permissions,
                                     const Array<int>& grantResults) override
    {
        std::vector<PermissionResult> results;

        {
            ScopedLock lock (overlayGuard);

            for (auto it = requests.begin(); it != requests.end();)
            {
                auto& request = *it;

                if (RuntimePermissions::isGranted (request.permission))
                {
                    results.push_back ({std::move (request), true});
                    it = requests.erase (it);
                }
                else
                {
                    ++it;
                }
            }

            auto n = permissions.size();

            for (int i = 0; i < n; ++i)
            {
                auto permission = androidPermissionToJucePermission (permissions[i]);
                auto granted = (grantResults.getReference (i) == 0);

                for (auto it = requests.begin(); it != requests.end();)
                {
                    auto& request = *it;

                    if (request.permission == permission)
                    {
                        results.push_back ({std::move (request), granted});
                        it = requests.erase (it);
                    }
                    else
                    {
                        ++it;
                    }
                }
            }
        }

        for (const auto& result : results)
            if (result.request.callback)
                result.request.callback (result.granted);

        {
            auto* env = getEnv();
            ScopedLock lock (overlayGuard);

            if (requests.size() > 0)
            {
                auto &request = requests.front();

                StringArray permissionsArray{
                        jucePermissionToAndroidPermission (request.permission)};
                auto jPermissionsArray = juceStringArrayToJava (permissionsArray);

                auto requestPermissionsMethodID
                    = env->GetMethodID(AndroidFragment, "requestPermissions", "([Ljava/lang/String;I)V");

                // this code should only be reached for SDKs >= 23, so this method should be
                // be available
                jassert(requestPermissionsMethodID != nullptr);

                env->CallVoidMethod (getNativeHandle(), requestPermissionsMethodID, jPermissionsArray.get (), 0);
            }
            else
            {
                getSingleton() = nullptr;
            }
        }
    }

    static std::unique_ptr<PermissionsOverlay>& getSingleton()
    {
        static std::unique_ptr<PermissionsOverlay> instance;
        return instance;
    }

    CriticalSection& overlayGuard;
    std::vector<PermissionsRequest> requests;
};

//==============================================================================
void RuntimePermissions::request (PermissionID permission, Callback callback)
{
    auto requestedPermission = jucePermissionToAndroidPermission (permission);

    if (! isPermissionDeclaredInManifest (requestedPermission))
    {
        // Error! If you want to be able to request this runtime permission, you
        // also need to declare it in your app's manifest. You can do so via
        // the Projucer. Otherwise this can't work.
        jassertfalse;

        callback (false);
        return;
    }

    auto alreadyGranted = isGranted (permission);

    if (alreadyGranted || getAndroidSDKVersion() < 23)
    {
        callback (alreadyGranted);
        return;
    }

    PermissionsRequest request (std::move (callback), permission);

    static CriticalSection overlayGuard;
    ScopedLock lock (overlayGuard);

    std::unique_ptr<PermissionsOverlay>& overlay = PermissionsOverlay::getSingleton();

    bool alreadyOpen = true;

    if (overlay == nullptr)
    {
        overlay.reset (new PermissionsOverlay (overlayGuard));
        alreadyOpen = false;
    }

    overlay->requests.push_back (std::move (request));

    if (! alreadyOpen)
        overlay->open();
}

bool RuntimePermissions::isRequired (PermissionID /*permission*/)
{
    return getAndroidSDKVersion() >= 23;
}

bool RuntimePermissions::isGranted (PermissionID permission)
{
    auto* env = getEnv();

    auto requestedPermission = jucePermissionToAndroidPermission (permission);
    int result = env->CallIntMethod (getAppContext().get(), AndroidContext.checkCallingOrSelfPermission,
                                     javaString (requestedPermission).get());

    return result == 0 /* PERMISSION_GRANTED */;
}

} // namespace juce

{'repo_name': 'juce-framework/JUCE', 'stars': '2212', 'repo_language': 'C++', 'file_name': 'include_juce_data_structures.mm', 'mime_type': 'text/x-c', 'hash': -6783889957318811311, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* internal interface for observing CSS style sheet loads */

#ifndef nsICSSLoaderObserver_h___
#define nsICSSLoaderObserver_h___

#include "nsISupports.h"

#define NS_ICSSLOADEROBSERVER_IID                    \
  {                                                  \
    0xf51fbf2c, 0xfe4b, 0x4a15, {                    \
      0xaf, 0x7e, 0x5e, 0x20, 0x64, 0x5f, 0xaf, 0x58 \
    }                                                \
  }

namespace mozilla {
class StyleSheet;
}

class nsICSSLoaderObserver : public nsISupports {
 public:
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICSSLOADEROBSERVER_IID)

  /**
   * StyleSheetLoaded is called after aSheet is marked complete and before any
   * load events associated with aSheet are fired.
   * @param aSheet the sheet that was loaded. Guaranteed to always be
   *        non-null, even if aStatus indicates failure.
   * @param aWasAlternate whether the sheet was an alternate.  This will always
   *        match the value LoadStyleLink or LoadInlineStyle returned in
   *        aIsAlternate if one of those methods were used to load the sheet,
   *        and will always be false otherwise.
   * @param aStatus is a success code if the sheet loaded successfully and a
   *        failure code otherwise.  Note that successful load of aSheet
   *        doesn't indicate anything about whether the data actually parsed
   *        as CSS, and doesn't indicate anything about the status of any child
   *        sheets of aSheet.
   */
  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet, bool aWasAlternate,
                              nsresult aStatus) = 0;
};

NS_DEFINE_STATIC_IID_ACCESSOR(nsICSSLoaderObserver, NS_ICSSLOADEROBSERVER_IID)

#endif  // nsICSSLoaderObserver_h___

{'repo_name': 'MrAlex94/Waterfox', 'stars': '1467', 'repo_language': 'None', 'file_name': 'scope-002a.css', 'mime_type': 'text/plain', 'hash': -6012499980850675061, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ProjectWorkspace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_mpw.xsd">

  <SchemaVersion>1.0</SchemaVersion>

  <Header>### uVision Project, (C) Keil Software</Header>

  <WorkspaceName>WorkSpace</WorkspaceName>

  <project>
    <PathAndName>.\Project_50230_IAP.uvproj</PathAndName>
  </project>

  <project>
    <PathAndName>.\Project_50230_AP.uvproj</PathAndName>
    <NodeIsActive>1</NodeIsActive>
  </project>

</ProjectWorkspace>

{'repo_name': 'pok3r-custom/pok3r_re_firmware', 'stars': '191', 'repo_language': 'Assembly', 'file_name': 'a.html', 'mime_type': 'text/html', 'hash': 1739519766248038425, 'source_dataset': 'data'}


name: Deploy docs to website

on:
  push:
    branches:
      - master
      - '[0-9]+.[0-9]+'
    paths:
      - 'mkdocs.yml'
      - 'docs/**'

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2.1.1
    - name: Set up Python 3.x
      uses: actions/setup-python@v1
      with:
        python-version: '3.x'
    - name: Display Python version
      run: python -c "import sys; print(sys.version)"
    - name: Install docs dependencies
      run: pip install -r docs/requirements.txt
    - name: Spin up RedisGears container
      run: docker run -d --rm --name redisgears -p 6379:6379 redislabs/redisgears:edge
    - name: Test code snippets
      run: python -m pytest -s -v docs/snippets
    - name: Get entire project
      run: git fetch -t
    - name: Build docs
      run: mkdocs build
    - uses: jakejarvis/s3-sync-action@v0.5.1
      with:
        args: --acl public-read --follow-symlinks
      env:
        AWS_S3_BUCKET: ${{ secrets.DOCS_AWS_S3_BUCKET }}
        AWS_ACCESS_KEY_ID: ${{ secrets.DOCS_AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.DOCS_AWS_SECRET_ACCESS_KEY }}
        DEST_DIR: ${{ secrets.DOCS_AWS_S3_DIR }}
        SOURCE_DIR: 'site'

{'repo_name': 'RedisGears/RedisGears', 'stars': '104', 'repo_language': 'C', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 1808493527589832488, 'source_dataset': 'data'}


/* @migen@ */
/*
**==============================================================================
**
** WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. PLEASE DO NOT EDIT.
**
**==============================================================================
*/
#ifndef _DerivedAssoc_h
#define _DerivedAssoc_h

#include <MI.h>
#include "BaseAssoc.h"
#include "Widget.h"
#include "Gadget.h"

/*
**==============================================================================
**
** DerivedAssoc [XYZ_DerivedAssoc]
**
** Keys:
**
**==============================================================================
*/

typedef struct _DerivedAssoc /* extends XYZ_BaseAssoc */
{
    MI_Instance __instance;
    /* BaseAssoc properties */
    Widget_ConstRef Left;
    Gadget_ConstRef Right;
    /* DerivedAssoc properties */
}
DerivedAssoc;

typedef struct _DerivedAssoc_Ref
{
    DerivedAssoc* value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
DerivedAssoc_Ref;

typedef struct _DerivedAssoc_ConstRef
{
    MI_CONST DerivedAssoc* value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
DerivedAssoc_ConstRef;

typedef struct _DerivedAssoc_Array
{
    struct _DerivedAssoc** data;
    MI_Uint32 size;
}
DerivedAssoc_Array;

typedef struct _DerivedAssoc_ConstArray
{
    struct _DerivedAssoc MI_CONST* MI_CONST* data;
    MI_Uint32 size;
}
DerivedAssoc_ConstArray;

typedef struct _DerivedAssoc_ArrayRef
{
    DerivedAssoc_Array value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
DerivedAssoc_ArrayRef;

typedef struct _DerivedAssoc_ConstArrayRef
{
    DerivedAssoc_ConstArray value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
DerivedAssoc_ConstArrayRef;

MI_EXTERN_C MI_CONST MI_ClassDecl DerivedAssoc_rtti;

MI_INLINE MI_Result MI_CALL DerivedAssoc_Construct(
    DerivedAssoc* self,
    MI_Context* context)
{
    return MI_ConstructInstance(context, &DerivedAssoc_rtti,
        (MI_Instance*)&self->__instance);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Clone(
    const DerivedAssoc* self,
    DerivedAssoc** newInstance)
{
    return MI_Instance_Clone(
        &self->__instance, (MI_Instance**)newInstance);
}

MI_INLINE MI_Boolean MI_CALL DerivedAssoc_IsA(
    const MI_Instance* self)
{
    MI_Boolean res = MI_FALSE;
    return MI_Instance_IsA(self, &DerivedAssoc_rtti, &res) == MI_RESULT_OK && res;
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Destruct(DerivedAssoc* self)
{
    return MI_Instance_Destruct(&self->__instance);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Delete(DerivedAssoc* self)
{
    return MI_Instance_Delete(&self->__instance);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Post(
    const DerivedAssoc* self,
    MI_Context* context)
{
    return MI_PostInstance(context, &self->__instance);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Set_Left(
    DerivedAssoc* self,
    const Widget* x)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        0,
        (MI_Value*)&x,
        MI_REFERENCE,
        0);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_SetPtr_Left(
    DerivedAssoc* self,
    const Widget* x)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        0,
        (MI_Value*)&x,
        MI_REFERENCE,
        MI_FLAG_BORROW);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Clear_Left(
    DerivedAssoc* self)
{
    return self->__instance.ft->ClearElementAt(
        (MI_Instance*)&self->__instance,
        0);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Set_Right(
    DerivedAssoc* self,
    const Gadget* x)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        1,
        (MI_Value*)&x,
        MI_REFERENCE,
        0);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_SetPtr_Right(
    DerivedAssoc* self,
    const Gadget* x)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        1,
        (MI_Value*)&x,
        MI_REFERENCE,
        MI_FLAG_BORROW);
}

MI_INLINE MI_Result MI_CALL DerivedAssoc_Clear_Right(
    DerivedAssoc* self)
{
    return self->__instance.ft->ClearElementAt(
        (MI_Instance*)&self->__instance,
        1);
}

/*
**==============================================================================
**
** DerivedAssoc provider function prototypes
**
**==============================================================================
*/

/* The developer may optionally define this structure */
typedef struct _DerivedAssoc_Self DerivedAssoc_Self;

MI_EXTERN_C void MI_CALL DerivedAssoc_Load(
    DerivedAssoc_Self** self,
    MI_Module_Self* selfModule,
    MI_Context* context);

MI_EXTERN_C void MI_CALL DerivedAssoc_Unload(
    DerivedAssoc_Self* self,
    MI_Context* context);

#endif /* _DerivedAssoc_h */

{'repo_name': 'microsoft/omi', 'stars': '195', 'repo_language': 'C', 'file_name': 'server.h', 'mime_type': 'text/x-c', 'hash': 8459314893913935896, 'source_dataset': 'data'}


.nh
.TH "X86-MFENCE" "7" "May 2019" "TTMO" "Intel x86-64 ISA Manual"
.SH NAME
MFENCE - MEMORY FENCE
.TS
allbox;
l
l .
T{
Opcode Instruction Op/ 64\-Bit Compat/ Description En Mode Leg Mode NP 0F AE F0 MFENCE ZO Valid Valid Serializes load and store operations.
T}
.TE

.SH INSTRUCTION OPERAND ENCODING
.TS
allbox;
l
l .
T{
Op/En Operand 1 Operand 2 Operand 3 Operand 4 ZO NA NA NA NA
T}
.TE

.SH DESCRIPTION
.PP
Performs a serializing operation on all load\-from\-memory and
store\-to\-memory instructions that were issued prior the MFENCE
instruction. This serializing operation guarantees that every load and
store instruction that precedes the MFENCE instruction in program order
becomes globally visible before any load or store instruction that
follows the MFENCE instruction.1 The MFENCE instruction is ordered with
respect to all load and store instructions, other MFENCE instructions,
any LFENCE and SFENCE instructions, and any serializing instructions
(such as the CPUID instruction). MFENCE does not serialize the
instruction stream.

.PP
.RS

.PP
1\&. A load instruction is considered to become globally visible when
the value to be loaded into its destination register is determined.

.RE

.PP
Weakly ordered memory types can be used to achieve higher processor
performance through such techniques as out\-of\-order issue, speculative
reads, write\-combining, and write\-collapsing. The degree to which a
consumer of data recognizes or knows that the data is weakly ordered
varies among applications and may be unknown to the producer of this
data. The MFENCE instruction provides a performance\-efficient way of
ensuring load and store ordering between routines that produce
weakly\-ordered results and routines that consume that data.

.PP
Processors are free to fetch and cache data speculatively from regions
of system memory that use the WB, WC, and WT memory types. This
speculative fetching can occur at any time and is not tied to
instruction execution. Thus, it is not ordered with respect to
executions of the MFENCE instruction; data can be brought into the
caches speculatively just before, during, or after the execution of an
MFENCE instruction.

.PP
This instruction’s operation is the same in non\-64\-bit modes and 64\-bit
mode.

.PP
Specification of the instruction's opcode above indicates a ModR/M byte
of F0. For this instruction, the processor ignores the r/m field of the
ModR/M byte. Thus, MFENCE is encoded by any opcode of the form 0F AE Fx,
where x is in the range 0\-7.

.SH OPERATION
.PP
.RS

.nf
Wait\_On\_Following\_Loads\_And\_Stores\_Until(preceding\_loads\_and\_stores\_globally\_visible);

.fi
.RE

.SH INTEL C/C++ COMPILER INTRINSIC EQUIVALENT
.PP
.RS

.nf
void \_mm\_mfence(void)

.fi
.RE

.SH EXCEPTIONS (ALL MODES OF OPERATION)
.PP
#UD If CPUID.01H:EDX.SSE2[bit 26] = 0.

.PP
If the LOCK prefix is used.

.SH SEE ALSO
.PP
x86\-manpages(7) for a list of other x86\-64 man pages.

.SH COLOPHON
.PP
This UNOFFICIAL, mechanically\-separated, non\-verified reference is
provided for convenience, but it may be incomplete or broken in
various obvious or non\-obvious ways. Refer to Intel® 64 and IA\-32
Architectures Software Developer’s Manual for anything serious.

.br
This page is generated by scripts; therefore may contain visual or semantical bugs. Please report them (or better, fix them) on https://github.com/ttmo-O/x86-manpages.

.br
MIT licensed by TTMO 2020 (Turkish Unofficial Chamber of Reverse Engineers - https://ttmo.re).

{'repo_name': 'ttmo-O/x86-manpages', 'stars': '169', 'repo_language': 'Roff', 'file_name': 'tag-content-uppercaser.sh', 'mime_type': 'text/x-shellscript', 'hash': -6204834743478159704, 'source_dataset': 'data'}


module Switchboard
  module Commands
    class Roster
      class Add < Switchboard::Command
        description "Add a JID to your roster"

        def self.run!
          switchboard = Switchboard::Client.new(Switchboard::Settings.new, false)

          switchboard.on_roster_loaded do
            # add the server as a contact if it wasn't already added
            ARGV.each do |jid|
              if roster.find(jid).empty?
                puts "Adding #{jid} to my roster..."
                roster.add(jid, nil, true)
              end
            end
          end

          switchboard.plug!(AutoAcceptJack)

          switchboard.run!
        end
      end
    end
  end
end

{'repo_name': 'mojodna/switchboard', 'stars': '136', 'repo_language': 'Ruby', 'file_name': 'pep.rb', 'mime_type': 'text/x-ruby', 'hash': -3142127624905431914, 'source_dataset': 'data'}


# SPDX-License-Identifier: GPL-2.0

config A
	bool "A"
	help
	  This is a new symbol.

choice
	prompt "Choice ?"
	depends on A
	help
	  "depends on A" has been newly added.

config CHOICE_B
	bool "Choice B"

config CHOICE_C
	bool "Choice C"
	help
	  This is a new symbol, so should be asked.

endchoice

choice
	prompt "Choice2 ?"

config CHOICE_D
	bool "Choice D"

config CHOICE_E
	bool "Choice E"

config CHOICE_F
	bool "Choice F"
	depends on A
	help
	  This is a new symbol, so should be asked.

endchoice

{'repo_name': '150balbes/Amlogic_s905-kernel', 'stars': '124', 'repo_language': 'C', 'file_name': 'stf.c', 'mime_type': 'text/x-c', 'hash': 6610901593309526033, 'source_dataset': 'data'}


Solution Architecture and Tools: Lambda

Notes

TBD

{'repo_name': 'stelligent/devops-essentials', 'stars': '125', 'repo_language': 'HTML', 'file_name': 'bootstrap.js', 'mime_type': 'text/plain', 'hash': -7886976965392136548, 'source_dataset': 'data'}