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

using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using System.Threading;
using System.Collections;
using System.Xml;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;

namespace Microsoft.Build.UnitTests.BackEnd
{
    /*
     * Class:   OnErrorHandling
     *
     * Tests that exercise the <OnError> tag.
     */
    [TestClass]
    sealed public class OnError_Tests
    {
        /*
         * Method:  Basic
         *
         * Construct a simple OnError tag.
         */
        [TestMethod]
        public void Basic()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
        }

        /// <summary>
        /// Target items and properties should be published to the project level even when a task that
        /// outputs them fails. (Of course the task must have populated its property before it errors.)
        /// Then these items and properties should be visible to the onerror targets.
        /// </summary>
        [TestMethod]
        public void FailingTaskStillPublishesOutputs()
        {
            MockLogger l = new MockLogger();

            string resx = Path.Combine(Path.GetTempPath(), "FailingTaskStillPublishesOutputs.resx");

            try
            {
                File.WriteAllText(resx, @"
                    <root>
                      <resheader name=""resmimetype"">
                        <value>text/microsoft-resx</value>
                      </resheader>
                      <resheader name=""version"">
                        <value>2.0</value>
                      </resheader>
                      <resheader name=""reader"">
                        <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <resheader name=""writer"">
                        <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <data name=""a"">
                        <value>aa</value>
                      </data>
                      <data name=""b"">
                        <value>bb</value>
                      </data>
                    </root>");

                Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
                    <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                        <Target Name='Build'>

                            <GenerateResource
                                ExecuteAsTool='false'
                                Sources='" + resx + @"'
                                StronglyTypedLanguage='!@:|'>
                                    <Output TaskParameter='FilesWritten' ItemName='FilesWrittenItem'/>
                                    <Output TaskParameter='FilesWritten' PropertyName='FilesWrittenProperty'/>
                            </GenerateResource>

                            <OnError ExecuteTargets='ErrorTarget'/>
                        </Target>

                        <Target Name='ErrorTarget'>
                            <Message Text='[@(fileswrittenitem)]'/>
                            <Message Text='[$(fileswrittenproperty)]'/>
                        </Target>
                    </Project>"))));

                ProjectInstance p = project.CreateProjectInstance();
                p.Build(new string[] { "Build" }, new ILogger[] { l });

                string resource = Path.ChangeExtension(resx, ".resources");

                Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
                l.AssertLogContains("[" + resource + "]", "[" + resource + "]");

                // And outputs are visible at the project level
                Assert.AreEqual(resource, Helpers.MakeList(p.GetItems("FilesWrittenItem"))[0].EvaluatedInclude);
                Assert.AreEqual(resource, p.GetPropertyValue("FilesWrittenProperty"));

                p = project.CreateProjectInstance();

                // But are gone after resetting of course
                Assert.AreEqual(0, Helpers.MakeList(p.GetItems("FilesWrittenItem")).Count);
                Assert.AreEqual(String.Empty, p.GetPropertyValue("FilesWrittenProperty"));
            }
            finally
            {
                File.Delete(resx);
            }
        }

        /// <summary>
        /// Target items and properties should be published to the project level when an OnError
        /// target runs, and those items and properties should be visible to the OnError targets.
        /// </summary>
        [TestMethod]
        public void OnErrorSeesPropertiesAndItemsFromFirstTarget()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>

                   <Target Name='Build'>
                      <!-- Create a bunch of items and properties -->
                      <CreateItem Include='a1'>
                        <Output ItemName='i1' TaskParameter='Include'/>
                      </CreateItem>
                      <ItemGroup>
                        <i1 Include='a2'/>
                      </ItemGroup>
                      <CreateProperty Value='v1'>
                        <Output PropertyName='p1' TaskParameter='Value'/>
                      </CreateProperty>
                      <PropertyGroup>
                        <p2>v2</p2>
                      </PropertyGroup>

                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='ErrorTarget'/>
                   </Target>

                   <Target Name='ErrorTarget'>
                      <Message Text='[@(i1)][$(p1)][$(p2)]'/>
                   </Target>

                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            l.AssertLogContains("[a1;a2][v1][v2]");
        }

        /*
         * Method:  TwoExecuteTargets
         *
         * Make sure two execute targets can be called.
         */
        [TestMethod]
        public void TwoExecuteTargets()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='CleanUp2'>
                      <Message Text='CleanUp2-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp;CleanUp2'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp2-was-called") != -1), "The CleanUp2 target should have been called.");
        }

        /*
         * Method:  TwoOnErrorClauses
         *
         * Make sure two OnError clauses can be used.
         */
        [TestMethod]
        public void TwoOnErrorClauses()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='CleanUp2'>
                      <Message Text='CleanUp2-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp'/>
                      <OnError ExecuteTargets='CleanUp2'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp2-was-called") != -1), "The CleanUp2 target should have been called.");
        }

        /*
         * Method:  DependentTarget
         *
         * Make sure that a target that is a dependent of a target called because of an
         * OnError clause is called
         */
        [TestMethod]
        public void DependentTarget()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp' DependsOnTargets='CleanUp2'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='CleanUp2'>
                      <Message Text='CleanUp2-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp2-was-called") != -1), "The CleanUp2 target should have been called.");
        }

        /*
         * Method:  ErrorInChildIsHandledInParent
         *
         * If a target is dependent on a child target and that child target errors,
         * then the parent's OnError clauses should fire.
         */
        [TestMethod]
        public void ErrorInChildIsHandledInParent()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='BuildStep1'>
                      <Error Text='Error-in-build-step-1.'/>
                   </Target>
                   <Target Name='Build' DependsOnTargets='BuildStep1'>
                      <OnError ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'BuildStep1' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Error-in-build-step-1") != -1), "The BuildStep1 target should have been called.");
        }

        /*
         * Method:  NonExistentExecuteTarget
         *
         * Construct a simple OnError tag.
         */
        [TestMethod]
        public void NonExistentExecuteTarget()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 2, "Expected at least one error because 'Build' failed and one error because 'CleanUp' didn't exist.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") == -1), "The CleanUp target should not have been called.");
        }

        /*
         * Method:  TrueCondition
         *
         * Test the case when the result of the condition is 'true'
         */
        [TestMethod]
        public void TrueCondition()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError Condition=""'A'!='B'"" ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
        }

        /*
         * Method:  FalseCondition
         *
         * Test the case when the result of the condition is 'false'
         */
        [TestMethod]
        public void FalseCondition()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError Condition=""'A'=='B'"" ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") == -1), "The CleanUp target should not have been called.");
        }

        /*
         * Method:  PropertiesInExecuteTargets
         *
         * Make sure that properties in ExecuteTargets are properly expanded.
         */
        [TestMethod]
        public void PropertiesInExecuteTargets()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <PropertyGroup>
                     <Part1>Clean</Part1>
                     <Part2>Up</Part2>
                   </PropertyGroup>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError Condition=""'A'!='B'"" ExecuteTargets='$(Part1)$(Part2)'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
        }

        /*
         * Method:  ErrorTargetsContinueAfterErrorsInErrorHandler
         *
         * If an error occurs in an error handling target, then continue processing
         * remaining error targets
         */
        [TestMethod]
        public void ErrorTargetsContinueAfterErrorsInErrorHandler()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp1'>
                      <Message Text='CleanUp1-was-called.'/>
                      <Error Text='Error in CleanUp1.'/>
                   </Target>
                   <Target Name='CleanUp2'>
                      <Message Text='CleanUp2-was-called.'/>
                      <Error Text='Error in CleanUp2.'/>
                   </Target>
                   <Target Name='CleanUp3'>
                      <Message Text='CleanUp3-was-called.'/>
                      <Error Text='Error in CleanUp3.'/>
                   </Target>
                   <Target Name='CoreBuild'>
                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='CleanUp1;CleanUp2'/>
                   </Target>
                   <Target Name='Build' DependsOnTargets='CoreBuild'>
                      <OnError ExecuteTargets='CleanUp3'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 4, "Four build errors expect: One from CoreBuild and on each from the error handlers.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp1-was-called") != -1), "The CleanUp1 target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp2-was-called") != -1), "The CleanUp2 target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp3-was-called") != -1), "The CleanUp3 target should have been called.");
        }

        /*
         * Method:  ExecuteTargetIsMissing
         *
         * If an OnError specifies an ExecuteTarget that is missing, that's an error
         */
        [TestMethod]
        public void ExecuteTargetIsMissing()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <OnError Condition=""'A'!='B'"" ExecuteTargets='CleanUp'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 2, "Expected one error because 'Build' failed and one because 'CleanUp' doesn't exist.");
        }

        /*
         * Method:  CommentsAroundOnError
         *
         * Since there is special-case code to ignore comments around OnError blocks,
         * let's test this case.
         */
        [TestMethod]
        public void CommentsAroundOnError()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <Error Text='This is an error.'/>
                      <!-- Comment before OnError -->
                      <OnError Condition=""'A'!='B'"" ExecuteTargets='CleanUp'/>
                      <!-- Comment after OnError -->
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("CleanUp-was-called") != -1), "The CleanUp target should have been called.");
        }

        /*
         * Method:  CircularDependency
         *
         * Detect circular dependencies and break out.
         */
        [TestMethod]
        public void CircularDependency()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='Build'>
                      <Error Text='Error in Build-Target'/>
                      <OnError ExecuteTargets='Build'/>
                   </Target>
                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 2, "Expected one error because 'Build' failed and one error because of the circular dependency.");
        }

        /*
         * Method:  OutOfOrderOnError
         *
         * OnError clauses must come at the end of a Target, it can't be sprinkled in-between tasks. Catch this case.
         */
        [TestMethod]
        [ExpectedException(typeof(InvalidProjectFileException))]
        public void OutOfOrderOnError()
        {
            MockLogger l = new MockLogger();
            Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <Target Name='CleanUp'>
                      <Message Text='CleanUp-was-called.'/>
                   </Target>
                   <Target Name='Build'>
                      <OnError ExecuteTargets='CleanUp'/>
                      <Delete Files='__non__existent_file__'/>
                   </Target>
                </Project>"))));

            /* No build required */
        }

        #region Postbuild
        /*
         * Method:  PostBuildBasic
         *
         * Handle the basic post-build case where the user has asked for 'On_Success' and
         * none of the build steps fail.
         */
        [TestMethod]
        public void PostBuildBasic()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Nowhere)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 0, "Expected no error because 'Build' succeeded.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") != -1), "The GenerateSatellites target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") != -1), "The PostBuild target should have been called.");
        }

        /*
         * Method:  PostBuildOnSuccessWhereCompileFailed
         *
         * User asked for 'On_Success' but the compile step failed. We don't expect post-build
         * to be called.
         */
        [TestMethod]
        public void PostBuildOnSuccessWhereCompileFailed()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Compile)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-step-failed") != -1), "The Compile target should have failed.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") == -1), "The GenerateSatellites target should not have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") == -1), "The PostBuild target should not have been called.");
        }

        /*
         * Method:  PostBuildOnSuccessWhereGenerateSatellitesFailed
         *
         * User asked for 'On_Success' but the PostBuildOnSuccessWhereGenerateSatellitesFailed step
         * failed. We don't expect post-build to be called.
         */
        [TestMethod]
        public void PostBuildOnSuccessWhereGenerateSatellitesFailed()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.GenerateSatellites)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") != -1), "The GenerateSatellites target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-step-failed") != -1), "The GenerateSatellites target should have failed.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") == -1), "The PostBuild target should not have been called.");
        }

        /*
         * Method:  PostBuildAlwaysWhereCompileFailed
         *
         * User asked for 'Always' but the compile step failed. We expect the post-build
         * to be called.
         */
        [TestMethod]
        public void PostBuildAlwaysWhereCompileFailed()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("Always", FailAt.Compile)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-step-failed") != -1), "The Compile target should have failed.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") == -1), "The GenerateSatellites target should not have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") != -1), "The PostBuild target should have been called.");
        }

        /*
         * Method:  PostBuildFinalOutputChangedWhereCompileFailed
         *
         * User asked for 'Final_Output_Changed' but the Compile step failed.
         * We expect post-build to be called.
         */
        [TestMethod]
        public void PostBuildFinalOutputChangedWhereCompileFailed()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.Compile)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-step-failed") != -1), "The Compile target should have failed.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") == -1), "The GenerateSatellites target should not have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") == -1), "The PostBuild target should not have been called.");
        }

        /*
         * Method:  PostBuildFinalOutputChangedWhereGenerateSatellitesFailed
         *
         * User asked for 'Final_Output_Changed' but the GenerateSatellites step failed.
         * We expect post-build to be called because Compile succeeded (and wrote to the output).
         */
        [TestMethod]
        public void PostBuildFinalOutputChangedWhereGenerateSatellitesFailed()
        {
            MockLogger l = new MockLogger();
            Project p = new Project
            (
                XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.GenerateSatellites)))
            );

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.IsTrue(l.ErrorCount == 1, "Expected one error because 'Build' failed.");
            Assert.IsTrue((l.FullLog.IndexOf("ResGen-was-called") != -1), "The ResGen target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("Compile-was-called") != -1), "The Compile target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-was-called") != -1), "The GenerateSatellites target should have been called.");
            Assert.IsTrue((l.FullLog.IndexOf("GenerateSatellites-step-failed") != -1), "The GenerateSatellites target should have failed.");
            Assert.IsTrue((l.FullLog.IndexOf("PostBuild-was-called") != -1), "The PostBuild target should have been called.");
        }

        /*
         * The different places that PostBuildBuilder might be instructed to fail at
         */
        private enum FailAt
        {
            Compile,
            GenerateSatellites,
            Nowhere
        }

        /*
         * Method:  PostBuildBuilder
         *
         * Build a project file that mimics the fairly complex way we plan to use OnError
         * to handle all the different combinations of project failures and post-build
         * conditions.
         *
         */
        private static string PostBuildBuilder
        (
            string controlFlag,  // On_Success, Always, Final_Output_Changed
            FailAt failAt
        )
        {
            string compileStep = "";
            if (FailAt.Compile == failAt)
            {
                compileStep = "<Error Text='Compile-step-failed'/>";
            }

            string generateSatellites = "";
            if (FailAt.GenerateSatellites == failAt)
            {
                generateSatellites = "<Error Text='GenerateSatellites-step-failed'/>";
            }

            return String.Format(ObjectModelHelpers.CleanupFileContents(@"
                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                   <PropertyGroup>
                     <Flag>{0}</Flag>
                   </PropertyGroup>
                   <Target Name='ResGen'>
                      <Message Text='ResGen-was-called.'/>
                   </Target>
                   <Target Name='Compile'>
                      <Message Text='Compile-was-called.'/>
                      <RemoveDir Directories='c:\__Hopefully_Nonexistent_Directory__'/>
                      {1}
                      <CreateItem Include='Yes'>
                         <Output TaskParameter='Include' ItemName='FinalOutputChanged'/>
                      </CreateItem>
                   </Target>
                   <Target Name='GenerateSatellites'>
                      <Message Text='GenerateSatellites-was-called.'/>
                      {2}
                   </Target>
                   <Target Name='PostBuild'>
                      <Message Text='PostBuild-was-called.'/>
                   </Target>
                   <Target Name='PostBuildOnSuccess' Condition=""'$(Flag)'!='Final_Output_Changed'"" DependsOnTargets='PostBuild'>
                      <Message Text='PostBuildOnSuccess-was-called.'/>
                   </Target>
                   <Target Name='PostBuildOnOutputChange' Condition=""'$(Flag)_@(FinalOutputChanged)'=='Final_Output_Changed_Yes'"" DependsOnTargets='PostBuild'>
                      <Message Text='PostBuildOnOutputChange-was-called.'/>
                   </Target>
                   <Target Name='CoreBuildSucceeded' DependsOnTargets='PostBuildOnSuccess;PostBuildOnOutputChange'>
                      <Message Text='CoreBuildSucceeded-was-called.'/>
                   </Target>
                   <Target Name='CoreBuild' DependsOnTargets='ResGen;Compile;GenerateSatellites'>
                      <Message Text='CoreBuild-was-called.'/>
                      <OnError Condition=""'$(Flag)'=='Always'"" ExecuteTargets='PostBuild'/>
                      <OnError ExecuteTargets='PostBuildOnOutputChange'/>
                   </Target>
                   <Target Name='Build' DependsOnTargets='CoreBuild;CoreBuildSucceeded'>
                      <Message Text='Build-target-was-called.'/>
                   </Target>
                </Project>
                "), controlFlag, compileStep, generateSatellites);
        }
        #endregion
    }
}


text:
from .dbscan import (
    dbscan_labels,
    get_largest_dbscan_clusters,
    segment_dbscan,
    )

from .segRedStick import (
    get_red_mask,
    )

from .boundary import (
    boundary_of_center_object,
    boundary_of_drivemap,
    boundary_of_lowest_points,
    )

__all__ = [
    'dbscan_labels',
    'get_largest_dbscan_clusters',
    'segment_dbscan',

    'get_red_mask',

    'boundary_of_center_object',
    'boundary_of_drivemap',
    'boundary_of_lowest_points',
]

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shindig.common;

import org.apache.shindig.common.util.OpenSocialVersion;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;

import junit.framework.Assert;

/**
 * Tests utility class for Version strings
 *
 */
public class OpenSocialVersionTest {

  @Test
  public void createOpenSocialVersion(){
    OpenSocialVersion version = new OpenSocialVersion("1.2.3");
    Assert.assertEquals(1, version.major);
    Assert.assertEquals(2, version.minor);
    Assert.assertEquals(3, version.patch);
    Assert.assertEquals(version, new OpenSocialVersion("1.2.3"));
  }

  @Test
  public void testEquivalence(){
    OpenSocialVersion version = new OpenSocialVersion("1.2.3");
    OpenSocialVersion version2 = new OpenSocialVersion("1.2");
    Assert.assertTrue(version.isEquivalent(version2));

    version = new OpenSocialVersion("2");
    Assert.assertTrue(version.isEquivalent("2.2"));

    version = new OpenSocialVersion("3");
    Assert.assertTrue(!version.isEquivalent("2.2"));
  }

  @Test
  public void testEqualOrGreaterThan(){
    OpenSocialVersion version = new OpenSocialVersion("1.2.3");
    OpenSocialVersion version2 = new OpenSocialVersion("1.2");
    Assert.assertTrue(version.isEqualOrGreaterThan(version2));
    Assert.assertTrue(!version2.isEqualOrGreaterThan(version));

    version = new OpenSocialVersion("2");
    version2 = new OpenSocialVersion("2.2");
    Assert.assertTrue(!version.isEqualOrGreaterThan(version2));
    Assert.assertTrue(version2.isEqualOrGreaterThan(version));

    version = new OpenSocialVersion("2.2.48");
    version2 = new OpenSocialVersion("2.2.49");
    Assert.assertTrue(!version.isEqualOrGreaterThan(version2));
    Assert.assertTrue(version2.isEqualOrGreaterThan(version));

    version = new OpenSocialVersion("3");
    Assert.assertTrue(version.isEqualOrGreaterThan("2.2"));

    version = new OpenSocialVersion("3.1.18");
    Assert.assertTrue(version.isEqualOrGreaterThan("2.2"));
  }

  @Test
  public void testVersionSorting(){
    ArrayList<OpenSocialVersion> list = new ArrayList<OpenSocialVersion>();
    list.add(new OpenSocialVersion("2.2.48"));
    list.add(new OpenSocialVersion("9.0.1"));
    list.add(new OpenSocialVersion("1.2.48"));
    list.add(new OpenSocialVersion("2.3.48"));
    list.add(new OpenSocialVersion("2.2.455"));
    list.add(new OpenSocialVersion("9.0.0"));
    Collections.sort(list, OpenSocialVersion.COMPARATOR);
    for(int i =0;i < list.size()-1;i++){
      Assert.assertTrue(list.get(i+1).isEqualOrGreaterThan(list.get(i)));
    }
  }

}


text:
Zero Plugin
===========

The ``zero`` plugin allows you to null fields in files' metadata tags. Fields
can be nulled unconditionally or conditioned on a pattern match. For example,
the plugin can strip useless comments like "ripped by MyGreatRipper." This
plugin only affects files' tags; the beets database is unchanged.

To use the plugin, enable it by including ``zero`` in the ``plugins`` line of
your configuration file. To configure the plugin, use a ``zero:`` section in
your configuration file. Set ``fields`` to the (whitespace-separated) list of
fields to change. You can get the list of available fields by running ``beet
fields``.  To conditionally filter a field, use ``field: [regexp, regexp]`` to
specify regular expressions.

For example::

    zero:
        fields: month day genre comments
        comments: [EAC, LAME, from.+collection, 'ripped by']
        genre: [rnb, 'power metal']

If a custom pattern is not defined for a given field, the field will be nulled
unconditionally.

Note that the plugin currently does not zero fields when importing "as-is".


text:
from django.core.exceptions import ValidationError
from django.test import TestCase
from factory.fuzzy import FuzzyText

from djoyapp.models import Item, Material
from factory_djoy import CleanModelFactory

# Create a basic Factories for Item which can be used to test CleanModelFactory
# through because CleanModelFactory is abstract.
class SimpleItemFactory(CleanModelFactory):
    class Meta:
        model = Item

class SimpleItemFactoryGOC(CleanModelFactory):
    class Meta:
        model = Item
        django_get_or_create = ('name',)

class ItemFactory(CleanModelFactory):
    class Meta:
        model = Item

    name = FuzzyText(length=5)

class FixedItemFactory(CleanModelFactory):
    class Meta:
        model = Item

    name = 'thing'

class MaterialFactory(CleanModelFactory):
    class Meta:
        model = Material

class TestSimpleItemFactory(TestCase):
    """
    Assert that invalid Item instances that could be created by factory are
    caught by full_clean.
    """

    def test_happy(self):
        """
        SimpleItemFactory can have required fields passed as kwargs
        """
        result = SimpleItemFactory(name='tap')

        self.assertEqual(Item.objects.count(), 1)
        self.assertEqual(result, Item.objects.filter(name='tap').first())

    def test_happy_build(self):
        """
        SimpleItemFactory can be built with invalid data
        """
        result = SimpleItemFactory.build()

        self.assertEqual(Item.objects.count(), 0)
        self.assertEqual(result.name, '')

    def test_happy_build_save(self):
        """
        SimpleItemFactory built instance can be saved to database
        """
        item = SimpleItemFactory.build()

        result = item.save()

        self.assertIsNone(result)
        self.assertEqual(Item.objects.count(), 1)

    def test_happy_build_not_clean(self):  # noqa
        """
        SimpleItemFactory can be built with invalid data, can not full clean
        """
        item = SimpleItemFactory.build()

        with self.assertRaises(ValidationError) as cm:
            item.full_clean()

        self.assertEqual(Item.objects.count(), 0)
        self.assertEqual(list(cm.exception.error_dict), ['name'])

    # Invalidation cases

    def test_missing_name(self):  # noqa
        """
        SimpleItemFactory does not autogenerate name and so fails validation.
        This is the main test for the outputting of the extra information in
        RuntimeError.
        """
        with self.assertRaises(RuntimeError) as cm:
            SimpleItemFactory()

        self.assertEqual(
            str(cm.exception),
            'Error building <class \'djoyapp.models.Item\'> with SimpleItemFactory.\n'
            'Bad values:\n'
            '  name: ""\n',
        )

    def test_no_get_or_create(self):  # noqa
        """
        CleanModelFactory does not provide get_or_create
        """
        SimpleItemFactoryGOC(name='exist')

        with self.assertRaises(RuntimeError):
            SimpleItemFactory(name='exist')

        self.assertEqual(Item.objects.count(), 1)

    def test_name_too_long(self):
        """
        When name is too long then information about the failing field is added
        to the stack trace.
        """
        with self.assertRaises(RuntimeError) as cm:
            SimpleItemFactory(name='__name__')

        self.assertIn('  name: "__name__"\n', str(cm.exception))

class TestItemFactory(TestCase):

    def test_make_single(self):
        """
        ItemFactory can generate a name by default, that name is valid
        """
        result = ItemFactory()

        self.assertEqual(Item.objects.count(), 1)
        self.assertEqual(result, Item.objects.first())

    def test_make_multi(self):
        """
        ItemFactory can generate multiple items
        """
        ItemFactory.create_batch(2)  # act

        self.assertEqual(Item.objects.count(), 2)

class TestFixedItemFactory(TestCase):

    def test_make_single(self):
        """
        FixedItemFactory makes Items with the same default name
        """
        result = FixedItemFactory()

        self.assertEqual(Item.objects.count(), 1)
        self.assertEqual(result, Item.objects.filter(name='thing').first())

    def test_duplicate(self):  # noqa
        """
        FixedItemFactory can not create batch because duplicate name values
        """
        with self.assertRaises(RuntimeError) as cm:
            FixedItemFactory.create_batch(2)

        self.assertIn('  name: "thing"\n', str(cm.exception))

    def test_happy_build_no_name(self):
        """
        FixedItemFactory can be used to create an Item with an empty
        """
        item = FixedItemFactory.build(name='')

        result = item.save()

        self.assertIsNone(result)
        self.assertEqual(Item.objects.filter(name='').count(), 1)
        self.assertEqual(item.name, '')

class TestMaterialFactory(TestCase):

    def test_make_single(self):
        MaterialFactory(name='paper', strength=1)  # act

    def test_error_all(self):
        with self.assertRaises(RuntimeError) as cm:
            MaterialFactory(name='feather', strength=200)

        self.assertIn('  __all__: obj.clean() failed\n', str(cm.exception))


text:
                Add Certificate

        <list-search
                class="pull-right"
                data-filters="filters"
                data-options="itemsPerPageOptions"
                data-items="itemsPerPage"
        ></list-search>

<konga-loader ng-if="loading && !items.length"></konga-loader>

                        {{item.api.name}}

                                The API does not exist anymore.

                    {{item.health_check_endpoint}}

                        {{item.notification_endpoint}}

                        {{moment(item.createdAt).format("MMM DD YYYY @h:mm")}}

                        //

                        <button class="btn btn-danger btn-link" ng-click="deleteItem(item)">

                            Delete
                        </button>

                        No data found...

                        Loading items...


text:
module.exports = (sequelize, Sequelize) => sequelize.define("CustomCommand", {
    id: {type: Sequelize.INTEGER.UNSIGNED, primaryKey: true, unique: true, autoIncrement: true},
    trigger: {type: Sequelize.STRING(191), allowNull: false, unique: true},
    message: {type: Sequelize.STRING, allowNull: false},
    status: {type: Sequelize.BOOLEAN, defaultValue: true},
    senderinfo: {type: Sequelize.BOOLEAN, defaultValue: true, allowNull: false},
    allowMention: {type: Sequelize.BOOLEAN, defaultValue: true, allowNull: false}
}, {
    underscored: true,
    tableName: 'customcommands'
});


text:
class CreateMfgOrderxOrders < ActiveRecord::Migration
  def change
    create_table :mfg_orderx_orders do |t|
      t.integer :rfq_id
      t.integer :quote_id
      t.string :wfid
      t.date :order_date
      t.date :delivery_date
      t.date :shipping_date
      t.integer :qty
      t.text :order_requirement
      t.boolean :expedite, :default => false
      t.boolean :cancelled, :default => false
      t.boolean :completed, :default => false
      t.integer :last_updated_by_id
      t.string :customer_po
      t.integer :executioner_id
      t.boolean :sample_required, :default => false

      t.timestamps
    end

    add_index :mfg_orderx_orders, :quote_id
    add_index :mfg_orderx_orders, :customer_po
    add_index :mfg_orderx_orders, :rfq_id
    add_index :mfg_orderx_orders, :wfid
  end
end


text:
@implementation MSGroupedTableViewFooterView

#pragma mark - MSTableViewHeaderFooterView

- (void)initialize
{
    [super initialize];
    self.textLabel.numberOfLines = 0;
    self.textLabel.font = self.class.defaultTextLabelFont;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_6_0
    self.textLabel.textAlignment = NSTextAlignmentCenter;
#else
    self.textLabel.textAlignment = UITextAlignmentCenter;
#endif
    self.detailTextLabel.hidden = YES;

#if defined(LAYOUT_DEBUG)
    self.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
    self.textLabel.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
#endif
}

+ (CGSize)padding
{
    CGFloat horizontalPadding = ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 54.0 : 20.0);
    CGFloat verticalPadding = 8.0;
    return CGSizeMake(horizontalPadding, verticalPadding);
}

+ (UIFont *)defaultTextLabelFont
{
    return [UIFont systemFontOfSize:15.0];
}

@end


text:
(function(factory) {

  if (typeof module !== 'undefined' && module && module.exports) { // Node.js & CommonJS
    var isIojs = parseInt(process.version.match(/^v(\d+)\./)[1]) >= 1;

    if (!isIojs) throw new Error('QUnit tests for node require io.js.');
    var qunit = (typeof(QUnit) == "undefined")? require('qunitjs') : QUnit;

    var dirname = (typeof(__dirname) == "undefined")? "./" : __dirname;
    var fs = require('fs');
    var path = require('path');
    var txt = fs.readFileSync(path.resolve(dirname,'fixtures.html'), 'utf8');

    var jsdom = require('jsdom');
    var doc = jsdom.jsdom(txt);
    var win = doc.defaultView;

    win.velm = require('../velm.js')(win);
    module.exports = factory(qunit, win);
  } else { // Browser
    factory(QUnit, window);
  }

})(function(QUnit, window) {

  var document = window.document;
  var velm = window.velm;

    function regExp(className) {
      return new RegExp('(^|\\s+)' + className + '(?=($|\\s+))');
    }

    function hasClass(el, className) {
      if (typeof(el) == 'string')
        el = document.querySelector(el);

      if (el.classList) {
        return el.classList.contains(className);
      } else if (el.className) {
        return !!~el.className.search(regExp(className));
      } else {
        throw new Error('Element ' + el + ' does not have classList or className properties.');
      }
    }

    function addClass(el, className) {
      if (typeof(el) == 'string')
        el = document.querySelector(el);

      if (hasClass(el, className)) return;

      if (el.classList) {
        el.classList.add(className);
      } else if (el.className) {
        el.className = el.className + ((el.className.trim().length > 0)? " " :"") + className;
      } else {
        throw new Error('Element ' + el + ' does not have classList or className properties.');
      }
    }

    function removeClass(el, className) {
      if (typeof(el) == 'string')
        el = document.querySelector(el);

      if (!hasClass(el, className)) return;

      if (el.classList) {
        el.classList.remove(className);
      } else if (el.className) {
        el.className = el.className.trim().replace(regExp(className), '');
      } else {
        throw new Error('Element ' + el + ' does not have classList or className properties.');
      }
    }

    function classList(el, arr) {
      if (typeof(el) == 'string')
        el = document.querySelector(el);

      if (arr && el.classList) { /*  New Setter */
        var last = el.classList.length - 1;
        for (var i=last; i >= 0; i--) {
          el.classList.remove(el.classList[i]);
        }

        for (var i=0; i < arr.length; i++) {
          el.classList.add(arr[i]);
        }

      } else if (arr && el.className) { /*  Old Setter */
          el.className = arr.join(' ');
      } else if (el.classList) { /* New Getter */
          return Array.prototype.slice.call(el.classList);
      } else if (el.className) { /* Old Getter */
          return el.className.split(/\s/);
      } else {
        throw new Error('Element ' + el + ' does not have classList or className properties.');
      }
    }

  Array.prototype.equals = Array.prototype.equals || function (array) {
    // if the other array is a falsy value, return
    if (!array)
      return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
      return false;

    for (var i = 0, l=this.length; i < l; i++) {
      // Check if we have nested arrays
      if (this[i] instanceof Array && array[i] instanceof Array) {
        // recurse into the nested arrays
        if (!this[i].equals(array[i]))
          return false;
        }
        else if (this[i] != array[i]) {
          // Warning - two different object instances will never be equal: {x:20} != {x:20}
          return false;
        }
    }
    return true;
  }

  QUnit.test('velm', function(assert) {
    assert.ok(velm != null, 'velm constructor exists');
    assert.ok(velm('div.fixture.text') != null, 'velm constructor accepts selector string');
    assert.ok(velm(document.querySelector('div.fixture.text')) != null, 'velm constructor accepts element');
  });

  QUnit.test('.text', function(assert) {
    var ui = {};

    velm('div.fixture.text')
      .text
      .to(ui, 'div');

    assert.equal(ui.div, "I'm a div.", "property returns text");

    ui.div = 'Hello world!';
    assert.equal(document.querySelector('div.fixture.text').innerText, "Hello world!", "assignment sets text");
  });

  QUnit.test('.html', function(assert) {
    var ui = {};

    velm('div.fixture.html')
      .html
      .to(ui, 'html');

    assert.equal(ui.html, "<b>I'm a div with HTML.</b>", "property returns html");

    ui.html = 'Hello world!';
    assert.equal(document.querySelector('div.fixture.html').innerHTML,"Hello world!", "assignment sets html");

  });

  QUnit.test('.classList', function(assert) {
    var ui = {};

    velm('div.fixture.clist')
      .classList
      .to(ui, 'classList');

    assert.ok(ui.classList.equals([ 'fixture', 'clist']), 'property returns classList');

    ui.classList = ['fixture', 'hello', 'world'];
    assert.ok(ui.classList.equals([ 'fixture', 'hello', 'world']), 'assignment sets classList');
  });

  QUnit.test('.hasClass', function(assert) {
    var ui = {};

    var div = document.querySelector('div.fixture.class');
    velm(div)
      .hasClass('on')
      .to(ui, 'on');

    assert.equal(ui.on, true, 'property returns true if class is present');

    ui.on = false;

    assert.ok(!hasClass(div,'on'), ' false assignment removes class');

    ui.on = true;
    assert.ok(hasClass(div,'on'), ' true assignment adds class');

    removeClass(div, 'on');
    assert.equal(ui.on, false, 'property returns false if class is not present');
  });

  QUnit.test('.noClass', function(assert) {
    var ui = {};
    var div = document.querySelector('div.fixture.class');

    velm(div)
      .noClass('off')
      .to(ui, 'on');

    assert.equal(ui.on, true,'property returns true if class is not present');

    ui.on = false;
    assert.ok(hasClass(div,'off'), ' false assignment adds class');

    ui.on = true;
    assert.ok(!hasClass(div,'off'), ' true assignment removes class');

    addClass(div, 'off');
    assert.equal(ui.on, false, 'property returns false if class is present');
  });

  QUnit.test('.attr', function(assert) {
    var ui = {};
    var div = document.querySelector('div.fixture.attr');

    velm(div)
      .attr('data-color')
      .to(ui, 'color');

    assert.equal(ui.color, null, 'property returns null or undefined if attribute is not present');

    ui.color = 'red';
    assert.equal(div.getAttribute('data-color'), 'red', 'assignment changes value of attribute');
    assert.equal(ui.color, 'red', 'property returns value of attribute');
  });

  QUnit.test('.hasTruthyAttr', function(assert) {
    var ui = {};
    var div = document.querySelector('div.fixture.hattr');

    velm(div)
      .hasTruthyAttr('data-display')
      .to(ui, 'display');

    assert.equal(ui.display, false, 'property returns false if attribute is not present');

    div.setAttribute('data-display', 'on');
    assert.equal(ui.display, true, 'property returns true if attribute is "yes"');

    div.setAttribute('data-display', '1');
    assert.equal(ui.display, true, 'property returns true if attribute is "1"');

    div.setAttribute('data-display', 'true');
    assert.equal(ui.display, true, 'property returns true if attribute is "true"');

    div.setAttribute('data-display', '');
    assert.equal(ui.display, true, 'property returns true if attribute is ""');

    div.setAttribute('data-display', 'no');
    assert.equal(ui.display, false, 'property returns false if attribute is "no"');

    div.setAttribute('data-display', '0');
    assert.equal(ui.display, false, 'property returns false if attribute is "0"');

    div.setAttribute('data-display', 'false');
    assert.equal(ui.display, false, 'property returns false if attribute is "false"');

    ui.display = true;
    assert.equal(ui.display, true, 'property can be set to true');
    assert.equal(div.getAttribute('data-display'), 'true', 'value of attribute is "true" when property is set to true');

    ui.display = false;
    assert.equal(ui.display, false, 'property can be set to false');
    assert.equal(div.getAttribute('data-display'), 'false', 'value of attribute is "false" when property is set to true');

  });

  QUnit.test('.noTruthyAttr', function(assert) {
    var ui = {};
    var div = document.querySelector('div.fixture.nattr');

    velm(div)
      .noTruthyAttr('data-display')
      .to(ui, 'display');

    assert.equal(ui.display, true, 'property returns true if attribute is not present');

    div.setAttribute('data-display', 'on');
    assert.equal(ui.display, false, 'property returns false if attribute is "yes"');

    div.setAttribute('data-display', '1');
    assert.equal(ui.display, false, 'property returns false if attribute is "1"');

    div.setAttribute('data-display', 'true');
    assert.equal(ui.display, false, 'property returns false if attribute is "true"');

    div.setAttribute('data-display', '');
    assert.equal(ui.display, false, 'property returns true if attribute is ""');

    div.setAttribute('data-display', 'no');
    assert.equal(ui.display, true, 'property returns true if attribute is "no"');

    div.setAttribute('data-display', '0');
    assert.equal(ui.display, true, 'property returns true if attribute is "0"');

    div.setAttribute('data-display', 'false');
    assert.equal(ui.display, true, 'property returns true if attribute is "false"');

    ui.display = true;
    assert.equal(ui.display, true, 'property can be set to true');
    assert.equal(div.getAttribute('data-display'), 'false', 'value of attribute is "false" when property is set to true');

    ui.display = false;
    assert.equal(ui.display, false, 'property can be set to false');
    assert.equal(div.getAttribute('data-display'), 'true', 'value of attribute is "false" when property is set to false');
  });

  QUnit.test('.textValue', function(assert) {
    var ui = {};
    var fixtures = [ 'input.fixture[type="text"]', 'input.fixture[type="password"]', 'textarea.fixture'];

    for (var i=0; i < fixtures.length; i++) {
      var input = document.querySelector(fixtures[i]);
      velm(input)
        .textValue
        .to(ui, 'text');

      assert.equal(ui.text, 'hello', 'property can be read');

      ui.text = 'bye';
      assert.equal(input.value, 'bye', 'property can be assigned');
    }

  });

  QUnit.test('.groupValue', function(assert) {
    var ui = {};
    var inputA = document.querySelector('input.fixture[type="radio"][value="A"]');
    var inputB = document.querySelector('input.fixture[type="radio"][value="B"]');

    velm(inputA)
      .groupValue
      .to(ui, 'choice');

    assert.equal(ui.choice, null, "property is null when no radio buttons checked");

    ui.choice = "A";
    assert.equal(inputA.checked, true, "input is checked when its value is equal to the property value");
    assert.equal(inputB.checked, false, "input is not checked when its value is not equal to the property value");

    ui.choice = null;
    assert.equal(inputA.checked, false, "input is not checked when property value is null");
    assert.equal(inputB.checked, false, "input is not checked when property value is null");
  });

  QUnit.test('.selectValue', function(assert) {
    var ui = {};
    var select = document.querySelector('select.fixture')

    velm(select)
      .selectValue
      .to(ui, 'selection');

    assert.equal(ui.selection, 'A', "property is the first value when no selection made");

    ui.selection = "A";
    assert.equal(select.value, "A", "changing property changes selection");
  });

  QUnit.load();
});


text:
import scalafix.v1._

import scala.meta._
import scala.meta.classifiers._
import scala.annotation.tailrec

package object fix {

  def show(tree: Tree)(implicit doc: SemanticDocument): Patch = {
    println("Tree.syntax: " + tree.syntax)
    println("Tree.structure: " + tree.structure)
    println("Tree.structureLabeled: " + tree.structureLabeled)
    println("Tree.symbol: " + tree.symbol)
    println()
    Patch.empty
  }

  implicit class TreeOps(private val self: Tree) extends AnyVal {
    @tailrec
    final def isDescendentOf[U](implicit classifier: Classifier[Tree, U]): Boolean =
      self.is[U] || {
        self.parent match {
          case None => false
          case Some(parent) => parent.isDescendentOf[U]
        }
      }
  }
}


text:
from django.db import models
from django.contrib.auth.models import User

class Account(models.Model):
    account_number = models.CharField(max_length=30)
    agency_number = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now=True)
    status = models.BooleanField(default="")
    accountant = models.ForeignKey(
        User,
        on_delete=models.CASCADE
    )

    class Meta:
        unique_together = ('accountant','account_number','agency_number')

class Cards(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.CharField(max_length=100)
    flag = models.CharField(max_length=100)
    status = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        cards = Cards.objects.filter(name=self.name)
        if len(cards) == 0:
            super(Cards, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = 'Card'
        verbose_name_plural = 'Cards'


text:
LIBNAME=graphics
COBJS=open.o draw.o fill.o color.o text.o \
  image.o make_img.o dump_img.o point_col.o sound.o events.o \
  subwindow.o
CAMLOBJS=graphics.cmo graphicsX11.cmo
LINKOPTS=-cclib "\"$(X11_LINK)\""
LDOPTS=-ldopt "$(X11_LINK)"

EXTRACFLAGS=$(X11_INCLUDES)

include ../Makefile

depend:
	gcc -MM $(CFLAGS) *.c | sed -e 's, /usr[^ ]*\.h,,g' > .depend
	../../boot/ocamlrun ../../tools/ocamldep *.mli *.ml >> .depend

include .depend


text:
import React, {Component} from 'react'

import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'
import {Apis, ApplicationCreate, Applications, Base, Login, Logout} from './app/components'
import {PageNotFound} from './app/components/Base/Errors'
import AuthManager from './app/data/AuthManager'
import qs from 'qs'

// import 'typeface-roboto'
import Utils from "./app/data/Utils";
import ConfigManager from "./app/data/ConfigManager";
import {MuiThemeProvider, createMuiTheme} from 'material-ui/styles';
import DarkTheme from './app/components/Shared/DarkTheme'
import LightTheme from './app/components/Shared/LightTheme'
const themes = [];

themes.push(createMuiTheme(LightTheme));
themes.push(createMuiTheme(DarkTheme));

// import './materialize.css'

/**
 * Render protected application paths
 */
class Protected extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showLeftMenu: false,
            themeIndex: 0,
        };
        this.environments = [];
        /* TODO: need to fix the header to avoid conflicting with messages ~tmkb*/
    }

    componentDidMount() {
        ConfigManager.getConfigs().environments.then(response => {
            this.environments = response.data.environments;
            this.handleEnvironmentQueryParam();
        }).catch(error => {
            console.error('Error while receiving environment configurations : ', error);
        });
    }

    /**
     * Change the environment with "environment" query parameter
     * @return {String} environment name in the query param
     */
    handleEnvironmentQueryParam() {
        let queryString = this.props.location.search;
        queryString = queryString.replace(/^\?/, '');
        /* With QS version up we can directly use {ignoreQueryPrefix: true} option */
        let queryParams = qs.parse(queryString);
        const environmentName = queryParams.environment;

        if (!environmentName || Utils.getEnvironment() === environmentName) {
            // no environment query param or the same environment
            return environmentName;
        }

        let environmentId = Utils.getEnvironmentID(this.environments, environmentName);
        if (environmentId === -1) {
            return environmentName;
        }

        let environment = this.environments[environmentId];
        Utils.setEnvironment(environment);
        return environmentName;
    }
    /**
     * Change the theme index incrementally
     */
    componentWillMount() {
        let storedThemeIndex = localStorage.getItem("themeIndex");
        if (storedThemeIndex) {
            this.setState({themeIndex: parseInt(storedThemeIndex)})
        }
    }
    setTheme() {
        this.setState({theme: themes[this.state.themeIndex % 3]});
        this.state.themeIndex++;
        localStorage.setItem("themeIndex", this.state.themeIndex);
    }

    render() {
        const environmentName = this.handleEnvironmentQueryParam();
        // Note: AuthManager.getUser() method is a passive check, which simply check the user availability in browser storage,
        // Not actively check validity of access token from backend
        if (AuthManager.getUser(environmentName)) {
            return (
                <MuiThemeProvider theme={themes[this.state.themeIndex % 2]}>
                    <Base setTheme={() => this.setTheme()}>
                        <Switch>
                            <Redirect exact from="/" to="/apis"/>
                            <Route path={"/apis"} component={Apis}/>
                            <Route path={"/applications"} component={Applications}/>
                            <Route path={"/application/create"} component={ApplicationCreate}/>
                            <Route component={PageNotFound}/>
                        </Switch>
                    </Base>
                </MuiThemeProvider>
            );
        }

        let params = qs.stringify({referrer: this.props.location.pathname});
        return (
            <Redirect to={{pathname: '/login', search: params}}/>
        );
    }
}

/**
 * Define base routes for the application
 */

const Store = (props) => {
    return (
        <Router basename="/store">
            <Switch>
                <Route path={"/login"} render={() => <Login appName={"store"} appLabel={"STORE"}/>}/>
                <Route path={"/logout"} component={Logout}/>
                <Route component={Protected}/>
            </Switch>
        </Router>
    );
}

export default Store;


text:
<?php

/**
 * A mock database model similiar to one one from lab3
 */
class Playlists extends MY_Model {

    // Constructor
    public function __construct() {
        parent::__construct('playlist', 'id');
    }

    public function getByCreator($which) {

        $this->db->where('creator', $which);
        $query = $this->db->get($this->_tableName);
        if ($query->num_rows() < 1)
            return array(); //returns an empty array so that the view doesn't break on 0 entry
        return $query->result_array();
    }

    public function getCreator($which) {
        $this->db->where('id', $which);
        $query = $this->db->get($this->_tableName);
        if ($query->num_rows() < 1)
            return -1;
        $result = $query->row_array();
        return $result['creator'];
    }
}


text:
export * from './prodlineResolve.service';
export * from './prodline.component';
export * from './prodlineList.component';
export * from './prodlineNew.component';
export * from './prodlineDetail.component';
export * from './prodlineHome.component';
export * from './prodline.routing';


text:
from tjson import ParseError

def parse(value):
    if ':s' not in value:
        raise ParseError

    return value.split(':s')[0]


text:
package com.mmall.concurrency.example.immutable;

import com.google.common.collect.Maps;
import com.mmall.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@NotThreadSafe
public class ImmutableExample1 {

    private final static Integer a = 1;
    private final static String b = "2";
    private final static Map<Integer, Integer> map = Maps.newHashMap();

    static {
        map.put(1, 2);
        map.put(3, 4);
        map.put(5, 6);
    }

    public static void main(String[] args) {
//        a = 2;
//        b = "3";
//        map = Maps.newHashMap();
        map.put(1, 3);
        log.info("{}", map.get(1));
    }

    private void test(final int a) {
//        a = 1;
    }
}


text:
#ifndef R_Z_NETWORK_H_
#define R_Z_NETWORK_H_
/**
 *  @addtogroup ldr_communication_serv
 *  @{
 *    @addtogroup z_family
 *    @{
 *      @addtogroup ldr_z_network_layer Z network layer
 *      Z network layer support receiving and sending bytes from
 *      Z protocol.
 *
 *      @{
 */

/*******************************************************************************
 * Includes
 ******************************************************************************/
#include "error_codes.h"
#include "t_basicdefinitions.h"
#include "t_z_network.h"
#include "t_communication_service.h"
#include "t_z_protocol.h"

/*******************************************************************************
 * Declaration of functions
 ******************************************************************************/
/**
 * Initializes the Z family network layer.
 *
 * @param [in]  Communication_p Communication module context.
 *
 * @retval  E_SUCCESS                   After successful execution.
 * @retval  E_FAILED_TO_INIT_COM_DEVICE Failed to initialize the communication
 *                                      device.
 */
ErrorCode_e Z_Network_Initialize(Communication_t *Communication_p);

/**
 * Shut down the Z family network layer.
 *
 * @param [in]  Communication_p Communication module context.
 *
 * @retval  E_SUCCESS After successful execution.
 */
ErrorCode_e Z_Network_Shutdown(const Communication_t *const Communication_p);

/**
 * Handler for received packets in Z protocol family.
 *
 * This callback function handles the received packets.
 *
 * @param [in] Data_p  Pointer to the received data.
 * @param [in] Length  Length of the received data.
 * @param [in] Param_p Extra parameters.
 *
 * @return none.
 */
void Z_Network_ReadCallback(const void *Data_p, const uint32 Length, void *Param_p);

/**
 * Handler function that is called after successful transmission of a packet.
 *
 * If new packet is ready for transmitting it starts
 * the transmission of the packet.
 *
 * @param [in] Data_p   Pointer to the data for transmitting.
 * @param [in] Length   Length of the received data.
 * @param [in] Param_p  Extra parameters.
 *
 * @return none.
 */

void Z_Network_WriteCallback(const void *Data_p, const uint32 Length, void *Param_p);

/**
 * Handler for receiving new data in Z protocol family.
 *
 * This function checks if new data has been received.
 *
 * @param [in]  Communication_p Communication module context.
 *
 * @return  none.
 */
void Z_Network_ReceiverHandler(Communication_t *Communication_p);

/**
 * Handler for sending new data in Z protocol family.
 *
 * This function checks if new data has been transmitted.
 *
 * @param [in]  Communication_p  Communication module context.
 * @param [in]  SendingContent_p Pointer to the sending context.
 *
 * @return  none.
 */
ErrorCode_e Z_Network_TransmiterHandler(Communication_t *Communication_p, Z_SendingContent_t *SendingContent_p);

/** @} */
/** @} */
/** @} */
#endif /*R_Z_NETWORK_H_*/


text:
<!doctype html>
<title>nyaa-explorer</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Christopher Kaster" />

<link href="lib/bootstrap-3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="style/main.css" rel="stylesheet" />

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

            </button>
            nyaa-explorer

                <form class="navbar-form" role="search">

                        <input type="text" class="form-control" placeholder="Search" id="search-field" />

                            <button class="btn btn-success" type="button" id="search-btn"></button>

                </form>

                    30


text:
//CakeJS.Database.Statement.StatementDecorator

//Types
import { StatementInterface } from 'Cake/Database/StatementInterface';
import { Type } from 'Cake/Database/Type';

//Utilities
import isEmpty from 'Cake/Utilities/isEmpty';
import isNumeric from 'Cake/Utilities/isEmpty';

export class StatementDecorator extends StatementInterface {
	constructor(statement = null, driver = null)
	{
		super();
		this._statement = statement;
		this._driver = driver;
	}

	bind(params, types)
	{
		if(isEmpty(params)){
			return;
		}

		for(var index in params){
			var value = params[index];
			var type = null;
			if(index in types){
				type = types[index];
			}
			this.bindValue(index, value, type);
		}
	}

	cast(value, type)
	{
		if(typeof type === 'string'){
			type = Type.build(type);
		}
		if(type instanceof Type){
			value = type.toDatabase(value, this._driver);
			type = type.toStatement(value, this._driver);
		}
		return [value, type];
	}
}


text:
Code of Conduct
===============

Team conduct
------------
* Be respectful
* Keep a friendly tone
* Be open to constructive criticism (we will be doing code reviews of every pull request)

Work conduct
------------
* Before starting work on an issue from the issue tracker, please, make sure there are no active pull requests referencing it.
* When you start working on an issue from issue tracker, please place a comment that you intend do so.
* Timebox your expectations for this work and update the issue/pull request regularly, so that if you say it will take you 2 days and in two weeks there hasn't been apparent progress, if another developer decides they would like to work on this, they can pick it up
* Be professional
* Review your own work after creating a pull and try to resolve any:
  * Build failures
  * Code issues reported by Sonar (unless these are false-positives)
  * Code indentation issues
  * Other issues you spot with your code
* When you open a new pull request:
  * Put the words `[in progress]` in the title, while the pull request is not yet ready for merging and remove these words, when done, so that it's clear when we can review and merge your pull
  * If this pull relates to an existing issue, please refer to it in your pull by mentioning it (for example, "This pull is for issue #123"), which will automatically link the pull to the issue.

General
-------
* Do your homework (when possible)
* Use our chat channel to ask for help [![RocketChat.Community.Channel](https://chat.carlspring.org/images/join-chat.svg)](https://chat.carlspring.org/channel/community)
* If you're new to the project:
 * Read:
   * [Getting Started Guide](https://strongbox.github.io/user-guide/getting-started.html)
   * [Building The Code](https://strongbox.github.io/developer-guide/building-the-code.html)
   * [Coding Convention](https://strongbox.github.io/developer-guide/coding-convention.html)
   * [Logging](https://strongbox.github.io/developer-guide/add-logging.html)
   * [Writing Tests](https://strongbox.github.io/developer-guide/writing-tests.html)
 * Have a general look around at the "Developer Guide" of our [wiki](https://strongbox.github.io/)
 * Look around the Github issue tracker and find some ["good first issue" and "help wanted"](https://github.com/strongbox/strongbox/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22+label%3A%22help+wanted%22) tasks


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Sabio.Web.Models.Requests
{
    public class AnnouncementUpdateRequest : AnnouncementAddRequest
    {
        [Required]
        public int Id { get; set; }
    }
}


text:
'use strict';

var gcm = require('node-gcm');

exports.getSender = function(config) {
  var options = config.android;
  // Create a sender using your Google Server API Key
  var sender = new gcm.Sender(options.apiKey);

  return function(device, payload, callback) {
    // payload MUST include title and message fields when using cordova PushPlugin on Android
    if (!payload || !payload.message || !payload.title) {
      return callback(new Error('GCM payload must include title and message fields'));
    } else if (device === 'mock') {
      return callback(null, {});
    }

    var messageData = {
      // TTL in seconds if device offline
      timeToLive: config.settings.timeoutInSeconds,
      // GCM payload parsed by PushPlugin
      data: payload
    };

    if (options.collapseKey) {
      // Collapse key for offline message grouping
      messageData.collapseKey = options.collapseKey;
    }

    var alert = new gcm.Message(messageData);

    var registrationIds = [];
    registrationIds.push(device);

    sender.sendNoRetry(alert, registrationIds, function(err, result) {
      return callback(err, result);
    });
  };
};


text:
<!DOCTYPE html>
<title>table is flex item</title>
<link rel="author" title="David Grogan" href="mailto:dgrogan@chromium.org">
<link rel="help" href="https://www.w3.org/TR/css-flexbox-1/#layout-algorithm" title="9. Flex Layout Algorithm">
<link rel="help" href="https://drafts.csswg.org/css-tables-3/#used-min-width-of-table">
<link rel="match" href="../reference/ref-filled-green-100px-square.xht">
<meta name="assert" content="Flex item table's min-content width is honored when it is larger than the table's specified min-width, and the sum of the flex base sizes are greater than the container's available size.">

Test passes if there is a filled green square and no red.


text:
import '../amp-nexxtv-player';
import {VideoEvents} from '../../../../src/video-interface';
import {listenOncePromise} from '../../../../src/event-helper';

describes.realWin(
  'amp-nexxtv-player',
  {
    amp: {
      extensions: ['amp-nexxtv-player'],
    },
  },
  env => {
    let win, doc;

    beforeEach(() => {
      win = env.win;
      doc = win.document;
    });

    async function getNexxtv(attributes, opt_responsive) {
      const nexxtv = doc.createElement('amp-nexxtv-player');

      for (const key in attributes) {
        nexxtv.setAttribute(key, attributes[key]);
      }
      nexxtv.setAttribute('width', '111');
      nexxtv.setAttribute('height', '222');
      if (opt_responsive) {
        nexxtv.setAttribute('layout', 'responsive');
      }
      doc.body.appendChild(nexxtv);
      await nexxtv.build();
      await nexxtv.layoutCallback();
      const nexxTimerIframe = nexxtv.querySelector('iframe');
      nexxtv.implementation_.handleNexxMessage_({
        origin: 'https://embed.nexx.cloud',
        source: nexxTimerIframe.contentWindow,
        data: JSON.stringify({cmd: 'onload'}),
      });
      return nexxtv;
    }

    it('renders nexxtv video player', async () => {
      const nexxtv = await getNexxtv({
        'data-mediaid': '71QQG852413DU7J',
        'data-client': '761',
      });
      const playerIframe = nexxtv.querySelector('iframe');
      expect(playerIframe).to.not.be.null;
      expect(playerIframe.src).to.equal(
        'https://embed.nexx.cloud/761/video/' +
          '71QQG852413DU7J?dataMode=static&platform=amp'
      );
    });

    it('renders player responsive', async () => {
      const nexxtv = await getNexxtv({
        'data-mediaid': '71QQG852413DU7J',
        'data-client': '761',
      });
      const playerIframe = nexxtv.querySelector('iframe');
      expect(playerIframe).to.not.be.null;
      expect(playerIframe.className).to.match(/i-amphtml-fill-content/);
    });

    it('removes iframe after unlayoutCallback', async () => {
      const nexxtv = await getNexxtv({
        'data-mediaid': '71QQG852413DU7J',
        'data-client': '761',
      });
      const playerIframe = nexxtv.querySelector('iframe');
      expect(playerIframe).to.not.be.null;

      const obj = nexxtv.implementation_;
      obj.unlayoutCallback();
      expect(nexxtv.querySelector('iframe')).to.be.null;
      expect(obj.iframe_).to.be.null;
    });

    it('should forward events from nexxtv-player to the amp element', async () => {
      const nexxtv = await getNexxtv({
        'data-mediaid': '71QQG852413DU7J',
        'data-client': '761',
      });
      const iframe = nexxtv.querySelector('iframe');
      await Promise.resolve();
      const p1 = listenOncePromise(nexxtv, VideoEvents.PLAYING);
      sendFakeMessage(nexxtv, iframe, {event: 'play'});
      await p1;
      const p2 = listenOncePromise(nexxtv, VideoEvents.MUTED);
      sendFakeMessage(nexxtv, iframe, {event: 'mute'});
      await p2;
      const p3 = listenOncePromise(nexxtv, VideoEvents.PAUSE);
      sendFakeMessage(nexxtv, iframe, {event: 'pause'});
      await p3;
      const p4 = listenOncePromise(nexxtv, VideoEvents.UNMUTED);
      sendFakeMessage(nexxtv, iframe, {event: 'unmute'});
      return p4;
    });

    function sendFakeMessage(nexxtv, iframe, command) {
      nexxtv.implementation_.handleNexxMessage_({
        origin: 'https://embed.nexx.cloud',
        source: iframe.contentWindow,
        data: command,
      });
    }
  }
);


text:
package alluxio.worker.block;

import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.Sessions;
import alluxio.StorageTierAssoc;
import alluxio.WorkerStorageTierAssoc;
import alluxio.exception.BlockAlreadyExistsException;
import alluxio.exception.BlockDoesNotExistException;
import alluxio.exception.InvalidWorkerStateException;
import alluxio.exception.WorkerOutOfSpaceException;
import alluxio.heartbeat.HeartbeatExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.concurrent.NotThreadSafe;

/**
 * The {@link SpaceReserver} periodically checks the available space on each storage tier. If the
 * used space is above the high watermark configured for the tier, eviction will be triggered to
 * reach the low watermark. If this is not the top tier, it will also add the amount of space
 * reserved on the tier above to reduce the impact of cascading eviction.
 */
@NotThreadSafe
public class SpaceReserver implements HeartbeatExecutor {
  private static final Logger LOG = LoggerFactory.getLogger(SpaceReserver.class);

  /** The block worker the space reserver monitors. */
  private final BlockWorker mBlockWorker;

  /** Association between storage tier aliases and ordinals for the worker. */
  private final StorageTierAssoc mStorageTierAssoc;

  /** Mapping from tier alias to high watermark in bytes. */
  private final Map<String, Long> mHighWatermarks = new HashMap<>();

  /** Mapping from tier alias to space in bytes to be reserved on the tier. */
  private final Map<String, Long> mReservedSpaces = new HashMap<>();

  /**
   * Creates a new instance of {@link SpaceReserver}.
   *
   * @param blockWorker the block worker handle
   */
  public SpaceReserver(BlockWorker blockWorker) {
    mBlockWorker = blockWorker;
    mStorageTierAssoc = new WorkerStorageTierAssoc();
    Map<String, Long> tierCapacities = blockWorker.getStoreMeta().getCapacityBytesOnTiers();
    long lastTierReservedBytes = 0;
    for (int ordinal = 0; ordinal < mStorageTierAssoc.size(); ordinal++) {
      String tierAlias = mStorageTierAssoc.getAlias(ordinal);
      long tierCapacity = tierCapacities.get(tierAlias);
      long reservedSpace;
      PropertyKey tierReservedSpaceProp =
          PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO.format(ordinal);
      if (Configuration.containsKey(tierReservedSpaceProp)) {
        LOG.warn("The property reserved.ratio is deprecated use high/low watermark instead.");
        reservedSpace = (long) (tierCapacity * Configuration.getDouble(tierReservedSpaceProp));
      } else {
        // High watermark defines when to start the space reserving process
        PropertyKey tierHighWatermarkProp =
            PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_HIGH_WATERMARK_RATIO.format(ordinal);
        long highWatermark =
            (long) (tierCapacity * Configuration.getDouble(tierHighWatermarkProp));
        mHighWatermarks.put(tierAlias, highWatermark);

        // Low watermark defines when to stop the space reserving process if started
        PropertyKey tierLowWatermarkProp =
            PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_LOW_WATERMARK_RATIO.format(ordinal);
        reservedSpace =
            (long) (tierCapacity - tierCapacity * Configuration.getDouble(tierLowWatermarkProp));
      }
      mReservedSpaces.put(tierAlias, reservedSpace + lastTierReservedBytes);
      lastTierReservedBytes += reservedSpace;
    }
  }

  private void reserveSpace() {
    Map<String, Long> usedBytesOnTiers = mBlockWorker.getStoreMeta().getUsedBytesOnTiers();
    for (int ordinal = mStorageTierAssoc.size() - 1; ordinal >= 0; ordinal--) {
      String tierAlias = mStorageTierAssoc.getAlias(ordinal);
      long reservedSpace = mReservedSpaces.get(tierAlias);
      if (mHighWatermarks.containsKey(tierAlias)) {
        long highWatermark = mHighWatermarks.get(tierAlias);
        if (highWatermark > reservedSpace && usedBytesOnTiers.get(tierAlias) >= highWatermark) {
          try {
            mBlockWorker.freeSpace(Sessions.MIGRATE_DATA_SESSION_ID, reservedSpace, tierAlias);
          } catch (WorkerOutOfSpaceException | BlockDoesNotExistException
              | BlockAlreadyExistsException | InvalidWorkerStateException | IOException e) {
            LOG.warn("SpaceReserver failed to free tier {} to {} bytes used", tierAlias,
                reservedSpace, e.getMessage());
          }
        }
      } else {
        try {
          mBlockWorker.freeSpace(Sessions.MIGRATE_DATA_SESSION_ID, reservedSpace, tierAlias);
        } catch (WorkerOutOfSpaceException | BlockDoesNotExistException
            | BlockAlreadyExistsException | InvalidWorkerStateException | IOException e) {
          LOG.warn(e.getMessage());
        }
      }
    }
  }

  @Override
  public void heartbeat() {
    reserveSpace();
  }

  @Override
  public void close() {
    // Nothing to close.
  }
}


text:
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/test_helpers.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"

namespace xla {
namespace {

class TrivialAllReduceTest : public HloTestBase {};

// Currently the CPU and GPU backends only support AllReduce with one
// replica.  But we can at least check this.

XLA_TEST_F(TrivialAllReduceTest, OneOperand) {
  const char* module_str = R"(
  HloModule test

  add {
    x = f32[] parameter(0)
    y = f32[] parameter(1)
    add = f32[] add(x, y)
  }

  ENTRY test_computation {
    p = f32[3] parameter(0)
    ROOT crs = f32[3] all-reduce(p), to_apply=add
  })";
  auto module =
      ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())
          .ValueOrDie();
  auto literal = LiteralUtil::CreateR1<float>({1, 2, 3});
  EXPECT_EQ(literal, ExecuteAndTransfer(std::move(module), {&literal}));
}

XLA_TEST_F(TrivialAllReduceTest, MultipleOperands) {
  const char* module_str = R"(
  HloModule test

  add {
    x = f32[] parameter(0)
    y = f32[] parameter(1)
    add = f32[] add(x, y)
  }

  ENTRY test_computation {
    p0 = f32[3] parameter(0)
    p1 = f32[2] parameter(1)
    ROOT crs = (f32[3], f32[2]) all-reduce(p0, p1), to_apply=add
  })";
  auto module =
      ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())
          .ValueOrDie();
  auto literal0 = LiteralUtil::CreateR1<float>({1, 2, 3});
  auto literal1 = LiteralUtil::CreateR1<float>({10, 20});
  EXPECT_EQ(LiteralUtil::MakeTuple({&literal0, &literal1}),
            ExecuteAndTransfer(std::move(module), {&literal0, &literal1}));
}

// On the GPU backend, constants get special handling.  Someone might pass a
// constant to CRS to e.g. count the number of replicas -- we need to make sure
// it works.
XLA_TEST_F(TrivialAllReduceTest, ConstantOperand) {
  const char* module_str = R"(
  HloModule test

  add {
    x = f32[] parameter(0)
    y = f32[] parameter(1)
    add = f32[] add(x, y)
  }

  ENTRY test_computation {
    p0 = f32[3] parameter(0)
    p1 = f32[2] constant({10, 20})
    ROOT crs = (f32[3], f32[2]) all-reduce(p0, p1), to_apply=add
  })";
  auto module =
      ParseAndReturnVerifiedModule(module_str, GetModuleConfigForTest())
          .ValueOrDie();
  auto literal0 = LiteralUtil::CreateR1<float>({1, 2, 3});
  auto literal1 = LiteralUtil::CreateR1<float>({10, 20});
  EXPECT_EQ(LiteralUtil::MakeTuple({&literal0, &literal1}),
            ExecuteAndTransfer(std::move(module), {&literal0}));
}

}  // namespace
}  // namespace xla


text:
import matplotlib
matplotlib.use('Agg')
import re
import pytest
import tempfile

import bayeslite
from bdbcontrib import bql_utils
from bdbcontrib import shell_utils

from test_population import prepare

csv_data = '''
id,one,two,three,four
0,1,3,1,four
1,5,4,5,four
2,1,5,2,three
3,4,4,3,five
4,0,3,1,one
5,0,1,2,three
6,1,1,1,four
7,3,3,1,one
8,2,1,5,two
9,0,2,0,one
'''.lstrip()

csv_data_nan = '''
id,one,two,three,four
0,NaN,3,NaN,four
1,5,4,5,four
2,NaN,5,2,three
3,4,4,3,five
4,0,3,NaN,NaN
5,0,NaN,2,three
6,NaN,NaN,NaN,four
7,3,3,NaN,NaN
8,2,NaN,5,two
9,0,2,0,NaN
'''.lstrip()

csv_data_empty = '''
id,one,two,three,four
0,,3,,four
1,5,4,5,four
2,,5,2,three
3,4,4,3,five
4,0,3,,""
5,0,,2,three
6,,,,four
7,3,3,,""
8,2,,5,two
9,0,2,0,""
'''.lstrip()

csv_data_999 = '''
id,one,two,three,four
0,999,3,999,four
1,5,4,5,four
2,999,5,2,three
3,4,4,3,five
4,0,3,999,999
5,0,999,2,three
6,999,999,999,four
7,3,3,999,999
8,2,999,5,two
9,0,2,0,999
'''.lstrip()

@pytest.mark.parametrize(
    "data, value, num_nulls_expected",
    [[csv_data, 'NaN', (0, 0, 0, 0,)],
     [csv_data_nan, 'NaN', (3, 3, 4, 3,)],
     [csv_data_999, '999', (3, 3, 4, 3,)],
     [csv_data_empty, '', (3, 3, 4, 3,)],
     [csv_data_nan, '999', (0, 0, 0, 0,)]])
def test_nullify_no_missing(data, value, num_nulls_expected):
    with tempfile.NamedTemporaryFile() as temp:
        temp.write(data)
        temp.seek(0)
        with bayeslite.bayesdb_open() as bdb:
            bayeslite.bayesdb_read_csv_file(bdb, 't', temp.name, header=True,
                                            create=True)
            bql_utils.nullify(bdb, 't', value)

            c = bdb.execute('SELECT COUNT(*) FROM t WHERE one IS NULL;')
            assert c.fetchvalue() == num_nulls_expected[0]

            c = bdb.execute('SELECT COUNT(*) FROM t WHERE two IS NULL;')
            assert c.fetchvalue() == num_nulls_expected[1]

            c = bdb.execute('SELECT COUNT(*) FROM t WHERE three IS NULL;')
            assert c.fetchvalue() == num_nulls_expected[2]

            c = bdb.execute('SELECT COUNT(*) FROM t WHERE four IS NULL;')
            assert c.fetchvalue() == num_nulls_expected[3]

def test_cursor_to_df():
    with bayeslite.bayesdb_open() as bdb:
        bql_utils.cursor_to_df(bdb.execute('select * from sqlite_master'))
        bql_utils.cursor_to_df(bdb.execute('select * from sqlite_master'
                ' where 0 = 1'))

def test_is_plotting_command():
    cmd1 = '.heatmap ESTIMATE PAIRWISE DEPENDENCE PROBABILITY FROM t; -f z.png'
    cmd2 = '.show SELECT a, b FROM t LIMIT 10; --no-contour'
    cmd3 = '.histogram SELECT a FROM t;'
    cmd4 = '.help histogram'
    cmd5 = 'SELECT a FROM t;'
    cmd6 = '-- .show is a plotting function'

    assert shell_utils.is_plotting_command(cmd1)
    assert shell_utils.is_plotting_command(cmd2)
    assert shell_utils.is_plotting_command(cmd3)
    assert not shell_utils.is_plotting_command(cmd4)
    assert not shell_utils.is_plotting_command(cmd5)
    assert not shell_utils.is_plotting_command(cmd6)

def test_clean_cmd_filename():
    output_dir = 'foo/baz'
    fignum = 0

    cmd1 = '.histogram SELECT a FROM t;'
    cmd2 = '.histogram SELECT a FROM t; -f pic.png'
    cmd1_expected = '.histogram SELECT a FROM t; --filename foo/baz/fig_0.png'

    cmd1_ud, _ = shell_utils.clean_cmd_filename(cmd1, fignum, output_dir)
    assert cmd1_ud == cmd1_expected
    with pytest.raises(ValueError):
        shell_utils.clean_cmd_filename(cmd2, fignum, output_dir)
    with pytest.raises(ValueError):
        shell_utils.clean_cmd_filename(cmd1_expected, fignum, output_dir)

def test_is_comment():
    assert not shell_utils.is_comment('.heatmap ESTIMATE PAIRWISE FOO;')
    assert shell_utils.is_comment('-- is a comment')
    assert shell_utils.is_comment('--is a comment')
    assert shell_utils.is_comment('---is a comment')

    # XXX: There is no support for inline comments in BQL scripts
    assert not shell_utils.is_comment(' -- not a comment')
    assert not shell_utils.is_comment('.show SELECT a, b FROM t;'
        ' --no-contour')

def test_is_dot_command():
    assert not shell_utils.is_dot_command('-- .show SELECT a, b FROM t;')
    assert not shell_utils.is_dot_command('SELECT ".show" FROM t;')
    assert shell_utils.is_dot_command('.show SELECT a, b FROM t;')

@pytest.mark.parametrize(
    "data, cols, cardinalities_expected",
    [[csv_data, None, [10, 6, 5, 5, 5]],
     [csv_data_nan, None, [10, 6, 5, 5, 5]],
     [csv_data_999, None, [10, 6, 5, 5, 5]],
     [csv_data_empty, None, [10, 6, 5, 5, 5]],
     [csv_data, ['id'], [10]],
     [csv_data, ['two', 'id'], [5, 10]],
     ])
def test_cardinality(data, cols, cardinalities_expected):
    with tempfile.NamedTemporaryFile() as temp:
        temp.write(data)
        temp.seek(0)
        with bayeslite.bayesdb_open() as bdb:
            bayeslite.bayesdb_read_csv_file(bdb, 't', temp.name, header=True,
                                            create=True)
            cards = bql_utils.cardinality(bdb, 't', cols)
            for col, count, expected_count in zip(
                    cards['name'], cards['distinct_count'],
                    cardinalities_expected):
                assert expected_count == count
                assert col in ('id', 'one', 'two', 'three', 'four')
                if cols is not None:
                    expected_col = cols.pop(0)
                    assert expected_col == col
            assert len(cards) == len(cardinalities_expected)

def test_describe_columns_and_column_type():
    with prepare() as (dts, _df):
        resultdf = dts.query('SELECT * from %t LIMIT 1')
        assert ['index', 'floats_1', 'categorical_1', 'categorical_2',
                'few_ints_3', 'floats_3', 'many_ints_4', 'skewed_numeric_5',
                ] == list(resultdf.columns)
        resultdf = dts.variable_stattypes()
        expected = {'floats_1': 'numerical',
                    'categorical_1': 'categorical',
                    'categorical_2': 'categorical',
                    'few_ints_3': 'categorical',
                    'floats_3': 'numerical',
                    'many_ints_4': 'numerical',
                    'skewed_numeric_5': r'(categorical|numerical)'}
        for (column, expected_type) in expected.iteritems():
            stattype = resultdf[resultdf['name'] == column]['stattype'].iloc[0]
            assert re.match(expected_type, stattype), column
            assert re.match(expected_type, dts.get_column_stattype(column))


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the IntWrapper class.
 * @constructor
 * @member {number} value
 *
 */
function IntWrapper() {
}

/**
 * Defines the metadata of IntWrapper
 *
 * @returns {object} metadata of IntWrapper
 *
 */
IntWrapper.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'int-wrapper',
    type: {
      name: 'Composite',
      className: 'IntWrapper',
      modelProperties: {
        value: {
          required: true,
          serializedName: 'value',
          type: {
            name: 'Number'
          }
        }
      }
    }
  };
};

module.exports = IntWrapper;


text:
using System;
using System.Linq;
using System.Threading;
using NUnit.Framework;

namespace Tests
{
    class TestWorker
    {
        public Exception? Exception;

        public void Random()
        {
            try
            {
                var bytes = Sodium.SodiumCore.GetRandomBytes(32);

                //this is mostly to make the compiler happier, as otherwise, bytes is never used
                if (bytes.Count() != 32)
                    throw new Exception("GetRandomCountMismatch");
            }
            catch (Exception ex)
            {
                Exception = ex;
            }
        }
    }

    /// Tests the thread safety
    [TestFixture]
    class ThreadSafetyTest
    {
        /// Does CryptoHash.Hash(string) return the expected value?
        [Test]
        public void ThreadSafetyRandomTest()
        {
            const int CONCURRENCY = 2;
            var workers = new TestWorker[CONCURRENCY];
            var threads = new Thread[CONCURRENCY];

            for (var i = 0; i < CONCURRENCY; i++)
            {
                workers[i] = new TestWorker();
                threads[i] = new Thread(workers[i].Random);
                threads[i].Start();
            }

            for (var i = 0; i < CONCURRENCY; i++)
            {
                threads[i].Join();
            }

            for (var i = 0; i < CONCURRENCY; i++)
            {
                Assert.IsNull(workers[i].Exception);
            }
        }
    }
}