text:
$ErrorActionPreference = 'Stop';
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

$url        = 'https://download.microsoft.com/download/C/4/F/C4F908C9-98ED-4E5F-88D5-7D6A5004AEBD/SQLServer2017-KB5016884-x64.exe'
$checksum   = 'ae3554ba0a474b4d1a6b2d3bb7f00a4f6308dbe50178fff67baa8b21cc74dbc2'
$softwareName = 'Hotfix 3456 for SQL Server 2017*(KB5016884)*'

[bool] $runningAU = (Test-Path Function:\au_GetLatest)
$filename = [IO.Path]::GetFileName($url)

# Download like Install-ChocolateyPackage (so we can restart from cached download)
$chocTempDir = $env:TEMP

$tempDir = Join-Path $chocTempDir "$($env:chocolateyPackageName)"
if ($env:chocolateyPackageVersion -ne $null) { $tempDir = Join-Path $tempDir "$($env:chocolateyPackageVersion)"; }
$tempDir = $tempDir -replace '\\chocolatey\\chocolatey\\', '\chocolatey\'
if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null }
$downloadFilePath = Join-Path $tempDir $filename

$fullFilePath = Join-Path $toolsDir $filename

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  url           = $url
  FileFullPath  = $downloadFilePath
  checksum      = $checksum
  checksumType  = 'sha256'
}

$filePath = Get-ChocolateyWebFile @packageArgs

if (Test-Path Function:\au_GetLatest) {
  return
}

# Copy into tools to keep for uninstall
Copy-Item $filePath -Destination $fullFilePath

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  file  = $fullFilePath
  softwareName  = $softwareName
  silentArgs    = "/q /IAcceptSQLServerLicenseTerms /Action=Patch /AllInstances"
  validExitCodes= @(0, 3010, 1641)
}

Install-ChocolateyInstallPackage @packageArgs

$files = get-childitem $toolsDir -include *.exe -recurse

foreach ($file in $files) {
  # generate an ignore file
  New-Item "$file.ignore" -type file -force | Out-Null
}


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

namespace System.ComponentModel.DataAnnotations.Tests
{
    public class ValidatorTests
    {
        public static readonly ValidationContext s_estValidationContext = new ValidationContext(new object());

        #region TryValidateObject

        [Fact]
        public static void TryValidateObjectThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null));

            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null, validateAllProperties: false));
        }

        [Fact]
        public static void TryValidateObjectThrowsIf_instance_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null));

            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null, validateAllProperties: false));
        }

        // TryValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance
        [Fact]
        public static void TestTryValidateObjectThrowsIfInstanceNotMatch()
        {
            AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null));
            AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null, validateAllProperties: true));
        }

        [Fact]
        public static void TryValidateObject_returns_true_if_no_errors()
        {
            var objectToBeValidated = "ToBeValidated";
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null));
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null, validateAllProperties: true));
        }

        [Fact]
        public static void TryValidateObject_returns_false_if_errors()
        {
            var objectToBeValidated = new ToBeValidated()
            {
                PropertyToBeTested = "Invalid Value",
                PropertyWithRequiredAttribute = "Valid Value"
            };
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));

            var validationResults = new List<ValidationResult>();
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
            Assert.Equal(1, validationResults.Count);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
        }

        // TryValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors()
        [Fact]
        public static void TestTryValidateObjectSuccessEvenWithOtherErrors()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, null, false));

            var validationResults = new List<ValidationResult>();
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, false));
            Assert.Equal(0, validationResults.Count);
        }

        [Fact]
        public static void TryValidateObject_returns_false_if_validateAllProperties_is_true_and_Required_test_fails()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));

            var validationResults = new List<ValidationResult>();
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
            Assert.Equal(1, validationResults.Count);
            // cannot check error message - not defined on ret builds
        }

        [Fact]
        public static void TryValidateObject_returns_true_if_validateAllProperties_is_true_and_all_attributes_are_valid()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));

            var validationResults = new List<ValidationResult>();
            Assert.True(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
            Assert.Equal(0, validationResults.Count);
        }

        [Fact]
        public static void TryValidateObject_returns_false_if_all_properties_are_valid_but_class_is_invalid()
        {
            var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));

            var validationResults = new List<ValidationResult>();
            Assert.False(
                Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
            Assert.Equal(1, validationResults.Count);
            Assert.Equal("ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, validationResults[0].ErrorMessage);
        }

        [Fact]
        public void TryValidateObject_IValidatableObject_Success()
        {
            var instance = new ValidatableSuccess();
            var context = new ValidationContext(instance);

            var results = new List<ValidationResult>();
            Assert.True(Validator.TryValidateObject(instance, context, results));
            Assert.Empty(results);
        }

        public class ValidatableSuccess : IValidatableObject
        {
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                return new ValidationResult[] { ValidationResult.Success };
            }
        }

        [Fact]
        public void TryValidateObject_IValidatableObject_Error()
        {
            var instance = new ValidatableError();
            var context = new ValidationContext(instance);

            var results = new List<ValidationResult>();
            Assert.False(Validator.TryValidateObject(instance, context, results));
            Assert.Equal("error", Assert.Single(results).ErrorMessage);
        }

        public class ValidatableError : IValidatableObject
        {
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                return new ValidationResult[] { new ValidationResult("error") };
            }
        }

        [Fact]
        public void TryValidateObject_RequiredNonNull_Success()
        {
            var instance = new RequiredFailure { Required = "Text" };
            var context = new ValidationContext(instance);

            var results = new List<ValidationResult>();
            Assert.True(Validator.TryValidateObject(instance, context, results));
            Assert.Empty(results);
        }

        [Fact]
        public void TryValidateObject_RequiredNull_Error()
        {
            var instance = new RequiredFailure();
            var context = new ValidationContext(instance);

            var results = new List<ValidationResult>();
            Assert.False(Validator.TryValidateObject(instance, context, results));
            Assert.Equal("The Required field is required.", Assert.Single(results).ErrorMessage);
        }

        public class RequiredFailure
        {
            [Required]
            public string Required { get; set; }
        }

        #endregion TryValidateObject

        #region ValidateObject

        [Fact]
        public static void ValidateObjectThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateObject(new object(), validationContext: null));

            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateObject(new object(), validationContext: null, validateAllProperties: false));
        }

        [Fact]
        public static void ValidateObjectThrowsIf_instance_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateObject(null, s_estValidationContext));

            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateObject(null, s_estValidationContext, false));
        }

        [Fact]
        public static void ValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance()
        {
            AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext));
            AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext, true));
        }

        [Fact]
        public static void ValidateObject_succeeds_if_no_errors()
        {
            var objectToBeValidated = "ToBeValidated";
            var validationContext = new ValidationContext(objectToBeValidated);
            Validator.ValidateObject(objectToBeValidated, validationContext);
            Validator.ValidateObject(objectToBeValidated, validationContext, true);
        }

        [Fact]
        public static void ValidateObject_throws_ValidationException_if_errors()
        {
            var objectToBeValidated = new ToBeValidated()
            {
                PropertyToBeTested = "Invalid Value",
                PropertyWithRequiredAttribute = "Valid Value"
            };
            var validationContext = new ValidationContext(objectToBeValidated);
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateObject(objectToBeValidated, validationContext, true));
            Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
            Assert.Equal("Invalid Value", exception.Value);
        }

        // ValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors
        [Fact]
        public static void TestValidateObjectNotThrowIfvalidateAllPropertiesFalse()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            Validator.ValidateObject(objectToBeValidated, validationContext, false);
        }

        // ValidateObject_throws_ValidationException_if_validateAllProperties_is_true_and_Required_test_fails
        [Fact]
        public static void TestValidateObjectThrowsIfRequiredTestFails()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
            var validationContext = new ValidationContext(objectToBeValidated);
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateObject(objectToBeValidated, validationContext, true));
            Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
            // cannot check error message - not defined on ret builds
            Assert.Null(exception.Value);
        }

        [Fact]
        public static void ValidateObject_succeeds_if_validateAllProperties_is_true_and_all_attributes_are_valid()
        {
            var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            Validator.ValidateObject(objectToBeValidated, validationContext, true);
        }

        [Fact]
        public static void ValidateObject_throws_ValidationException_if_all_properties_are_valid_but_class_is_invalid()
        {
            var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
            var validationContext = new ValidationContext(objectToBeValidated);
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateObject(objectToBeValidated, validationContext, true));
            Assert.IsType<ValidClassAttribute>(exception.ValidationAttribute);
            Assert.Equal(
                "ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName,
                exception.ValidationResult.ErrorMessage);
            Assert.Equal(objectToBeValidated, exception.Value);
        }

        #endregion ValidateObject

        #region TryValidateProperty

        [Fact]
        public static void TryValidatePropertyThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateProperty(new object(), validationContext: null, validationResults: null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_value_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateProperty(null, s_estValidationContext, validationResults: null));
        }

        // TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
        [Fact]
        public static void TestTryValidatePropertyThrowsIfNullOrEmptyValidationContextMemberName()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = null;
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateProperty(null, validationContext, null));

            validationContext.MemberName = string.Empty;
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateProperty(null, validationContext, null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NonExist";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "InternalProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));

            validationContext.MemberName = "ProtectedProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));

            validationContext.MemberName = "PrivateProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "Item";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());

            validationContext.MemberName = "NoAttributesProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(123, validationContext, validationResults: null));
        }

        [Fact]
        public static void TryValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());

            // cannot assign null to a non-value-type property
            validationContext.MemberName = "EnumProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));

            // cannot assign null to a non-nullable property
            validationContext.MemberName = "NonNullableProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));
        }

        [Fact]
        public static void TryValidateProperty_returns_true_if_null_passed_to_nullable_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NullableProperty";
            Assert.True(Validator.TryValidateProperty(null, validationContext, validationResults: null));
        }

        [Fact]
        public static void TryValidateProperty_returns_true_if_no_attributes_to_validate()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NoAttributesProperty";
            Assert.True(
                Validator.TryValidateProperty("Any Value", validationContext, validationResults: null));
        }

        [Fact]
        public static void TryValidateProperty_returns_false_if_errors()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyToBeTested";
            Assert.False(
                Validator.TryValidateProperty("Invalid Value", validationContext, null));

            var validationResults = new List<ValidationResult>();
            Assert.False(
                Validator.TryValidateProperty("Invalid Value", validationContext, validationResults));
            Assert.Equal(1, validationResults.Count);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
        }

        [Fact]
        public static void TryValidateProperty_returns_false_if_Required_attribute_test_fails()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            Assert.False(
                Validator.TryValidateProperty(null, validationContext, null));

            var validationResults = new List<ValidationResult>();
            Assert.False(
                Validator.TryValidateProperty(null, validationContext, validationResults));
            Assert.Equal(1, validationResults.Count);
            // cannot check error message - not defined on ret builds
        }

        [Fact]
        public static void TryValidateProperty_returns_true_if_all_attributes_are_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            Assert.True(
                Validator.TryValidateProperty("Valid Value", validationContext, null));

            var validationResults = new List<ValidationResult>();
            Assert.True(
                Validator.TryValidateProperty("Valid Value", validationContext, validationResults));
            Assert.Equal(0, validationResults.Count);
        }

        #endregion TryValidateProperty

        #region ValidateProperty

        [Fact]
        public static void ValidatePropertyThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateProperty(new object(), validationContext: null));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_value_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateProperty(null, s_estValidationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = null;
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateProperty(null, validationContext));

            validationContext.MemberName = string.Empty;
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateProperty(null, validationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NonExist";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "InternalProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));

            validationContext.MemberName = "ProtectedProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));

            validationContext.MemberName = "PrivateProperty";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "Item";
            AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());

            validationContext.MemberName = "NoAttributesProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(123, validationContext));
        }

        [Fact]
        public static void ValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());

            // cannot assign null to a non-value-type property
            validationContext.MemberName = "EnumProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext));

            // cannot assign null to a non-nullable property
            validationContext.MemberName = "NonNullableProperty";
            AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext));
        }

        [Fact]
        public static void ValidateProperty_succeeds_if_null_passed_to_nullable_property()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NullableProperty";
            Validator.ValidateProperty(null, validationContext);
        }

        [Fact]
        public static void ValidateProperty_succeeds_if_no_attributes_to_validate()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NoAttributesProperty";
            Validator.ValidateProperty("Any Value", validationContext);
        }

        [Fact]
        public static void ValidateProperty_throws_ValidationException_if_errors()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyToBeTested";
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateProperty("Invalid Value", validationContext));
            Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
            Assert.Equal("Invalid Value", exception.Value);
        }

        [Fact]
        public static void ValidateProperty_throws_ValidationException_if_Required_attribute_test_fails()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateProperty(null, validationContext));
            Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
            // cannot check error message - not defined on ret builds
            Assert.Null(exception.Value);
        }

        [Fact]
        public static void ValidateProperty_succeeds_if_all_attributes_are_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            Validator.ValidateProperty("Valid Value", validationContext);
        }

        #endregion ValidateProperty

        #region TryValidateValue

        [Fact]
        public static void TryValidateValueThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateValue(new object(),
                    validationContext: null, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
        }

        [Fact]
        public static void TryValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = null;
            Assert.Throws<ArgumentNullException>(
                () => Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: null));
        }

        [Fact]
        public static void TryValidateValue_returns_true_if_no_attributes_to_validate_regardless_of_value()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NoAttributesProperty";
            Assert.True(Validator.TryValidateValue(null, validationContext,
                validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
            Assert.True(Validator.TryValidateValue(new object(), validationContext,
                validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
        }

        [Fact]
        public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate));

            var validationResults = new List<ValidationResult>();
            Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate));
            Assert.Equal(1, validationResults.Count);
            // cannot check error message - not defined on ret builds
        }

        [Fact]
        public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_invalid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));

            var validationResults = new List<ValidationResult>();
            Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
            Assert.Equal(1, validationResults.Count);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
        }

        [Fact]
        public static void TryValidateValue_returns_true_if_Property_has_RequiredAttribute_and_value_is_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));

            var validationResults = new List<ValidationResult>();
            Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
            Assert.Equal(0, validationResults.Count);
        }

        [Fact]
        public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
            Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));

            var validationResults = new List<ValidationResult>();
            Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
            Assert.Equal(1, validationResults.Count);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
        }

        [Fact]
        public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyToBeTested";
            var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
            Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));

            var validationResults = new List<ValidationResult>();
            Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
            Assert.Equal(0, validationResults.Count);
        }

        #endregion TryValidateValue

        #region ValidateValue

        [Fact]
        public static void ValidateValueThrowsIf_ValidationContext_is_null()
        {
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateValue(new object(),
                    validationContext: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
        }

        [Fact]
        public static void ValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = null;
            Assert.Throws<ArgumentNullException>(
                () => Validator.ValidateValue(new object(), validationContext, validationAttributes: null));
        }

        [Fact]
        public static void ValidateValue_succeeds_if_no_attributes_to_validate_regardless_of_value()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "NoAttributesProperty";
            Validator.ValidateValue(null, validationContext, Enumerable.Empty<ValidationAttribute>());
            Validator.ValidateValue(new object(), validationContext, Enumerable.Empty<ValidationAttribute>());
        }

        // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_null()
        [Fact]
        public static void TestValidateValueThrowsIfNullRequiredAttribute()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateValue(null, validationContext, attributesToValidate));
            Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
            // cannot check error message - not defined on ret builds
            Assert.Null(exception.Value);
        }

        // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_invalid()
        [Fact]
        public static void TestValidateValueThrowsIfRequiredAttributeInvalid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
            Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
            Assert.Equal("Invalid Value", exception.Value);
        }

        [Fact]
        public static void ValidateValue_succeeds_if_Property_has_RequiredAttribute_and_value_is_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
            Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
        }

        // ValidateValue_throws_ValidationException_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
        [Fact]
        public static void TestValidateValueThrowsIfNoRequiredAttribute()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyWithRequiredAttribute";
            var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
            var exception = Assert.Throws<ValidationException>(
                () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
            Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
            Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
            Assert.Equal("Invalid Value", exception.Value);
        }

        [Fact]
        public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid()
        {
            var validationContext = new ValidationContext(new ToBeValidated());
            validationContext.MemberName = "PropertyToBeTested";
            var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
            Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
        }

        #endregion ValidateValue

        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
        public class ValidValueStringPropertyAttribute : ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext _)
            {
                if (value == null) { return ValidationResult.Success; }
                var valueAsString = value as string;
                if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; }
                return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value);
            }
        }

        [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
        public class ValidClassAttribute : ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext _)
            {
                if (value == null) { return ValidationResult.Success; }
                if (value.GetType().Name.ToLowerInvariant().Contains("invalid"))
                {
                    return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName);
                }
                return ValidationResult.Success;
            }
        }

        [ValidClass]
        public class ToBeValidated
        {
            [ValidValueStringProperty]
            public string PropertyToBeTested { get; set; }

            public string NoAttributesProperty { get; set; }

            [Required]
            [ValidValueStringProperty]
            public string PropertyWithRequiredAttribute { get; set; }

            internal string InternalProperty { get; set; }
            protected string ProtectedProperty { get; set; }
            private string PrivateProperty { get; set; }

            public string this[int index]
            {
                get { return null; }
                set { }
            }

            public TestEnum EnumProperty { get; set; }

            public int NonNullableProperty { get; set; }
            public int? NullableProperty { get; set; }
        }

        public enum TestEnum
        {
            A = 0
        }

        [ValidClass]
        public class InvalidToBeValidated
        {
            [ValidValueStringProperty]
            public string PropertyToBeTested { get; set; }

            public string NoAttributesProperty { get; set; }

            [Required]
            [ValidValueStringProperty]
            public string PropertyWithRequiredAttribute { get; set; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Convert column mapper
 *
 * @category   Mage
 * @package    Mage_Dataflow
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Dataflow_Model_Convert_Mapper_Column extends Mage_Dataflow_Model_Convert_Mapper_Abstract
{
    /**
     * Dataflow batch model
     *
     * @var Mage_Dataflow_Model_Batch
     */
    protected $_batch;

    /**
     * Dataflow batch export model
     *
     * @var Mage_Dataflow_Model_Batch_Export
     */
    protected $_batchExport;

    /**
     * Dataflow batch import model
     *
     * @var Mage_Dataflow_Model_Batch_Import
     */
    protected $_batchImport;

    /**
     * Retrieve Batch model singleton
     *
     * @return Mage_Dataflow_Model_Batch
     */
    public function getBatchModel()
    {
        if (is_null($this->_batch)) {
            $this->_batch = Mage::getSingleton('dataflow/batch');
        }
        return $this->_batch;
    }

    /**
     * Retrieve Batch export model
     *
     * @return Mage_Dataflow_Model_Batch_Export
     */
    public function getBatchExportModel()
    {
        if (is_null($this->_batchExport)) {
            $object = Mage::getModel('dataflow/batch_export');
            $this->_batchExport = Varien_Object_Cache::singleton()->save($object);
        }
        return Varien_Object_Cache::singleton()->load($this->_batchExport);
    }

    /**
     * Retrieve Batch import model
     *
     * @return Mage_Dataflow_Model_Import_Export
     */
    public function getBatchImportModel()
    {
        if (is_null($this->_batchImport)) {
            $object = Mage::getModel('dataflow/batch_import');
            $this->_batchImport = Varien_Object_Cache::singleton()->save($object);
        }
        return Varien_Object_Cache::singleton()->load($this->_batchImport);
    }

    public function map()
    {
        $batchModel  = $this->getBatchModel();
        $batchExport = $this->getBatchExportModel();

        $batchExportIds = $batchExport
            ->setBatchId($this->getBatchModel()->getId())
            ->getIdCollection();

        $onlySpecified = (bool)$this->getVar('_only_specified') === true;

        if (!$onlySpecified) {
            foreach ($batchExportIds as $batchExportId) {
                $batchExport->load($batchExportId);
                $batchModel->parseFieldList($batchExport->getBatchData());
            }

            return $this;
        }

        if ($this->getVar('map') && is_array($this->getVar('map'))) {
            $attributesToSelect = $this->getVar('map');
        }
        else {
            $attributesToSelect = array();
        }

        if (!$attributesToSelect) {
            $this->getBatchExportModel()
                ->setBatchId($this->getBatchModel()->getId())
                ->deleteCollection();

            throw new Exception(Mage::helper('dataflow')->__('Error in field mapping: field list for mapping is not defined.'));
        }

        foreach ($batchExportIds as $batchExportId) {
            $batchExport = $this->getBatchExportModel()->load($batchExportId);
            $row = $batchExport->getBatchData();

            $newRow = array();
            foreach ($attributesToSelect as $field => $mapField) {
                $newRow[$mapField] = isset($row[$field]) ? $row[$field] : null;
            }

            $batchExport->setBatchData($newRow)
                ->setStatus(2)
                ->save();
            $this->getBatchModel()->parseFieldList($batchExport->getBatchData());
        }

        return $this;
    }
}


text:
package net.firejack.platform.service.site.endpoint;

import net.firejack.platform.api.OPFEngine;
import net.firejack.platform.api.registry.domain.RegistryNodeTree;
import net.firejack.platform.api.site.domain.NavigationElement;
import net.firejack.platform.api.site.domain.NavigationElementTree;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Component("siteService")
@Path("site")
@WebService()
@SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL)
public class SiteEndpoint implements ISiteEndpoint {

    @Override
    @GET
    @Path("/navigation/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<NavigationElement> readNavigationElement(@PathParam("id") Long id) {
        return OPFEngine.SiteService.readNavigationElementBroker(id);
    }

    /**
     * Service retrieves tree navigation elements by parent lookup
     *
     * @param lookup
     * @return
     */
    @Override
    @GET
    @Path("/navigation/tree-by-lookup/{lookup}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<NavigationElement> readTreeNavigationElementsByParentLookup(
		    @PathParam("lookup") String lookup) {
        return OPFEngine.SiteService.readTreeNavigationElementsByParentLookup(lookup);
    }

        /**
     * Service retrieves the child navigation elements by parent id.
     *
     * @param parentId - ID of the parent entity
     * @return found list of navigation elements
     */
    @Override
    @GET
    @Path("/navigation/list-by-parent-id/{parentId}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<NavigationElement> readNavigationElementsByParentId(
		    @PathParam("parentId") Long parentId) {
        return OPFEngine.SiteService.readNavigationElementsByParentId(parentId);
    }

    /**
     * Service create a navigation element
     *
     * @param request request with navigation element data
     * @return created navigation element
     */
    @Override
    @POST
    @Path("/navigation")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<RegistryNodeTree> createNavigationElement(
		    ServiceRequest<NavigationElement> request) {
        return OPFEngine.SiteService.createNavigationElement(request.getData());
    }

    /**
     * Service update the navigation element
     *
     * @param id - navigation element id which need to update
     * @param request - request with navigation element data
     * @return updated navigation element
     */
    @Override
    @PUT
    @Path("/navigation/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<RegistryNodeTree> updateNavigationElement(
		    @PathParam("id") Long id, ServiceRequest<NavigationElement> request) {
        return OPFEngine.SiteService.updateNavigationElement(request.getData());
    }

    /**
     * Service delete the navigation element by id
     *
     * @param id - navigation element id which need to delete
     * @return message
     */
    @Override
    @DELETE
    @Path("/navigation/{id}")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse deleteNavigationElement(@PathParam(value = "id") Long id) {
        return OPFEngine.SiteService.deleteNavigationElement(id);
    }

    @Override
    @GET
    @Path("/navigation/cached/{packageLookup}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<NavigationElement> readCachedNavigationList(
		    @PathParam("packageLookup") String packageLookup) {
        return OPFEngine.SiteService.readCachedNavigationElements(packageLookup);
    }

    @Override
    @GET
    @Path("/navigation/tree/{packageLookup}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ServiceResponse<NavigationElementTree> readTreeNavigationMenu(
		    @PathParam("packageLookup") String packageLookup, @QueryParam("lazyLoadResource") boolean lazyLoadResource) {
        return OPFEngine.SiteService.readTreeNavigationMenu(packageLookup, lazyLoadResource);
    }

}


text:
{% if overview %}

{{ overview }}

{% else %}

{% include templates/_errorthrower.md missing_block='overview' purpose='states, in one or two sentences, the purpose of this document' %}

{% endif %}

* TOC
{: toc}

{% if objectives %}

## Objectives

{{ objectives }}

{% else %}

{% include templates/_errorthrower.md missing_block='objectives' heading='Objectives' purpose='lists the objectives for this tutorial.' %}

{% endif %}

{% if prerequisites %}

## Before you begin

{{ prerequisites }}

{% else %}

{% include templates/_errorthrower.md missing_block='prerequisites' heading='Before you begin' purpose='lists action prerequisites and knowledge prerequisites' %}

{% endif %}

{% if lessoncontent %}

{{ lessoncontent }}

{% else %}

{% include templates/_errorthrower.md missing_block='lessoncontent' purpose='provides the lesson content for this tutorial.' %}

{% endif %}

{% if cleanup %}

## Cleaning up

{{ cleanup }}

{% endif %}

{% if whatsnext %}

## What's next

{{ whatsnext }}

{% endif %}


text:
@interface SCInfobarBannerCoordinator : NSObject <NavigationCoordinator>
@end

#endif  // IOS_SHOWCASE_INFOBARS_SC_INFOBAR_BANNER_COORDINATOR_H_


text:
layout: default
class: Project
title: -maven-release ('local'|'remote') ( ',' option )*
summary:  Set the Maven release options for the Maven Bnd Repository
---

The `-maven-release` is an instruction that provides the context for a release to Maven repository. In the Maven world it is customary that a release has a JAR with sources and a JAR with Javadoc. In the OSGi world this is unnecessary because the sources can be packaged inside the bundle. (Since the source is placed at a standard location, the IDEs can take advantage of this.) However, putting an artifact on Maven Central requires that these extra JARs are included. This instruction allows you to specify additional parameters for this release process.

Though this instruction is not specific for a plugin, it was developed in conjunction with the [Maven Bnd Repository Plugin].

	-maven-release		::= ('local'|'remote' (';' snapshot )?) ( ',' option )*
	snapshot			::= <value to be used for timestamp>
	option				::= sources | javadoc | pom
	sources				::= 'sources' ( ';' 'path' '=' path-option )?
	javadoc				::= 'javadoc'
								( ';path=' path-option )?
								( ';packages=' packages-option )?
								(';' javadoc-command ) *
	path-option			::= 'NONE' | PATH
	packages-option		::= 'EXPORTS' | 'ALL'
	javadoc-command		::= '-' NAME '=' VALUE
	pom					::= 'pom' ( ';path=' PATH )

The `aQute.maven.bnd.MavenBndRepository` is a bnd plugin that represent the local and a remote Maven repository.The locations of both repositories can be configured. The local repository is always used as a cache for the remote repository.

The repository has the following parameters:

* `url` – The remote repository URL. Credentials and proxy can be set with the [Http Client options]. The url should be the base url of a Maven repository. If no URL is configured, there is no remote repository.
* `local`  – (`~/.m2/repository`) The location of the local repository. By default this is `~/.m2/repository`. It is not possible to not have a local repository because it acts as the cache.
* `generate` – (`JAVADOC,SOURCES`) A combination of `JAVADOC` and/or `SOURCES`. If no `-maven-release` instruction is found and the released artifact contains source code, then the given classifiers are used to generate them.
* `readOnly` – (`false`) Indicates if this is a read only repository
* `name` – The name of the repository

If the Maven Bnd Repository is asked to put a file, it will look up the `-maven-release` instruction using merged properties. The property is looked up from the bnd file that built the artifact. However, it should in general be possible to define this header in the workspace using macros like `${project}` to specify relative paths.

The `-maven-release` instruction contains a set of operations

	-maven-release 	::= 'type;' type ( ','  | coordinates | javadoc | pom | sources )*
	type			::= 'local' | 'remote'
	javadoc			::= path | properties
	path			::= PATH | URL
	properties		::= entry ( ';' entry )*
	entry			::= '-' NAME '=' NAME
	pom				::= path
	sources			::= path

[settings]: /chapters/880-settings.html

[Maven Bnd Repository Plugin]: /plugins/maven


text:
namespace device {

class HidConnectionLinux::FileThreadHelper
    : public base::MessagePumpLibevent::Watcher,
      public base::MessageLoop::DestructionObserver {
 public:
  FileThreadHelper(base::PlatformFile platform_file,
                   scoped_refptr<HidDeviceInfo> device_info,
                   base::WeakPtr<HidConnectionLinux> connection,
                   scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : platform_file_(platform_file),
        connection_(connection),
        task_runner_(task_runner) {
    // Report buffers must always have room for the report ID.
    report_buffer_size_ = device_info->max_input_report_size() + 1;
    has_report_id_ = device_info->has_report_id();
  }

  ~FileThreadHelper() override {
    DCHECK(thread_checker_.CalledOnValidThread());
    base::MessageLoop::current()->RemoveDestructionObserver(this);
  }

  // Starts the FileDescriptorWatcher that reads input events from the device.
  // Must be called on a thread that has a base::MessageLoopForIO.
  static void Start(scoped_ptr<FileThreadHelper> self) {
    base::ThreadRestrictions::AssertIOAllowed();
    self->thread_checker_.DetachFromThread();

    if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
            self->platform_file_, true, base::MessageLoopForIO::WATCH_READ,
            &self->file_watcher_, self.get())) {
      HID_LOG(ERROR) << "Failed to start watching device file.";
    }

    // |self| is now owned by the current message loop.
    base::MessageLoop::current()->AddDestructionObserver(self.release());
  }

 private:
  // base::MessagePumpLibevent::Watcher implementation.
  void OnFileCanReadWithoutBlocking(int fd) override {
    DCHECK(thread_checker_.CalledOnValidThread());
    DCHECK_EQ(fd, platform_file_);

    scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(report_buffer_size_));
    char* data = buffer->data();
    size_t length = report_buffer_size_;
    if (!has_report_id_) {
      // Linux will not prefix the buffer with a report ID if report IDs are not
      // used by the device. Prefix the buffer with 0.
      *data++ = 0;
      length--;
    }

    ssize_t bytes_read = HANDLE_EINTR(read(platform_file_, data, length));
    if (bytes_read < 0) {
      if (errno != EAGAIN) {
        HID_PLOG(EVENT) << "Read failed";
        // This assumes that the error is unrecoverable and disables reading
        // from the device until it has been re-opened.
        // TODO(reillyg): Investigate starting and stopping the file descriptor
        // watcher in response to pending read requests so that per-request
        // errors can be returned to the client.
        file_watcher_.StopWatchingFileDescriptor();
      }
      return;
    }
    if (!has_report_id_) {
      // Behave as if the byte prefixed above as the the report ID was read.
      bytes_read++;
    }

    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&HidConnectionLinux::ProcessInputReport,
                                      connection_, buffer, bytes_read));
  }

  void OnFileCanWriteWithoutBlocking(int fd) override {
    NOTREACHED();  // Only listening for reads.
  }

  // base::MessageLoop::DestructionObserver:
  void WillDestroyCurrentMessageLoop() override {
    DCHECK(thread_checker_.CalledOnValidThread());
    delete this;
  }

  base::ThreadChecker thread_checker_;
  base::PlatformFile platform_file_;
  size_t report_buffer_size_;
  bool has_report_id_;
  base::WeakPtr<HidConnectionLinux> connection_;
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  base::MessagePumpLibevent::FileDescriptorWatcher file_watcher_;

  DISALLOW_COPY_AND_ASSIGN(FileThreadHelper);
};

HidConnectionLinux::HidConnectionLinux(
    scoped_refptr<HidDeviceInfo> device_info,
    base::File device_file,
    scoped_refptr<base::SingleThreadTaskRunner> file_task_runner)
    : HidConnection(device_info),
      file_task_runner_(file_task_runner),
      weak_factory_(this) {
  task_runner_ = base::ThreadTaskRunnerHandle::Get();
  device_file_ = std::move(device_file);

  // The helper is passed a weak pointer to this connection so that it can be
  // cleaned up after the connection is closed.
  scoped_ptr<FileThreadHelper> helper(
      new FileThreadHelper(device_file_.GetPlatformFile(), device_info,
                           weak_factory_.GetWeakPtr(), task_runner_));
  helper_ = helper.get();
  file_task_runner_->PostTask(
      FROM_HERE, base::Bind(&FileThreadHelper::Start, base::Passed(&helper)));
}

HidConnectionLinux::~HidConnectionLinux() {
  DCHECK(helper_ == nullptr);
}

void HidConnectionLinux::PlatformClose() {
  // By closing the device file on the FILE thread (1) the requirement that
  // base::File::Close is called on a thread where I/O is allowed is satisfied
  // and (2) any tasks posted to this task runner that refer to this file will
  // complete before it is closed.
  file_task_runner_->DeleteSoon(FROM_HERE, helper_);
  helper_ = nullptr;
  file_task_runner_->PostTask(FROM_HERE,
                              base::Bind(&HidConnectionLinux::CloseDevice,
                                         base::Passed(&device_file_)));

  while (!pending_reads_.empty()) {
    pending_reads_.front().callback.Run(false, NULL, 0);
    pending_reads_.pop();
  }
}

void HidConnectionLinux::PlatformRead(const ReadCallback& callback) {
  PendingHidRead pending_read;
  pending_read.callback = callback;
  pending_reads_.push(pending_read);
  ProcessReadQueue();
}

void HidConnectionLinux::PlatformWrite(scoped_refptr<net::IOBuffer> buffer,
                                       size_t size,
                                       const WriteCallback& callback) {
  // Linux expects the first byte of the buffer to always be a report ID so the
  // buffer can be used directly.
  file_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&HidConnectionLinux::BlockingWrite,
                 device_file_.GetPlatformFile(), buffer, size,
                 base::Bind(&HidConnectionLinux::FinishWrite,
                            weak_factory_.GetWeakPtr(), size, callback),
                 task_runner_));
}

void HidConnectionLinux::PlatformGetFeatureReport(
    uint8_t report_id,
    const ReadCallback& callback) {
  // The first byte of the destination buffer is the report ID being requested
  // and is overwritten by the feature report.
  DCHECK_GT(device_info()->max_feature_report_size(), 0u);
  scoped_refptr<net::IOBufferWithSize> buffer(
      new net::IOBufferWithSize(device_info()->max_feature_report_size() + 1));
  buffer->data()[0] = report_id;

  file_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(
          &HidConnectionLinux::BlockingIoctl, device_file_.GetPlatformFile(),
          HIDIOCGFEATURE(buffer->size()), buffer,
          base::Bind(&HidConnectionLinux::FinishGetFeatureReport,
                     weak_factory_.GetWeakPtr(), report_id, buffer, callback),
          task_runner_));
}

void HidConnectionLinux::PlatformSendFeatureReport(
    scoped_refptr<net::IOBuffer> buffer,
    size_t size,
    const WriteCallback& callback) {
  // Linux expects the first byte of the buffer to always be a report ID so the
  // buffer can be used directly.
  file_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&HidConnectionLinux::BlockingIoctl,
                 device_file_.GetPlatformFile(), HIDIOCSFEATURE(size), buffer,
                 base::Bind(&HidConnectionLinux::FinishSendFeatureReport,
                            weak_factory_.GetWeakPtr(), callback),
                 task_runner_));
}

void HidConnectionLinux::FinishWrite(size_t expected_size,
                                     const WriteCallback& callback,
                                     ssize_t result) {
  if (result < 0) {
    HID_PLOG(EVENT) << "Write failed";
    callback.Run(false);
  } else {
    if (static_cast<size_t>(result) != expected_size) {
      HID_LOG(EVENT) << "Incomplete HID write: " << result
                     << " != " << expected_size;
    }
    callback.Run(true);
  }
}

void HidConnectionLinux::FinishGetFeatureReport(
    uint8_t report_id,
    scoped_refptr<net::IOBuffer> buffer,
    const ReadCallback& callback,
    int result) {
  if (result < 0) {
    HID_PLOG(EVENT) << "Failed to get feature report";
    callback.Run(false, NULL, 0);
  } else if (result == 0) {
    HID_LOG(EVENT) << "Get feature result too short.";
    callback.Run(false, NULL, 0);
  } else if (report_id == 0) {
    // Linux adds a 0 to the beginning of the data received from the device.
    scoped_refptr<net::IOBuffer> copied_buffer(new net::IOBuffer(result - 1));
    memcpy(copied_buffer->data(), buffer->data() + 1, result - 1);
    callback.Run(true, copied_buffer, result - 1);
  } else {
    callback.Run(true, buffer, result);
  }
}

void HidConnectionLinux::FinishSendFeatureReport(const WriteCallback& callback,
                                                 int result) {
  if (result < 0) {
    HID_PLOG(EVENT) << "Failed to send feature report";
    callback.Run(false);
  } else {
    callback.Run(true);
  }
}

// static
void HidConnectionLinux::BlockingWrite(
    base::PlatformFile platform_file,
    scoped_refptr<net::IOBuffer> buffer,
    size_t size,
    const InternalWriteCallback& callback,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  base::ThreadRestrictions::AssertIOAllowed();
  ssize_t result = HANDLE_EINTR(write(platform_file, buffer->data(), size));
  task_runner->PostTask(FROM_HERE, base::Bind(callback, result));
}

// static
void HidConnectionLinux::BlockingIoctl(
    base::PlatformFile platform_file,
    int request,
    scoped_refptr<net::IOBuffer> buffer,
    const IoctlCallback& callback,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  base::ThreadRestrictions::AssertIOAllowed();
  int result = ioctl(platform_file, request, buffer->data());
  task_runner->PostTask(FROM_HERE, base::Bind(callback, result));
}

// static
void HidConnectionLinux::CloseDevice(base::File device_file) {
  device_file.Close();
}

void HidConnectionLinux::ProcessInputReport(scoped_refptr<net::IOBuffer> buffer,
                                            size_t size) {
  DCHECK(thread_checker().CalledOnValidThread());
  PendingHidReport report;
  report.buffer = buffer;
  report.size = size;
  pending_reports_.push(report);
  ProcessReadQueue();
}

void HidConnectionLinux::ProcessReadQueue() {
  DCHECK(thread_checker().CalledOnValidThread());
  while (pending_reads_.size() && pending_reports_.size()) {
    PendingHidRead read = pending_reads_.front();
    PendingHidReport report = pending_reports_.front();

    pending_reports_.pop();
    if (CompleteRead(report.buffer, report.size, read.callback)) {
      pending_reads_.pop();
    }
  }
}

}  // namespace device


text:
package betterwithaddons.item;

import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemLilyPad;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.event.ForgeEventFactory;

public class ItemBlockLilypad extends ItemLilyPad {
    public ItemBlockLilypad(Block block) {
        super(block);
        setRegistryName("minecraft","waterlily");
    }

    @Override
    public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) {
        ItemStack itemstack = playerIn.getHeldItem(handIn);
        RayTraceResult raytraceresult = this.rayTrace(worldIn, playerIn, true);

        if (raytraceresult == null)
        {
            return new ActionResult<>(EnumActionResult.PASS, itemstack);
        }
        else
        {
            if (raytraceresult.typeOfHit == RayTraceResult.Type.BLOCK)
            {
                BlockPos blockpos = raytraceresult.getBlockPos();

                if (!worldIn.isBlockModifiable(playerIn, blockpos) || !playerIn.canPlayerEdit(blockpos.offset(raytraceresult.sideHit), raytraceresult.sideHit, itemstack))
                {
                    return new ActionResult<>(EnumActionResult.FAIL, itemstack);
                }

                BlockPos blockpos1 = blockpos.up();

                if (block.canPlaceBlockAt(worldIn,blockpos1))
                {
                    // special case for handling block placement with water lilies
                    BlockSnapshot blocksnapshot = BlockSnapshot.getBlockSnapshot(worldIn, blockpos1);
                    worldIn.setBlockState(blockpos1, Blocks.WATERLILY.getDefaultState());
                    if (ForgeEventFactory.onPlayerBlockPlace(playerIn, blocksnapshot, net.minecraft.util.EnumFacing.UP, handIn).isCanceled())
                    {
                        blocksnapshot.restore(true, false);
                        return new ActionResult<>(EnumActionResult.FAIL, itemstack);
                    }

                    worldIn.setBlockState(blockpos1, Blocks.WATERLILY.getDefaultState(), 11);

                    if (playerIn instanceof EntityPlayerMP)
                    {
                        CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP)playerIn, blockpos1, itemstack);
                    }

                    if (!playerIn.capabilities.isCreativeMode)
                    {
                        itemstack.shrink(1);
                    }

                    playerIn.addStat(StatList.getObjectUseStats(this));
                    worldIn.playSound(playerIn, blockpos, SoundEvents.BLOCK_WATERLILY_PLACE, SoundCategory.BLOCKS, 1.0F, 1.0F);
                    return new ActionResult<>(EnumActionResult.SUCCESS, itemstack);
                }
            }

            return new ActionResult<>(EnumActionResult.FAIL, itemstack);
        }
    }
}


text:
namespace analyze_ISO
{
	class container_ISO : public _agaliaContainerBase
	{
	protected:
		container_ISO(const wchar_t* path, IStream* stream);
		virtual ~container_ISO();

		virtual HRESULT getColumnCount(uint32_t* count) const override;
		virtual HRESULT getColumnWidth(uint32_t column, int32_t* length) const override;
		virtual HRESULT getColumnName(uint32_t column, agaliaString** str) const override;
		virtual HRESULT getGridRowCount(const agaliaItem* item, uint32_t* row) const override;
		virtual HRESULT getGridValue(const agaliaItem* item, uint32_t row, uint32_t column, agaliaString** str) const override;

		virtual HRESULT getRootItem(agaliaItem** root) const override;

		virtual HRESULT getPropertyValue(PropertyType type, agaliaString** str) const override;
		virtual HRESULT getThumbnailImage(HBITMAP* phBitmap, uint32_t maxW, uint32_t maxH) const override;

	public:
		static _agaliaContainerBase* CreateInstance(const wchar_t* path, IStream* stream);
		static bool IsSupported(IStream* stream);
		static HRESULT GetContainerName(agaliaString** name);
	};
}


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

namespace Umbraco.Web.Search
{
    [DataContract(Name = "searcher", Namespace = "")]
    public class ExamineSearcherModel
    {
        public ExamineSearcherModel()
        {
            ProviderProperties = new Dictionary<string, string>();
        }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "providerProperties")]
        public IDictionary<string, string> ProviderProperties { get; private set; }
    }

}


text:
/**
 * Module dependencies.
 */
var express    = require('express');
var http       = require('http');
var path       = require('path');
var handlebars = require('express3-handlebars')

// Routes
var index          = require('./routes/index');
var error          = require('./routes/error');
var history        = require('./routes/history');
var myaccount      = require('./routes/myaccount');
var sign_in        = require('./routes/sign_in');
var sign_up        = require('./routes/sign_up');
var statistic      = require('./routes/statistic');
var brands         = require('./routes/brands');
var beverages      = require ( './routes/beverages');
var menu           = require('./routes/menu');
var help           = require('./routes/help');
var addCustomDrink = require('./routes/addCustomDrink');
var recommend      = require('./routes/recommend');

// Example route
// var user = require('./routes/user');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Add routes here
app.get('/', index.view);
app.get('/error', error.view);
app.get('/sign_in', sign_in.view);
app.get('/sign_up', sign_up.view);
app.get('/myaccount', myaccount.view);
app.get('/history', history.view);
app.get('/statistic', statistic.view);
app.get('/brands', brands.brands);
app.get('/beverages', beverages.beverages);
app.get('/types', beverages.beverage_types);
app.get('/sizes', beverages.beverage_sizes);
app.get('/menu', menu.menu);
app.get('/helpdoc', help.view);
app.get('/addCustomDrink', addCustomDrink.view);
app.get('/recommendation', recommend.recommend);

// Example route
// app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


text:
package com.facebook.buck.core.rules.actions;

import com.facebook.buck.core.rules.analysis.action.ActionAnalysisData;
import com.facebook.buck.core.rules.analysis.action.ActionAnalysisDataKey;
import com.facebook.buck.core.util.immutables.BuckStyleValue;

/**
 * Implementation of {@link ActionAnalysisData} that just holds an {@link Action}. This mimics the
 * effect of having a deferred
 */
@BuckStyleValue
public interface ActionWrapperData extends ActionAnalysisData {

  @Override
  ActionAnalysisDataKey getKey();

  /** @return the {@link Action} this wraps */
  Action getAction();
}


text:
package com.avast.metrics.statsd;

import com.avast.metrics.TimerPairImpl;
import com.avast.metrics.api.*;
import com.avast.metrics.filter.FilterConfig;
import com.avast.metrics.filter.MetricsFilter;
import com.avast.metrics.test.NoOpMonitor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static org.junit.Assert.assertTrue;

public class StatsDMetricFilterTest {

    private final Class noopMeterClazz = NoOpMonitor.INSTANCE.newMeter("testMonitor").getClass();
    private final Class noopCounterClazz = NoOpMonitor.INSTANCE.newCounter("testCounter").getClass();
    private final Class noopGaugeClazz = NoOpMonitor.INSTANCE.newGauge("testGauge", () -> "").getClass();
    private final Class noopHistogramClazz = NoOpMonitor.INSTANCE.newHistogram("testHistogram").getClass();
    private final Class noopTimerClazz = NoOpMonitor.INSTANCE.newTimer("testTimer").getClass();

    private ScheduledExecutorService scheduler;

    @Before
    public void setUp() {
        scheduler = Executors.newScheduledThreadPool(2);
    }

    @After
    public void tearDown() {
        scheduler.shutdown();
    }

    @Test
    public void testAllDisabled() {
        try (StatsDMetricsMonitor monitor = new StatsDMetricsMonitor("localhost", 80, "test-app", Naming.defaultNaming(), Duration.ofSeconds(1), scheduler, MetricsFilter.ALL_DISABLED)) {
            Meter meter = monitor.newMeter("meter");
            Counter counter = monitor.newCounter("counter");
            Gauge gauge = monitor.newGauge("gauge", () -> "");
            Histogram histogram = monitor.newHistogram("histogram");
            Timer timer = monitor.newTimer("timer");
            TimerPair timerPair = monitor.newTimerPair("timerPair");

            assertTrue(meter.getClass().equals(noopMeterClazz));
            assertTrue(counter.getClass().equals(noopCounterClazz));
            assertTrue(gauge.getClass().equals(noopGaugeClazz));
            assertTrue(histogram.getClass().equals(noopHistogramClazz));
            assertTrue(timer.getClass().equals(noopTimerClazz));
            assertTrue(timerPair.getClass().equals(TimerPairImpl.class)); // no-op are timers inside
        }
    }

    @Test
    public void testAllEnabled() {
        try (StatsDMetricsMonitor monitor = new StatsDMetricsMonitor("localhost", 80, "test-app", Naming.defaultNaming(), Duration.ofSeconds(1), scheduler, MetricsFilter.ALL_ENABLED)) {
            Meter meter = monitor.newMeter("meter");
            Counter counter = monitor.newCounter("counter");
            Gauge gauge = monitor.newGauge("gauge", () -> "");
            Histogram histogram = monitor.newHistogram("histogram");
            Timer timer = monitor.newTimer("timer");
            TimerPair timerPair = monitor.newTimerPair("timerPair");

            assertTrue(meter.getClass().equals(StatsDMeter.class));
            assertTrue(counter.getClass().equals(StatsDCounter.class));
            assertTrue(gauge.getClass().equals(StatsDGauge.class));
            assertTrue(histogram.getClass().equals(StatsDHistogram.class));
            assertTrue(timer.getClass().equals(StatsDTimer.class));
            assertTrue(timerPair.getClass().equals(TimerPairImpl.class));
        }
    }

    @Test
    public void testFiltered() {
        FilterConfig filterConfigRoot = new FilterConfig("root", true);
        FilterConfig filterConfig = new FilterConfig("level1.level2", false);
        MetricsFilter metricsFilter = buildMetricsFilter(filterConfigRoot, filterConfig);

        try (final StatsDMetricsMonitor monitor = buildMonitor(metricsFilter).named("level1")) {
            Meter meter = monitor.newMeter("level2");
            Counter counter = monitor.newCounter("level2");
            Gauge gauge = monitor.newGauge("level2", () -> "");
            Histogram histogram = monitor.newHistogram("level2");
            Timer timer = monitor.newTimer("level2");
            TimerPair timerPair = monitor.newTimerPair("level2");

            assertTrue(meter.getClass().equals(noopMeterClazz));
            assertTrue(counter.getClass().equals(noopCounterClazz));
            assertTrue(gauge.getClass().equals(noopGaugeClazz));
            assertTrue(histogram.getClass().equals(noopHistogramClazz));
            assertTrue(timer.getClass().equals(noopTimerClazz));
            assertTrue(timerPair.getClass().equals(TimerPairImpl.class)); // no-op are timers inside
        }
    }

    @Test
    public void testNotFiltered() {
        FilterConfig filterConfigRoot = new FilterConfig("root", false);
        FilterConfig filterConfig = new FilterConfig("level1.level2", true);
        MetricsFilter metricsFilter = buildMetricsFilter(filterConfigRoot, filterConfig);

        try (final StatsDMetricsMonitor monitor = buildMonitor(metricsFilter).named("level1")) {
            Meter meter = monitor.newMeter("level2");
            Counter counter = monitor.newCounter("level2");
            Gauge gauge = monitor.newGauge("level2", () -> "");
            Histogram histogram = monitor.newHistogram("level2");
            Timer timer = monitor.newTimer("level2");
            TimerPair timerPair = monitor.newTimerPair("level2");

            assertTrue(meter.getClass().equals(StatsDMeter.class));
            assertTrue(counter.getClass().equals(StatsDCounter.class));
            assertTrue(gauge.getClass().equals(StatsDGauge.class));
            assertTrue(histogram.getClass().equals(StatsDHistogram.class));
            assertTrue(timer.getClass().equals(StatsDTimer.class));
            assertTrue(timerPair.getClass().equals(TimerPairImpl.class));
        }
    }

    @Test
    public void testNestedMonitor() {
        FilterConfig filterConfigRoot = new FilterConfig("root", false);
        FilterConfig filterConfigMeter = new FilterConfig("level1.level2.meter", true);
        FilterConfig filterConfigCounter = new FilterConfig("level1.level2.counter", false);
        FilterConfig filterConfigGauge = new FilterConfig("level1.level2.gauge", true);
        FilterConfig filterConfigHistogram = new FilterConfig("level1.level2.histogram", false);
        FilterConfig filterConfigTimer = new FilterConfig("level1.level2.timer", true);
        FilterConfig filterConfigTimerPair = new FilterConfig("level1.level2.timePair", false);

        MetricsFilter metricsFilter = buildMetricsFilter(
                filterConfigRoot,
                filterConfigMeter,
                filterConfigCounter,
                filterConfigGauge,
                filterConfigHistogram,
                filterConfigTimer,
                filterConfigTimerPair
        );

        try (StatsDMetricsMonitor monitor = buildMonitor(metricsFilter).named("level1").named("level2")) {
            Meter meter = monitor.newMeter("meter");
            Counter counter = monitor.newCounter("counter");
            Gauge gauge = monitor.newGauge("gauge", () -> "");
            Histogram histogram = monitor.newHistogram("histogram");
            Timer timer = monitor.newTimer("timer");
            TimerPair timerPair = monitor.newTimerPair("timePair");

            assertTrue(meter.getClass().equals(StatsDMeter.class));
            assertTrue(counter.getClass().equals(noopCounterClazz));
            assertTrue(gauge.getClass().equals(StatsDGauge.class));
            assertTrue(histogram.getClass().equals(noopHistogramClazz));
            assertTrue(timer.getClass().equals(StatsDTimer.class));
            assertTrue(timerPair.getClass().equals(TimerPairImpl.class)); // no-op are timers inside
        }
    }

    private StatsDMetricsMonitor buildMonitor(MetricsFilter metricsFilter) {
        return new StatsDMetricsMonitor("localhost", 80, "test-app", Naming.defaultNaming(), Duration.ofSeconds(1), scheduler, metricsFilter);
    }

    private MetricsFilter buildMetricsFilter(FilterConfig... filterConfigs) {
        List<FilterConfig> filterConfigsList = new ArrayList<>();
        Collections.addAll(filterConfigsList, filterConfigs);
        return MetricsFilter.newInstance(filterConfigsList, ".");
    }
}


text:
<?php

// This is a simplified example, which doesn't cover security of uploaded images.
// This example just demonstrate the logic behind the process.

// files storage folder
$dir = '/advanced/uploads/';

$_FILES['file']['type'] = strtolower($_FILES['file']['type']);

if ($_FILES['file']['type'] == 'image/png'
|| $_FILES['file']['type'] == 'image/jpg'
|| $_FILES['file']['type'] == 'image/gif'
|| $_FILES['file']['type'] == 'image/jpeg'
|| $_FILES['file']['type'] == 'image/pjpeg')
{
    // setting file's mysterious name
    $filename = md5(date('YmdHis')).'.jpg';
    $file = $dir.$filename;

    // copying
    move_uploaded_file($_FILES['file']['tmp_name'], $file);

    // displaying file
    $array = array(
        'url' => 'uploads/'.$filename,
        'id' => 123
    );

    echo stripslashes(json_encode($array));

}

?>


text:
from flask import Flask
from flask import request
from flask import session
from flask import make_response
from flask import redirect
from flask import abort

print('Starting flask app named {}'.format(__name__))
app = Flask(__name__)

@app.route('/')
def index():
    response = '''

    <title>Hello you!</title>

Hello World!!!

    You're coming to me via {}
    With full request details:
    {}
    With session:
    {}

    '''
    user_agent = request.headers.get('User-Agent')
    response = response.format(user_agent,request.headers,session)
    response = make_response(response)
    response.set_cookie('answer', '42')
    return response

@app.route('/help')
def help_index():
    response = '''

    <title>Support</title>

Call your parents.

    '''
    return response

@app.route('/user/names/<name>')
def user(name):
    response = '''

    <title>Support</title>

Call your parents, {}!

    '''
    response = response.format(name)
    return response

@app.route('/redirect')
def redirect_me():
    return redirect('http://www.nyu.edu')

def load_user(id):
    print(type(id))
    if (int(id) == 1):
        return 'rob'
    else:
        return None

@app.route('/user/ids/<id>')
def get_user(id):
    user = load_user(id)
    if not user:
        abort(403)
    return '
Hello, %s
' % user

if __name__ == '__main__':
    # main line
    app.run(host='0.0.0.0',debug=False)
    #app.run(debug=True)


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, Emory University,
*  the University of Minnesota Supercomputing Institute
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details.
*============================================================================
**/
/**
*============================================================================
*============================================================================
**/
package org.cagrid.introduce.service1.service;

import org.cagrid.introduce.service1.service.globus.resource.Service1Resource;
import  org.cagrid.introduce.service1.service.Service1Configuration;

import java.rmi.RemoteException;

import javax.naming.InitialContext;
import javax.xml.namespace.QName;

import org.apache.axis.MessageContext;
import org.globus.wsrf.Constants;
import org.globus.wsrf.ResourceContext;
import org.globus.wsrf.ResourceContextException;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceHome;
import org.globus.wsrf.ResourceProperty;
import org.globus.wsrf.ResourcePropertySet;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * Provides some simple accessors for the Impl.
 *
 * @created by Introduce Toolkit version 1.2
 *
 */
public abstract class Service1ImplBase {

	public Service1ImplBase() throws RemoteException {

	}

	public Service1Configuration getConfiguration() throws Exception {
		return Service1Configuration.getConfiguration();
	}

	public org.cagrid.introduce.service1.service.globus.resource.Service1ResourceHome getResourceHome() throws Exception {
		ResourceHome resource = getResourceHome("home");
		return (org.cagrid.introduce.service1.service.globus.resource.Service1ResourceHome)resource;
	}

	protected ResourceHome getResourceHome(String resourceKey) throws Exception {
		MessageContext ctx = MessageContext.getCurrentContext();

		ResourceHome resourceHome = null;

		String servicePath = ctx.getTargetService();

		String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/" + resourceKey;
		try {
			javax.naming.Context initialContext = new InitialContext();
			resourceHome = (ResourceHome) initialContext.lookup(jndiName);
		} catch (Exception e) {
			throw new Exception("Unable to instantiate resource home. : " + resourceKey, e);
		}

		return resourceHome;
	}

}


text:
/**
 *
 */
package com.happy3w.autobuy.action;

/**
 * 获取表格中内容的Xpath.
 * @version 2016年10月19日上午11:43:53
 * @author happy3w
 */
public class TableXPath {
	/**
	 * 表格的xpath.
	 */
	private String table;
	/**
	 * 相对于表格的row的xpath.
	 */
	private String row;
	/**
	 * 获取值需要满足的条件,row中的cell.
	 */
	private String condition;
	/**
	 * 满足条件后,需要取得的对象,row中的cell.
	 */
	private String target;

	public String getTable() {
		return table;
	}
	public void setTable(String table) {
		this.table = table;
	}
	public String getRow() {
		return row;
	}
	public void setRow(String row) {
		this.row = row;
	}
	public String getFilter() {
		return condition;
	}
	public void setFilter(String product) {
		this.condition = product;
	}
	public String getTarget() {
		return target;
	}
	public void setTarget(String target) {
		this.target = target;
	}

}


text:
package org.command4spring.jms.service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.command4spring.example.SampleCommand;
import org.command4spring.example.SampleResult;
import org.command4spring.exception.DispatchException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-jms-with-response-test.xml"})
public class JmsDispatcherServiceWithResultTest {

	@Autowired
	JmsDispatcherService jmsDispatcherService;

	@Test
	public void testSynchronousJmsExecution() throws DispatchException, InterruptedException, ExecutionException, TimeoutException {
		SampleCommand command=new SampleCommand();
		Future<SampleResult> futureResult=this.jmsDispatcherService.dispatch(command);
		SampleResult result=futureResult.get(5, TimeUnit.SECONDS);
		Assert.assertEquals(command.getCommandId(), result.getCommandId());
	}

}


text:
<!DOCTYPE html>

<title>Canvas test: 2d.composite.clip.source-out</title>

<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="minimal.2d.composite.clip.destination-in.html" title="2d.composite.clip.destination-in">
<link rel="next" href="minimal.2d.composite.clip.destination-out.html" title="2d.composite.clip.destination-out">

Pass

Fail

These images should be identical:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
WebServer
=========

A .Net Micro Framework Web Server targeting Netduino Plus 2 and NETMF version 4.3

Introduction
-----------

When you would like to build a rich Web API on a Netduino device for control of any hardware and much more.

Web address to this example
http://192.168.1.100/MyFirst

    public class Program
    {
        public static void Main()
        {
            var webServer = new WebServer();
            webServer.Start(80);
        }
    }

    public class MyFirstController : Controller
    {
        public void Index()
        {
            SetHtmlResult("<!DOCTYPE html>
My page
");
        }
    }

###Json return type support

{"id": 1,"name": "My name","status": True,"myList": [1, 2, 3],"myOtherClass": {"innerName": "My inner name","innerStatus":      False}}

    public class JsonController : Controller
    {
        public void Index()
        {
            var myClass = new MyClass
            {
                Id = 1,
                Name = "My name",
                Status = true,
                MyList = new ArrayList { 1, 2, 3 },
                MyOtherClass = new MyOtherClass
                {
                    InnerName = "My inner name",
                    InnerStatus = false,
                }
            };
            SetJsonResult(myClass);
        }
    }

    public class MyClass
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool Status { get; set; }

        public ArrayList MyList { get; set; }

        public MyOtherClass MyOtherClass { get; set; }
    }

    public class MyOtherClass
    {
        public string InnerName { get; set; }

        public bool InnerStatus { get; set; }
    }

###Default Controller and Method

To add a default controller and to change the default controller method, default method name is Index and default controller name is empty string (not defined)

    public class Program
    {
        public static void Main()
        {
            var webServer = new WebServer();
            webServer.RouteTable.DefaultControllerName = "Default";
            webServer.RouteTable.DefaultMethodName = "MyMethodName";
            webServer.StartServer();
        }
    }

    public class DefaultController : Controller
    {
        public void MyMethodName()
        {
            SetHtmlResult("<!DOCTYPE html>
Default controller example
");
        }
    }

#Getting Started
---------------

## Run Demo web
1. Download Rinsen/WebServer.
2. Set desired .Net Micro Framework Deployment type in DemoWeb
3. Build and Start
4. Locate Output - Debug in Visual Studio
5. Copy http address
6. Run address in browser and add example name at the end http://192.168.1.x:8500/ Put example name here

### Examples
1. Blink
2. DataModelBinder
3. FormCollection
4. Exception
5. Exception/InnerException
6. Json
7. DontLetMeIn

## Unit tests
Unit tests is based on MFUnit, MFUnit is included via NuGet

https://github.com/ducas/MFUnit/
### Run unit tests
1. Set Rinsen.WebServer.UnitTests as StartUp Project
2. Set Deployment option to Emulator
3. Build and Run


text:
CKEDITOR.editorConfig = function( config ) {

	// %REMOVE_START%
	// The configuration options below are needed when running CKEditor from source files.
	config.plugins = 'dialogui,dialog,about,a11yhelp,basicstyles,blockquote,clipboard,panel,floatpanel,menu,contextmenu,resize,button,toolbar,elementspath,enterkey,entities,popup,filebrowser,floatingspace,listblock,richcombo,format,horizontalrule,htmlwriter,wysiwygarea,image,indent,indentlist,fakeobjects,link,list,magicline,maximize,pastetext,pastefromword,removeformat,showborders,sourcearea,specialchar,menubutton,scayt,stylescombo,tab,table,tabletools,undo,wsc,save,closebtn,inlinecancel';
	config.skin = 'icy_orange';
	// %REMOVE_END%

	// Define changes to default configuration here.
	// For complete reference see:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		{ name: 'forms' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons provided by the standard plugins, which are
	// not needed in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Set the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre';

	// Simplify the dialog windows.
	config.removeDialogTabs = 'image:advanced;link:advanced';
};


text:
#ifndef MSVCFCNTL_H
#define MSVCFCNTL_H

//#include <../ucrt/fcntl.h>

#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

#define O_NDELAY    _FNDELAY

#define _FNONBLOCK  0x4000  /* non blocking I/O (POSIX style) */
#define O_NONBLOCK  _FNONBLOCK

#define _FOPEN      (-1)    /* from sys/file.h, kernel use only */
#define _FREAD      0x0001  /* read enabled */
#define _FWRITE     0x0002  /* write enabled */
#define _FAPPEND    0x0008  /* append (writes guaranteed at the end) */
#define _FMARK      0x0010  /* internal; mark during gc() */
#define _FDEFER     0x0020  /* internal; defer for next gc pass */
#define _FASYNC     0x0040  /* signal pgrp when data ready */
#define _FSHLOCK    0x0080  /* BSD flock() shared lock present */
#define _FEXLOCK    0x0100  /* BSD flock() exclusive lock present */
#define _FCREAT     0x0200  /* open with file create */
#define _FTRUNC     0x0400  /* open with truncation */
#define _FEXCL      0x0800  /* error on open if file exists */
#define _FNBIO      0x1000  /* non blocking I/O (sys5 style) */
#define _FSYNC      0x2000  /* do all writes synchronously */
#define _FNONBLOCK  0x4000  /* non blocking I/O (POSIX style) */
#define _FNDELAY    _FNONBLOCK  /* non blocking I/O (4.2 style) */
#define _FNOCTTY    0x8000  /* don't assign a ctty on this open */

#define O_ACCMODE   (O_RDONLY|O_WRONLY|O_RDWR)

/* XXX close on exec request; must match UF_EXCLOSE in user.h */
#define FD_CLOEXEC  1   /* posix */

/* fcntl(2) requests */
#define F_DUPFD     0   /* Duplicate fildes */
#define F_GETFD     1   /* Get fildes flags (close on exec) */
#define F_SETFD     2   /* Set fildes flags (close on exec) */
#define F_GETFL     3   /* Get file flags */
#define F_SETFL     4   /* Set file flags */

#ifndef _POSIX_SOURCE
# define    F_GETOWN    5   /* Get owner - for ASYNC */
# define    F_SETOWN    6   /* Set owner - for ASYNC */
#endif  /* !_POSIX_SOURCE */

#define F_GETLK     7   /* Get record-locking information */
#define F_SETLK     8   /* Set or Clear a record-lock (Non-Blocking) */
#define F_SETLKW    9   /* Set or Clear a record-lock (Blocking) */

#ifndef _POSIX_SOURCE
# define    F_RGETLK    10  /* Test a remote lock to see if it is blocked */
# define    F_RSETLK    11  /* Set or unlock a remote lock */
# define    F_CNVT      12  /* Convert a fhandle to an open fd */
# define    F_RSETLKW   13  /* Set or Clear remote record-lock(Blocking) */
#endif  /* !_POSIX_SOURCE */

/* fcntl(2) flags (l_type field of flock structure) */
#define F_RDLCK     1   /* read lock */
#define F_WRLCK     2   /* write lock */
#define F_UNLCK     3   /* remove lock(s) */

#ifndef _POSIX_SOURCE
# define    F_UNLKSYS   4   /* remove remote locks for a given system */
#endif  /* !_POSIX_SOURCE */

/* not implemented: int KDEWIN_EXPORT __cdecl fcntl (int fd, int cmd,...); */

#ifdef __cplusplus
}
#endif

#endif // MSVCFCNTL_H


text:
// ReSharper disable UnusedParameter.Global
namespace Apache.Ignite.Service
{
    using System;
    using Apache.Ignite.Core;

    /// <summary>
    /// .NET Core implementation of Ignite Service.
    /// </summary>
    public static class IgniteService
    {
        /// <summary>
        /// Uninstall the service.
        /// </summary>
        public static void Uninstall()
        {
            throw GetNotSupportedException();
        }

        /// <summary>
        /// Install the service.
        /// </summary>
        public static void DoInstall(Tuple<string, string>[] allArgs)
        {
            throw GetNotSupportedException();
        }

        /// <summary>
        /// Run the service.
        /// </summary>
        public static void Run(IgniteConfiguration cfg)
        {
            throw GetNotSupportedException();
        }

        /// <summary>
        /// Gets the exception.
        /// </summary>
        private static Exception GetNotSupportedException()
        {
            // Not supported right now, we should add cross-platform support when .NET Core 3 rolls out:
            // Windows Services and systemd on Linux).
            return new NotSupportedException("Ignite as Windows Service is not supported on .NET Core.");
        }
    }
}