text:
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter;
using System.Web.OData.TestCommon;
using System.Web.OData.TestCommon.Models;
using Microsoft.OData.Edm;
using Microsoft.OData.UriParser;
using Microsoft.TestCommon;
using ODataPath = System.Web.OData.Routing.ODataPath;

namespace System.Web.OData
{
    public class DeltaTest
    {
        public static IEnumerable<object[]> DeltaModelPropertyNamesData
        {
            get
            {
                MethodInfo getDefaultValue = typeof(DeltaTest).GetMethod("GetDefaultValue");

                var defaultValues = typeof(DeltaModel).GetProperties().Select(p => new[] { p.Name, getDefaultValue.MakeGenericMethod(p.PropertyType).Invoke(obj: null, parameters: null) });
                return defaultValues.Concat(new object[][]
                {
                    new object[] { "StringProperty" , "42" },
                    new object[] { "ComplexModelProperty", new ComplexModel { ComplexIntProperty = 42, ComplexNullableIntProperty = null } },
                    new object[] { "CollectionProperty", new Collection<int> { 1, 2, 3 }}
                });
            }
        }

        [Fact]
        public void Ctor_ThrowsArgumentNull_entityType()
        {
            Assert.ThrowsArgumentNull(() => new Delta<Base>(structuralType: null), "structuralType");
        }

        [Fact]
        public void Ctor_ThrowsInvalidOperation_If_EntityType_IsNotAssignable_To_TEntityType()
        {
            Assert.Throws<InvalidOperationException>(
                () => new Delta<Derived>(typeof(AnotherDerived)),
                "The actual entity type 'System.Web.OData.DeltaTest+AnotherDerived' is not assignable to the expected type 'System.Web.OData.DeltaTest+Derived'.");
        }

        [Fact]
        public void Can_Declare_A_Delta_Of_An_AbstractClass()
        {
            Delta<AbstractBase> abstractDelta = null;
            Assert.Null(abstractDelta);
        }

        [Theory]
        [PropertyData("DeltaModelPropertyNamesData")]
        public void RoundTrip_Properties(string propertyName, object value)
        {
            Delta<DeltaModel> delta = new Delta<DeltaModel>();

            Type propertyType;
            Assert.True(delta.TryGetPropertyType(propertyName, out propertyType));

            Assert.True(delta.TrySetPropertyValue(propertyName, value));

            object retrievedValue;
            delta.TryGetPropertyValue(propertyName, out retrievedValue);
            Assert.Equal(value, retrievedValue);
        }

        [Fact]
        public void CanGetChangedPropertyNames()
        {
            var original = new AddressEntity { ID = 1, City = "Redmond", State = "NY", StreetAddress = "21110 NE 44th St", ZipCode = 98074 };

            dynamic delta = new Delta<AddressEntity>();
            var idelta = delta as IDelta;
            // modify in the way we expect the formatter too.
            idelta.TrySetPropertyValue("City", "Sammamish");
            Assert.Equal(1, idelta.GetChangedPropertyNames().Count());
            Assert.Equal("City", idelta.GetChangedPropertyNames().Single());

            // read the property back
            object city = null;
            Assert.True(idelta.TryGetPropertyValue("City", out city));
            Assert.Equal("Sammamish", city);

            // modify the way people will through custom code
            delta.StreetAddress = "23213 NE 15th Ct";
            var mods = idelta.GetChangedPropertyNames().ToArray();
            Assert.Equal(2, mods.Count());
            Assert.True(mods.Contains("StreetAddress"));
            Assert.True(mods.Contains("City"));
            Assert.Equal("23213 NE 15th Ct", delta.StreetAddress);
        }

        [Fact]
        public void CanReadUnmodifiedDefaultValuesFromDelta()
        {
            dynamic patch = new Delta<AddressEntity>();
            Assert.Equal(0, patch.ID);
            Assert.Null(patch.City);
            Assert.Null(patch.State);
            Assert.Null(patch.StreetAddress);
            Assert.Equal(0, patch.ZipCode);
        }

        [Fact]
        public void CanPatch()
        {
            var original = new AddressEntity { ID = 1, City = "Redmond", State = "WA", StreetAddress = "21110 NE 44th St", ZipCode = 98074 };

            dynamic delta = new Delta<AddressEntity>();
            delta.City = "Sammamish";
            delta.StreetAddress = "23213 NE 15th Ct";

            delta.Patch(original);
            // unchanged
            Assert.Equal(1, original.ID);
            Assert.Equal(98074, original.ZipCode);
            Assert.Equal("WA", original.State);
            // changed
            Assert.Equal("Sammamish", original.City);
            Assert.Equal("23213 NE 15th Ct", original.StreetAddress);
        }

        [Fact]
        public void CanPatch_OpenType()
        {
            // Arrange
            var address = new SimpleOpenAddress
            {
                City = "City",
                Street = "Street",
                Properties = new Dictionary<string, object>
                {
                    { "IntProp", 9 },
                    { "ListProp", new List<int> {1, 2, 3} }
                }
            };

            PropertyInfo propertyInfo = typeof(SimpleOpenAddress).GetProperty("Properties");
            var delta = new Delta<SimpleOpenAddress>(typeof(SimpleOpenAddress), null, propertyInfo);
            delta.TrySetPropertyValue("City", "ChangedCity");
            delta.TrySetPropertyValue("IntProp", 1);

            // Act
            delta.Patch(address);

            // Assert
            // unchanged
            Assert.Equal("Street", address.Street);
            Assert.Equal(new List<int> { 1, 2, 3 }, address.Properties["ListProp"]);

            // changed
            Assert.Equal("ChangedCity", address.City);
            Assert.Equal(1, address.Properties["IntProp"]);
        }

        [Fact]
        public void CanPut_OpenType()
        {
            // Arrange
            var address = new SimpleOpenAddress
            {
                City = "City",
                Street = "Street",
                Properties = new Dictionary<string, object>
                {
                    { "IntProp", 9 },
                    { "ListProp", new List<int> {1, 2, 3} }
                }
            };

            PropertyInfo propertyInfo = typeof(SimpleOpenAddress).GetProperty("Properties");
            var delta = new Delta<SimpleOpenAddress>(typeof(SimpleOpenAddress), null, propertyInfo);
            delta.TrySetPropertyValue("City", "ChangedCity");
            delta.TrySetPropertyValue("IntProp", 1);

            // Act
            delta.Put(address);

            // Assert
            Assert.Equal("ChangedCity", address.City);
            Assert.Null(address.Street);
            Assert.Equal(1, address.Properties["IntProp"]);
            Assert.False(address.Properties.ContainsKey("ListProp"));
        }

        [Fact]
        public void CanCopyUnchangedValues()
        {
            var original = new AddressEntity { ID = 1, City = "Redmond", State = "WA", StreetAddress = "21110 NE 44th St", ZipCode = 98074 };

            dynamic delta = new Delta<AddressEntity>();
            delta.City = "Sammamish";
            delta.StreetAddress = "23213 NE 15th Ct";
            var idelta = delta as Delta<AddressEntity>;
            idelta.CopyUnchangedValues(original);
            // unchanged values have been reset to defaults
            Assert.Equal(0, original.ID);
            Assert.Equal(0, original.ZipCode);
            Assert.Equal(null, original.State);
            // changed values have been left unmodified
            Assert.Equal("Redmond", original.City);
            Assert.Equal("21110 NE 44th St", original.StreetAddress);
        }

        [Fact]
        public void CanPut()
        {
            var original = new AddressEntity { ID = 1, City = "Redmond", State = "WA", StreetAddress = "21110 NE 44th St", ZipCode = 98074 };

            dynamic delta = new Delta<AddressEntity>();
            delta.City = "Sammamish";
            delta.StreetAddress = "23213 NE 15th Ct";
            var idelta = delta as Delta<AddressEntity>;
            idelta.Put(original);

            // unchanged values have been reset to defaults
            Assert.Equal(0, original.ID);
            Assert.Equal(0, original.ZipCode);
            Assert.Equal(null, original.State);
            // changed values have been updated to values in delta
            Assert.Equal("Sammamish", original.City);
            Assert.Equal("23213 NE 15th Ct", original.StreetAddress);
        }

        [Fact]
        public void CanClear()
        {
            dynamic delta = new Delta<AddressEntity>();
            delta.StreetAddress = "Test";
            var idelta = delta as IDelta;
            Assert.Equal(1, idelta.GetChangedPropertyNames().Count());
            idelta.Clear();
            Assert.Equal(0, idelta.GetChangedPropertyNames().Count());
        }

        [Fact]
        public void CanCreateDeltaOfDerivedTypes()
        {
            var delta = new Delta<Base>(typeof(Derived));
            Assert.IsType(typeof(Derived), delta.GetInstance());
        }

        [Fact]
        public void CanChangeDerivedClassProperties()
        {
            // Arrange
            dynamic delta = new Delta<Base>(typeof(Derived));

            // Act
            delta.DerivedInt = 10;

            // Assert
            Assert.Equal(delta.GetChangedPropertyNames(), new[] { "DerivedInt" });
        }

        [Fact]
        public void Patch_Patches_DerivedTypeProperties()
        {
            // Arrange
            dynamic delta = new Delta<Base>(typeof(Derived));
            delta.DerivedInt = 42;
            Derived derived = new Derived();

            // Act
            delta.Patch(derived);

            // Assert
            Assert.Equal(42, derived.DerivedInt);
            Assert.Equal(0, derived.BaseInt);
            Assert.Null(derived.BaseString);
            Assert.Null(derived.DerivedString);
        }

        [Fact]
        public void Put_Clears_DerivedTypeProperties()
        {
            // Arrange
            dynamic delta = new Delta<Base>(typeof(Derived));
            delta.DerivedInt = 24;
            Derived derived = new Derived { BaseInt = 42, DerivedInt = 0, BaseString = "42", DerivedString = "42" };

            // Act
            delta.Put(derived);

            // Assert
            Assert.Equal(24, derived.DerivedInt);
            Assert.Equal(0, derived.BaseInt);
            Assert.Null(derived.BaseString);
            Assert.Null(derived.DerivedString);
        }

        [Fact]
        public void Put_DoesNotClear_PropertiesNotOnEntityType()
        {
            // Arrange
            dynamic delta = new Delta<Base>(typeof(Derived));
            delta.DerivedInt = 24;
            DerivedDerived derived = new DerivedDerived { BaseInt = 42, DerivedInt = 0, BaseString = "42", DerivedString = "42", DerivedDerivedInt = 42, DerivedDerivedString = "42" };

            // Act
            delta.Put(derived);

            // Assert
            Assert.Equal("42", derived.DerivedDerivedString);
            Assert.Equal(42, derived.DerivedDerivedInt);
        }

        [Fact]
        public void Put_DoesNotClear_NonUpdatableProperties()
        {
            // Arrange
            string expectedString = "hello, world";
            int expectedInt = 24;
            var delta = new Delta<Base>(typeof(Base), new[] { "BaseInt" });
            delta.TrySetPropertyValue("BaseInt", expectedInt);

            Base entity = new Base { BaseInt = 42, BaseString = expectedString };

            // Act
            delta.Put(entity);

            // Assert
            Assert.Equal(expectedInt, entity.BaseInt);
            Assert.Equal(expectedString, entity.BaseString);
        }

        [Fact]
        public void Patch_ClearsAndAddsTo_CollectionPropertiesWithNoSetter()
        {
            // Arrange
            dynamic delta = new Delta<DeltaModelWithCollection>();
            delta.CollectionPropertyWithoutSet = new[] { 1, 2, 3 };
            DeltaModelWithCollection model = new DeltaModelWithCollection { CollectionPropertyWithoutSet = { 42 } };

            // Act
            delta.Patch(model);

            // Assert
            Assert.Equal(new[] { 1, 2, 3 }, model.CollectionPropertyWithoutSet);
        }

        [Fact]
        public void Delta_Fails_IfCollectionPropertyDoesNotHaveSetAndHasNullValue()
        {
            // Arrange
            dynamic delta = new Delta<InvalidDeltaModel>();

            // Act & Assert
            Assert.Throws<SerializationException>(
                () => delta.CollectionPropertyWithoutSetAndNullValue = new[] { "1" },
                "The property 'CollectionPropertyWithoutSetAndNullValue' on type 'System.Web.OData.DeltaTest+InvalidD" +
                "eltaModel' returned a null value. The input stream contains collection items which cannot be added if " +
                "the instance is null.");
        }

        [Fact]
        public void Delta_Fails_IfCollectionPropertyDoesNotHaveSetAndClear()
        {
            // Arrange
            dynamic delta = new Delta<InvalidDeltaModel>();

            // Act & Assert
            Assert.Throws<SerializationException>(
                () => delta.CollectionPropertyWithoutSetAndClear = new[] { "1" },
                "The type 'System.Int32[]' of the property 'CollectionPropertyWithoutSetAndClear' on type 'System.Web." +
                "OData.DeltaTest+InvalidDeltaModel' does not have a Clear method. Consider using a collection type" +
                " that does have a Clear method, such as IList<T> or ICollection<T>.");
        }

        [Fact]
        public void Patch_UnRelatedType_Throws_Argument()
        {
            // Arrange
            Delta<Base> delta = new Delta<Base>(typeof(Derived));
            AnotherDerived unrelatedEntity = new AnotherDerived();

            // Act & Assert
            Assert.ThrowsArgument(
                () => delta.Patch(unrelatedEntity),
                "original",
                "Cannot use Delta of type 'System.Web.OData.DeltaTest+Derived' on an entity of type 'System.Web.OData.DeltaTest+AnotherDerived'.");
        }

        [Fact]
        public void Put_UnRelatedType_Throws_Argument()
        {
            // Arrange
            Delta<Base> delta = new Delta<Base>(typeof(Derived));
            AnotherDerived unrelatedEntity = new AnotherDerived();

            // Act & Assert
            Assert.ThrowsArgument(
                () => delta.Put(unrelatedEntity),
                "original",
                "Cannot use Delta of type 'System.Web.OData.DeltaTest+Derived' on an entity of type 'System.Web.OData.DeltaTest+AnotherDerived'.");
        }

        [Fact]
        public void CopyChangedValues_UnRelatedType_Throws_Argument()
        {
            // Arrange
            Delta<Base> delta = new Delta<Base>(typeof(Derived));
            AnotherDerived unrelatedEntity = new AnotherDerived();

            // Act & Assert
            Assert.ThrowsArgument(
                () => delta.CopyChangedValues(unrelatedEntity),
                "original",
                "Cannot use Delta of type 'System.Web.OData.DeltaTest+Derived' on an entity of type 'System.Web.OData.DeltaTest+AnotherDerived'.");
        }

        [Fact]
        public void CopyUnchangedValues_UnRelatedType_Throws_Argument()
        {
            // Arrange
            Delta<Base> delta = new Delta<Base>(typeof(Derived));
            AnotherDerived unrelatedEntity = new AnotherDerived();

            // Act & Assert
            Assert.ThrowsArgument(
                () => delta.CopyUnchangedValues(unrelatedEntity),
                "original",
                "Cannot use Delta of type 'System.Web.OData.DeltaTest+Derived' on an entity of type 'System.Web.OData.DeltaTest+AnotherDerived'.");
        }

        public static TheoryDataSet<string, string, object> ODataFormatter_Can_Read_Delta_DataSet
        {
            get
            {
                return new TheoryDataSet<string, string, object>()
                {
                    { "IntProperty", "23", 23 },
                    { "LongProperty", String.Format(CultureInfo.InvariantCulture, "'{0}'", Int64.MaxValue), Int64.MaxValue }, // longs are serialized as strings in odata json
                    { "LongProperty", String.Format(CultureInfo.InvariantCulture, "'{0}'", Int64.MinValue), Int64.MinValue }, // longs are serialized as strings in odata json
                    { "NullableIntProperty", "null", null },
                    { "BoolProperty", "true", true },
                    { "NullableBoolProperty", "null", null },
                    // TODO: Investigate how to add support for DataTime in webapi.odata, ODataLib v4 does not support it.
                    // { "DateTimeProperty", "'1992-01-01'", new DateTime(1992, 1, 1) },
                    { "DateTimeOffsetProperty", "'1992-01-01'", new DateTimeOffset(new DateTime(1992, 1, 1)) },
                    { "NullableDateTimeOffsetProperty", "'1992-01-01'", new DateTimeOffset(new DateTime(1992, 1, 1)) },
                    { "NullableDateTimeOffsetProperty", "null", null },
                    { "DateProperty", "'1997-07-01'", new Date(1997, 7, 1) },
                    { "NullableDateProperty", "null", null },
                    { "TimeOfDayProperty", "'10:11:12.0130000'", new TimeOfDay(10, 11, 12, 13) },
                    { "NullableTimeOfDayProperty", "null", null },
                    { "StringProperty", "'42'", "42" },
                    { "ComplexModelProperty", "{ 'ComplexIntProperty' : 42 }", new ComplexModel { ComplexIntProperty = 42 } },
                    { "CollectionProperty", "[ 1, 2, 3 ]", new Collection<int> { 1, 2, 3} },
                    { "ComplexModelCollectionProperty", "[ { 'ComplexIntProperty' : 42 } ]", new Collection<ComplexModel> { new ComplexModel { ComplexIntProperty = 42 } } }
                };
            }
        }

        [Theory]
        [PropertyData("ODataFormatter_Can_Read_Delta_DataSet")]
        public void ODataFormatter_Can_Read_Delta(string propertyName, string propertyJsonValue, object expectedValue)
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock<ODataConventionModelBuilder>();
            builder.EntityType<DeltaModel>();
            builder.EntitySet<DeltaModel>("ignored");
            IEdmModel model = builder.GetEdmModel();
            IEnumerable<ODataMediaTypeFormatter> odataFormatters = ODataMediaTypeFormatters.Create();
            Delta<DeltaModel> delta;

            using (HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri("http://localhost") })
            {
                IEdmEntitySet entitySet = model.EntityContainer.EntitySets().Single();
                HttpConfiguration config = new HttpConfiguration();
                config.MapODataServiceRoute("default", "", model);
                request.SetConfiguration(config);
                request.EnableODataDependencyInjectionSupport("default");
                request.ODataProperties().Path = new ODataPath(new EntitySetSegment(entitySet));
                IEnumerable<MediaTypeFormatter> perRequestFormatters = odataFormatters.Select(
                    (f) => f.GetPerRequestFormatterInstance(typeof(Delta<DeltaModel>), request, null));

                HttpContent content = new StringContent(String.Format("{{ '{0}' : {1} }}", propertyName, propertyJsonValue));
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;IEEE754Compatible=true");

                // Act
                delta = content.ReadAsAsync<Delta<DeltaModel>>(perRequestFormatters).Result;
            }

            // Assert
            Assert.Equal(delta.GetChangedPropertyNames(), new[] { propertyName });
            object value;
            Assert.True(delta.TryGetPropertyValue(propertyName, out value));
            Assert.Equal(expectedValue, value);
        }

        public static TheoryDataSet<string, string, string, object> ODataFormatter_Can_Read_Delta_DataSet_WithAlias
        {
            get
            {
                return new TheoryDataSet<string, string, string, object>()
                {
                    { "StringProperty", "StringPropertyAlias", "'42'", "42" },
                    { "ComplexModelProperty", "ComplexModelPropertyAlias", "{ 'ComplexIntPropertyAlias' : 42 }", new ComplexModelWithAlias { ComplexIntProperty = 42 } },
                    { "CollectionProperty", "CollectionPropertyAlias", "[ 1, 2, 3 ]", new Collection<int> { 1, 2, 3} },
                    { "ComplexModelCollectionProperty", "ComplexModelCollectionPropertyAlias", "[ { 'ComplexIntPropertyAlias' : 42 } ]", new Collection<ComplexModelWithAlias> { new ComplexModelWithAlias { ComplexIntProperty = 42 } } }
                };
            }
        }

        [Theory]
        [PropertyData("ODataFormatter_Can_Read_Delta_DataSet_WithAlias")]
        public void ODataFormatter_CanReadDelta_WithAlias(string propertyName, string propertyNameAlias, string propertyJsonValue, object expectedValue)
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock<ODataConventionModelBuilder>();
            builder.ModelAliasingEnabled = true;
            builder.EntityType<DeltaModelWithAlias>();
            builder.EntitySet<DeltaModelWithAlias>("ignored");
            IEdmModel model = builder.GetEdmModel();
            IEnumerable<ODataMediaTypeFormatter> odataFormatters = ODataMediaTypeFormatters.Create();
            Delta<DeltaModelWithAlias> delta;

            using (HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri("http://localhost") })
            {
                IEdmEntitySet entitySet = model.EntityContainer.EntitySets().Single();
                HttpConfiguration config = new HttpConfiguration();
                config.MapODataServiceRoute("default", "", model);
                request.SetConfiguration(config);
                request.EnableODataDependencyInjectionSupport("default");
                request.ODataProperties().Path = new ODataPath(new EntitySetSegment(entitySet));
                IEnumerable<MediaTypeFormatter> perRequestFormatters = odataFormatters.Select(
                    (f) => f.GetPerRequestFormatterInstance(typeof(Delta<DeltaModelWithAlias>), request, null));

                HttpContent content = new StringContent(String.Format("{{ '{0}' : {1} }}", propertyNameAlias, propertyJsonValue));
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Act
                delta = content.ReadAsAsync<Delta<DeltaModelWithAlias>>(perRequestFormatters).Result;
            }

            // Assert
            Assert.Equal(delta.GetChangedPropertyNames(), new[] { propertyName });
            object value;
            Assert.True(delta.TryGetPropertyValue(propertyName, out value));
            Assert.Equal(expectedValue, value);
        }

        public static TheoryDataSet<Type> TypedDelta_Returns_Correct_ExpectedClrType_And_ActualType_DataSet
        {
            get
            {
                return new TheoryDataSet<Type>()
                {
                    { typeof(Customer) },
                    { typeof(BellevueCustomer) }
                };
            }
        }

        [Theory]
        [PropertyData("TypedDelta_Returns_Correct_ExpectedClrType_And_ActualType_DataSet")]
        public void TypedDelta_Returns_Correct_ExpectedClrType_And_ActualType(Type actualType)
        {
            // Arrange
            TypedDelta delta = new Delta<Customer>(actualType);

            // Act
            Type actualActualType = delta.EntityType;
            Type actualExpectedType = delta.ExpectedClrType;

            // Assert
            Assert.Equal(typeof(Customer), actualExpectedType);
            Assert.Equal(actualType, actualActualType);
        }

        public static T GetDefaultValue<T>()
        {
            return default(T);
        }

        private class DeltaModel
        {
            public int IntProperty { get; set; }

            public int? NullableIntProperty { get; set; }

            public long LongProperty { get; set; }

            public long? NullableLongProperty { get; set; }

            public bool BoolProperty { get; set; }

            public bool? NullableBoolProperty { get; set; }

            public Guid GuidProperty { get; set; }

            public Guid? NullableGuidProperty { get; set; }

            public DateTimeOffset DateTimeOffsetProperty { get; set; }

            public DateTimeOffset? NullableDateTimeOffsetProperty { get; set; }

            public Date DateProperty { get; set; }

            public Date? NullableDateProperty { get; set; }

            public TimeOfDay TimeOfDayProperty { get; set; }

            public TimeOfDay? NullableTimeOfDayProperty { get; set; }

            public string StringProperty { get; set; }

            public ComplexModel ComplexModelProperty { get; set; }

            public Collection<int> CollectionProperty { get; set; }

            public Collection<ComplexModel> ComplexModelCollectionProperty { get; set; }
        }

        private class DeltaModelWithCollection
        {
            public DeltaModelWithCollection()
            {
                CollectionPropertyWithoutSet = new Collection<int>();
                ComplexModelCollectionPropertyWithOutSet = new Collection<ComplexModel>();
            }

            public Collection<int> CollectionPropertyWithoutSet { get; private set; }

            public Collection<ComplexModel> ComplexModelCollectionPropertyWithOutSet { get; private set; }
        }

        private class InvalidDeltaModel
        {
            public InvalidDeltaModel()
            {
                CollectionPropertyWithoutSetAndClear = new int[0];
            }

            public IEnumerable<int> CollectionPropertyWithoutSetAndNullValue { get; private set; }

            public IEnumerable<int> CollectionPropertyWithoutSetAndClear { get; private set; }
        }

        private class ComplexModel
        {
            public int ComplexIntProperty { get; set; }

            public int? ComplexNullableIntProperty { get; set; }

            public override bool Equals(object obj)
            {
                ComplexModel model = obj as ComplexModel;

                if (model == null)
                {
                    return false;
                }

                return ComplexIntProperty == model.ComplexIntProperty && ComplexNullableIntProperty == model.ComplexNullableIntProperty;
            }

            public override int GetHashCode()
            {
                throw new NotImplementedException();
            }
        }

        private abstract class AbstractBase
        {
        }

        private class Base
        {
            public int BaseInt { get; set; }

            public string BaseString { get; set; }
        }

        private class Derived : Base
        {
            public int DerivedInt { get; set; }

            public string DerivedString { get; set; }
        }

        private class DerivedDerived : Derived
        {
            public int DerivedDerivedInt { get; set; }

            public string DerivedDerivedString { get; set; }
        }

        private class AnotherDerived : Base
        {
        }

        [DataContract(Namespace = "com.contoso", Name = "DeltaModelAlias")]
        private class DeltaModelWithAlias
        {
            [DataMember(Name = "StringPropertyAlias")]
            public string StringProperty { get; set; }

            [DataMember(Name = "ComplexModelPropertyAlias")]
            public ComplexModelWithAlias ComplexModelProperty { get; set; }

            [DataMember(Name = "CollectionPropertyAlias")]
            public Collection<int> CollectionProperty { get; set; }

            [DataMember(Name = "ComplexModelCollectionPropertyAlias")]
            public Collection<ComplexModelWithAlias> ComplexModelCollectionProperty { get; set; }
        }

        [DataContract(Namespace = "com.contoso", Name = "ComplexModelAlias")]
        private class ComplexModelWithAlias
        {
            [DataMember(Name = "ComplexIntPropertyAlias")]
            public int ComplexIntProperty { get; set; }

            [DataMember(Name = "ComplexNullableIntPropertyAlias")]
            public int? ComplexNullableIntProperty { get; set; }

            public override bool Equals(object obj)
            {
                ComplexModelWithAlias model = obj as ComplexModelWithAlias;

                if (model == null)
                {
                    return false;
                }

                return ComplexIntProperty == model.ComplexIntProperty && ComplexNullableIntProperty == model.ComplexNullableIntProperty;
            }

            public override int GetHashCode()
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
class StatisticsAnnouncementOrganisation < ActiveRecord::Base
  belongs_to :statistics_announcement, inverse_of: :statistics_announcement_organisations
  belongs_to :organisation, inverse_of: :statistics_announcement_organisations

  validates :statistics_announcement, :organisation, presence: true
end

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>WorkbookFormatting | Dashboard Extensions</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Dashboard Extensions

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					WorkbookFormatting

Interface WorkbookFormatting

The Workbook formatting contains an array of Formatting sheets.
							Each of these sheets can be identified by the ClassNameKey and
						contains the CSS properties needed to mimic the formatting on your workbook.

Hierarchy

						WorkbookFormatting

Index

Properties

formatting<wbr>Sheets

Properties

formatting<wbr>Sheets

formatting<wbr>Sheets: Array<FormattingSheet>

Defined in packages/api-external-contract-js/src/ExternalContract/Shared/WorkbookFormattingInterfaces.ts:13

returns

An array of formatting sheets that contain the css properties for a tableau workbook.

since

1.7.0 and Tableau 2021.4

						Globals

						Workbook<wbr>Formatting

								formatting<wbr>Sheets

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method


text:
<?php

Route::group(['namespace' => 'Tasks'], function() {
    // Views
    Route::group(['prefix' => 'tasks'], function() {
        Route::get('/' , function () {
            return view('tasks.tasks');
        })->middleware('permission:read-tasks');
    });
    // API
    Route::group(['prefix' => 'api/tasks'], function() {
        // Find
        Route::get('/byCreator', 'TaskController@byCreator')->middleware('permission:read-tasks');
        // CRUD
        Route::post('/store', 'TaskController@store')->middleware('permission:create-tasks');
        //Route::put('/update/{id}', 'TaskController@update')->middleware('permission:update-tasks');
        Route::delete('/destroy/{id}', 'TaskController@destroy')->middleware('permission:delete-tasks');
        Route::put('/markDone/{id}', 'TaskController@markDone')->middleware('permission:update-tasks');
        Route::put('/updateOrder', 'TaskController@updateOrder')->middleware('permission:update-tasks');
    });
});


text:
<?php

require('config.php');
require('common.php');
require('inc/header.php');
require('inc/faq.php');
require('inc/footer.php');


text:
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Z.Reflection.Test
{
    [TestClass]
    public class Method_GetSignature_OutParameterModifierMethod
    {
        [TestMethod]
        public void GetSignature()
        {
            // Type
            var @this = typeof(MethodModel<>).GetMethod("OutParameterModifierMethod", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            // Exemples
            string result = @this.GetSignature();

            // Unit Test
            Assert.AreEqual("OutParameterModifierMethod(int)", result);
        }
    }
}


text:
package remote.client;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class Client_Activator extends Application  {
	@Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> rootResources = new HashSet<Class<?>>();

        rootResources.add(Endpoint.class);

        return rootResources;
    }
}


text:
package org.hawkular.apm.tests.dockerized.environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import org.hawkular.apm.tests.dockerized.exception.EnvironmentException;
import org.hawkular.apm.tests.dockerized.model.TestEnvironment;

/**
 * @author Pavol Loffay
 */
public class DockerComposeExecutor extends AbstractDockerBasedEnvironment {
    private static final Logger log = Logger.getLogger(DockerComposeExecutor.class.getName());

    private DockerComposeExecutor(String scenarioDirectory, String apmBindAddress) {
        super(scenarioDirectory, apmBindAddress);
        if (apmBindAddress == null) {
            throw new NullPointerException("Bind address for APM should be specified.");
        }
    }

    /**
     * @param scenarioDirectory Absolute path of test scenario directory
     * @param apmBindAddress Address of default gateway (host OS where is running APM server). This network
     *                       is also used as default in docker-compose
     */
    public static DockerComposeExecutor getInstance(String scenarioDirectory, String apmBindAddress) {
        return new DockerComposeExecutor(scenarioDirectory, apmBindAddress);
    }

    @Override
    public List<String> run(TestEnvironment testEnvironment) {
        if (testEnvironment.isPull()) {
            List<String> cmd = composeCommandWithFiles(testEnvironment.getDockerCompose());
            cmd.add("pull");
            runShellCommand(cmd);
        }

        /**
         * Note that if image is not in local cache it will be download from the hub
         */
        List<String> cmd = composeCommandWithFiles(testEnvironment.getDockerCompose());
        cmd.addAll(Arrays.asList("up", "-d"));
        runShellCommand(cmd);

        return testEnvironment.getDockerCompose();
    }

    @Override
    public void stopAndRemove(List<String> ids) {
        List<String> cmd = composeCommandWithFiles(ids);
        cmd.addAll(Arrays.asList("down", "--rmi", "all"));
        try {
            runShellCommand(cmd);
        } catch (EnvironmentException ex) {
            log.severe(String.format("docker-compose down failed %s", ex.getMessage()));
            ex.printStackTrace();
        }
    }

    /**
     * @param id Id of the environment, Concretely docker-compose file.
     * @param serviceName Service name in running environment. Service defined in docker-compose.
     * @param script Script to execute
     */
    @Override
    public void execScript(List<String> id, String serviceName, String script) {
        List<String> cmd = composeCommandWithFiles(id);
        cmd.addAll(Arrays.asList("exec", serviceName, "bash", "-c", scriptExecCommand(script)));
        runShellCommand(cmd);
    }

    private void runShellCommand(List<String> commands) {

        log.info(String.format("Executing command on host OS: `%s`", commands));

        try {
            Process process = Runtime.getRuntime().exec(commands.toArray(new String[0]));

            /**
             * Output
             */
            InputStream stdin = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            log.info("<OUTPUT>");
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            log.info("</OUTPUT>");

            int exitVal = process.waitFor();
            log.info(String.format("Process exit value: %d", exitVal));

            if (process == null || exitVal != 0) {
                log.severe(String.format("`%s` did not return 0", commands));
                log.severe("-------- stderr ");
                log.severe(new BufferedReader(new InputStreamReader(process.getErrorStream())).lines().collect(Collectors.joining("\n")));
                log.severe("-------- /stderr ");
                throw new EnvironmentException(commands + " did not return 0, actual = " +
                        (process != null ? process.exitValue(): ""));
            }

        } catch (IOException | InterruptedException ex) {
            log.severe(String.format("Could not run: %s", commands));
            throw new EnvironmentException("Could not run: " + commands, ex);
        }

        log.info(String.format("Command `%s`, successfully executed", commands));
    }

    private List<String> composeCommandWithFiles(List<String> composeFiles) {
        List<String> composeCmdWithArgs = new ArrayList<>(composeFiles.size()*2 + 1);
        composeCmdWithArgs.add("docker-compose");

        for (String composeFile: composeFiles) {
            composeCmdWithArgs.add("-f");
            composeCmdWithArgs.add(scenarioDirectory + File.separator + composeFile);
        }
        return composeCmdWithArgs;
    }
}


text:
'use strict';

module.exports = DateHandler;

//The months of the year used for gettign the natural language date
let month = ['January', 'Februaruy', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

//Creating a module to  be exported in our routes
function DateHandler (){

    this.getDate = (req, res) => {

      //We will get a strign version and a int version of the date passed in the url
      let stringDate = decodeURI(req.path.substring(1));
      let intDate = parseInt(stringDate, 10);

      //If intDate is a number we will use intDate to mkae the Date object else we will use string date
      let date = isNaN(intDate) ? new Date(stringDate) : new Date(intDate);

      let dateObj = {unix : null,
                     natural : null
                    };

        //If the date object has a proper date we will set the unix and natural dateson our dateObj
        if(!isNaN(date.getTime())){
          dateObj.unix = Math.floor(date.getTime()/1000);
          dateObj.natural = month[date.getMonth()] + ' ' + date.getDate().toString()+ ', ' + date.getFullYear().toString();
        }

      res.json(dateObj);

    };

};


text:
package org.jf.dexlib.Code.Analysis;

import org.jf.dexlib.Util.ExceptionWithContext;

public class ValidationException extends ExceptionWithContext {
    private int codeAddress;

    public ValidationException(int codeAddress, String errorMessage) {
        super(errorMessage);
        this.codeAddress = codeAddress;
    }

    public ValidationException(String errorMessage) {
        super(errorMessage);
    }

    public void setCodeAddress(int codeAddress) {
        this.codeAddress = codeAddress;
    }

    public int getCodeAddress() {
        return codeAddress;
    }
}


text:
namespace jcc {
namespace simulation {

class SimViewer : public viewer::Window3D {
 public:
  SimViewer();
  void on_key(int key, int scancode, int action, int mods) override;
  void on_mouse_button(int button, int action, int mods) override;
  void on_mouse_move(const viewer::WindowPoint &mouse_pos) override;
  void on_scroll(const double amount) override;

  void draw() override;
  void draw_element(int id, const Element &element);
  void draw_robot(const planning::drifter::State &state);

  // @returns true if it's time for a view update
  bool update_editor_state();

 private:
  MainMenuState main_menu_state_;
  EditorState editor_state_;
  InteractableGeometry interactable_geo_;
  SimulationIntegrator integrator_;

  geometry::spatial::RayCaster ray_caster_;
  bool show_bvh_ = false;

  viewer::GeometryBuffer geo_;
  viewer::GeometryBuffer tmp_geo_;

  viewer::GeometryBuffer plan_geo_;
  viewer::GeometryBuffer robot_geo_;

  viewer::GeometryBuffer bgnd_geo_;

  viewer::GeometryBuffer lidar_geo_;

  // SceneTree robot_tree_;

  std::map<std::string, Asset> assets_;

  std::stack<EditorCommand> editor_commands_;

  bool had_robots_ = false;
  bool view_state_change_ = false;

  jcc::TimePoint last_step_time_ = jcc::TimePoint::min();

  //
  // Between frames
  //

  TaskPopupState task_popup_state_;

  CommandQueue cmd_queue_;
};

std::shared_ptr<SimViewer> create_sim_viewer(const std::string &title);

}  // namespace simulation
}  // namespace jcc


text:
layout: page
title: Sail Serenity Llc. Executive Retreat
date: 2016-05-24
author: Betty Powers
tags: weekly links, java
status: published
summary: Cras in tellus dui. Pellentesque elementum justo id nisi tristique.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 03/28/2016
  endDate: 03/31/2016
  ctyhocn: DALRKHX
  groupCode: SSLER
published: true
---
Pellentesque scelerisque massa varius, molestie dolor sit amet, pharetra nulla. Ut ac lobortis dui, quis accumsan justo. Nulla facilisi. Quisque varius ligula eget diam ultrices, sit amet iaculis dui aliquam. Vivamus vulputate enim ac diam consequat, sed pretium urna laoreet. Phasellus convallis, dolor a volutpat mollis, mauris tortor porttitor nulla, quis egestas nisi sem id leo. Ut tellus felis, vulputate et dui id, euismod aliquet augue. Maecenas sit amet ligula pretium, sollicitudin ipsum vitae, consequat est. Integer sapien diam, finibus nec lacus non, convallis placerat risus. Sed vitae porttitor dui.

1 Fusce eu ante eget nibh ultrices ultricies a id nibh
1 Sed ac mauris lobortis, sagittis urna sed, faucibus mi
1 Nunc quis dolor pretium, ultrices ex in, sagittis massa.

Nullam porta, nisi sed aliquam vulputate, quam elit tristique turpis, id dignissim ex tortor at urna. Nunc eu orci eget enim dignissim dapibus. Vivamus ut lacus ac purus blandit varius nec sed diam. Vestibulum dolor sapien, tincidunt id lacus nec, egestas commodo nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec massa justo, ornare et tempus eu, vehicula venenatis massa. Donec ac vestibulum massa, sit amet suscipit sem. Pellentesque id facilisis sem, at vulputate mauris. Morbi rhoncus eu urna a efficitur. Etiam eu euismod elit. Donec id sapien sit amet turpis ultricies ultrices.
Sed finibus ipsum nec mi fermentum sagittis. Phasellus faucibus scelerisque consequat. Quisque feugiat accumsan sagittis. Vivamus id erat sapien. Nullam vitae eleifend ipsum, vitae vestibulum lorem. Vestibulum arcu ante, tincidunt ut tempor eu, vestibulum vitae elit. Proin at sem non lorem efficitur pharetra. Fusce id ipsum vitae augue cursus aliquet quis et tellus. Maecenas a mollis neque. Sed laoreet nulla sed tortor venenatis, placerat sollicitudin erat bibendum.


text:
<?php

final class PhabricatorFilesManagementCatWorkflow
  extends PhabricatorFilesManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('cat')
      ->setSynopsis(pht('Print the contents of a file.'))
      ->setArguments(
        array(
          array(
            'name' => 'begin',
            'param' => 'bytes',
            'help' => pht('Begin printing at a specific offset.'),
          ),
          array(
            'name' => 'end',
            'param' => 'bytes',
            'help' => pht('End printing at a specific offset.'),
          ),
          array(
            'name'      => 'names',
            'wildcard'  => true,
          ),
        ));
  }

  public function execute(PhutilArgumentParser $args) {
    $console = PhutilConsole::getConsole();

    $names = $args->getArg('names');
    if (count($names) > 1) {
      throw new PhutilArgumentUsageException(
        pht('Specify exactly one file to print, like "%s".', 'F123'));
    } else if (!$names) {
      throw new PhutilArgumentUsageException(
        pht('Specify a file to print, like "%s".', 'F123'));
    }

    $file = head($this->loadFilesWithNames($names));

    $begin = $args->getArg('begin');
    $end = $args->getArg('end');

    $iterator = $file->getFileDataIterator($begin, $end);
    foreach ($iterator as $data) {
      echo $data;
    }

    return 0;
  }

}


text:
/* Object.is() */
(function() {
    console.log(Object.is('foo', 'foo'));     // true
    console.log(Object.is(window, window));   // true

    console.log(Object.is('foo', 'bar'));     // false
    console.log(Object.is([], []));           // false

    var test = {a: 1};
    console.log(Object.is(test, test));       // true

    console.log(console.log(Object.is(null, null))); // true

// Special Cases
    console.log(Object.is(0, -0));            // false
    console.log(Object.is(-0, -0));           // true
    console.log(Object.is(NaN, 0 / 0));         // true
}());


text:
<?php

namespace PHPExiftool\Driver\Tag\MXF;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class EssenceStreamID extends AbstractTag
{

    protected $Id = '060e2b34.0101.0104.01030404.00000000';

    protected $Name = 'EssenceStreamID';

    protected $FullName = 'MXF::Main';

    protected $GroupName = 'MXF';

    protected $g0 = 'MXF';

    protected $g1 = 'MXF';

    protected $g2 = 'Video';

    protected $Type = 'int32u';

    protected $Writable = false;

    protected $Description = 'Essence Stream ID';

}


text:
require 'test_helper'

module Elasticsearch
  module Test
    class IndicesFlushSyncedTest < ::Test::Unit::TestCase

      context "Indices: Flush synced" do
        subject { FakeClient.new }

        should "perform correct request" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'POST', method
            assert_equal 'foo/_flush/synced', url
            assert_equal Hash.new, params
            assert_nil   body
            true
          end.returns(FakeResponse.new)

          subject.indices.flush_synced :index => 'foo'
        end

        should "raise a NotFound exception" do
          subject.expects(:perform_request).raises(NotFound)

          assert_raise NotFound do
            subject.indices.flush_synced :index => 'foo'
          end
        end

        should "catch a NotFound exception with the ignore parameter" do
          subject.expects(:perform_request).raises(NotFound)

          assert_nothing_raised do
            subject.indices.flush_synced :index => 'foo', :ignore => 404
          end
        end
      end

    end
  end
end


text:
var wreck = require('wreck');
var EventEmitter = require('events').EventEmitter;

var default_url = 'https://guarded-sierra-2722.herokuapp.com';

exports.create_lock_client = function (options) {
    if (!options || !options.token)
        throw new Error('The options.token is not specified');
    options.token = options.token;
    options.url = options.url || default_url;
    options.poll_ttl = options.poll_ttl || 45000;
    options.request_timeout = options.request_timeout || 30000;
    options.max_poll_attempt = options.max_poll_attempt || 10;
    options.initial_poll_delay = options.initial_poll_delay || 500;
    options.poll_delay_backoff = options.poll_delay_backoff || 1.2;

    var client = new EventEmitter();

    client.close = function () {
        this._closed = true;
        if (this._delay) {
            clearTimeout(this._delay);
            delete this._delay;
        }
    };

    client.send = function (data, cb) {
        post({
            url: options.url + '/lock/event',
            token: options.token,
            data: data,
            request_timeout: options.request_timeout
        }, cb);
    }

    var error_count = 0;
    var delay = 0;
    function poll_once() {
        var url = options.url + '/lock/hook'
        wreck.get(url, {
            timeout: options.poll_ttl,
            json: true,
            headers: {
                'Authorization': 'Bearer ' + options.token
            }
        }, function (err, res, body) {
            if (client._closed)
                return;
            if (err && err.output && err.output.statusCode === 504) {
                error_count = delay = 0;
                return poll_once();
            }
            if (err || (res.statusCode !== 200 && res.statusCode !== 404)) {
                client.emit('warn', new Error('Unable to communicate with hypelock sever after ' + error_count + ' attempts.'));
                if (error_count++ >= options.max_poll_attempt) {
                    client.close();
                    return client.emit('error', new Error('Unable to communicate with hypelock sever after ' + options.max_poll_attempt + ' attempts.'));
                }
                delay = delay ? delay * options.poll_delay_backoff : options.initial_poll_delay;
                client._delay = setTimeout(poll_once, delay);
                return;
            }
            if (res.statusCode === 200)
                client.emit('message', body);
            poll_once();
        });
    }

    poll_once();

    return client;
};

exports.register = function (options, cb) {
    options = options || {};
    options.url = options.url || default_url;
    options.request_timeout = options.request_timeout || 30000;

    post({
        url: options.url + '/api/doorlock',
        token: options.token,
        data: options.data,
        request_timeout: options.request_timeout
    }, cb);
}

exports.action = function (options, cb) {
    options = options || {};
    options.url = options.url || default_url;
    options.request_timeout = options.request_timeout || 30000;

    post({
        url: options.url + '/api/doorlock/' + options.device_id + '/action',
        token: options.token,
        data: options.data,
        request_timeout: options.request_timeout
    }, cb);
}

function post(params, cb) {
    var options = {
        json: true,
        payload: JSON.stringify(params.data),
        timeout: params.request_timeout,
        headers: {
            'Content-Type': 'application/json'
        }
    };
    if (params.token)
        options.headers.Authorization = 'Bearer ' + params.token;
    wreck.post(params.url, options, function (err, res, body) {
        if (err)
            return cb(err);
        if (res.statusCode !== 200)
            return cb(new Error('Error response from Hyperlock server. HTTP status ' +
                res.statusCode + ': ' + (body || '<empty>')));
        cb(null, body);
    });

}


text:
$(document).ready(function(){
	$(".alert-success").delay(5000).fadeOut("slow");
});


text:
using System;

namespace Jynd
{
    public static class JyndConvert
    {
        [ThreadStatic]
        private static JyndItem[] Items;

        [ThreadStatic]
        private static short[] Instances;

        [ThreadStatic]
        private static short[] Hashes;

        public static dynamic Deserialize(string json)
        {
            Items = Items ?? new JyndItem[UInt16.MaxValue];
            Hashes = Hashes ?? new short[UInt16.MaxValue];
            Instances = Instances ?? new short[UInt16.MaxValue];

            JyndData data = new JyndData(json, Items, Hashes);
            JyndParser parser = new JyndParser(data, Instances);

            parser.Execute();

            if (data.Source[0] == '{')
            {
                return new JyndObject(data, 0);
            }

            return new JyndArray(data, 0);
        }
    }
}


text:
package org.apache.mxnetexamples.multitask

import org.apache.mxnet._
import org.slf4j.LoggerFactory
import org.apache.mxnet.Context

import org.scalatest.FunSuite

/**
  * Integration test for imageClassifier example.
  * This will run as a part of "make scalatest"
  */
class MultiTaskSuite extends FunSuite {
  test("Multitask Test") {
    val logger = LoggerFactory.getLogger(classOf[MultiTaskSuite])
    if (System.getenv().containsKey("SCALA_TEST_ON_GPU") &&
      System.getenv("SCALA_TEST_ON_GPU").toInt == 1) {
      logger.info("Multitask Test...")

      val batchSize = 100
      val numEpoch = 3
      val ctx = Context.gpu()

      val modelPath = ExampleMultiTask.getTrainingData
      val (executor, evalMetric) = ExampleMultiTask.train(batchSize, numEpoch, ctx, modelPath)
      evalMetric.get.foreach { case (name, value) =>
        assert(value >= 0.95f)
      }
      executor.dispose()
    } else {
      logger.info("GPU test only, skipped...")
    }
  }
}


text:
import speech
import time

if __name__ == '__main__':
    speech_object = speech.speech()
    val = 51
    ask_val = True
    if ask_val:
        while True:
                val = int(input('Enter value'))
                speech_object.say(val)
    else:
        speech_object.say(val)
        time.sleep(0.5)
        while speech_object.now_saying():
            time.sleep(0.2)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Grevillea 16(no. 79): 94 (1888)

#### Original name
Pocillum boltonii W. Phillips, 1888

### Remarks
null


text:
package mx.com.sct.checkyourrute.utils;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

public class Posiciones {
	//Nueva clase Posiciones
    //Constante de Posici—n del marcador
public static final LatLng SAGRADA_FAMILIA = new LatLng(41.40347, 2.17432);
    //Constante de Opciones de Polil'nea.
public static final PolylineOptions POLILINEA = new PolylineOptions()
                           .add(new LatLng(41.40347, 2.17432))
                           .add(new LatLng(41.40691, 2.16864))
                           .add(new LatLng(41.40364, 2.16437));
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Oppo A33
 *
 * DEVICE: A33
 * MODEL: A33
 */
final class a33_a33 {
    public static final String DATA = "Oppo|A33|";
}


text:
# diffler
A fast property comparer of instances using compiled expression trees on the fly.

If you need to collect the different property values of instances of the same kind,
you may find this tool efficient and useful, because:
- it is not using reflection
- it executes the comparision upon the precompiled expression tree for the given type, thus making it much faster than using reflection
- supports comparing complex types (by default equality comparer)
- supports comparing arrays
- supports ignoring properties from comparision
- ignores generated `ExtensionData` properties by default (can be changed via the static `Diff.IgnoreExtensionDataProperties` property)

#### Solution
A comparer algorithm is compiled and cached for every type, which are generated by using [expression trees](https://msdn.microsoft.com/en-us/library/bb397951.aspx). The result of the comparision is contained in a `Dictionary<string,object>` instance, which holds the different property name and value pairs.

Each property value is compared by the default equality comparer (via calling Equals()) of the actual property type. Array types are compared by elements, by their type's default comparer.

The C# source codes are contained in a Visual Studio 2015 solution, the tests are using Moq and MSPEC.

#### Usage

##### Comparing two instances of T
```CSharp
using rblt.Tools;

/// t1 and t2 are instances of T
T t1 = ...
T t2 = ...

/// getting the different properties and their values:
var delta = Diff.Them(t1, t2);

/// which is the same as using the extension method:
var delta = t1.Versus(t2);
```

##### Ignoring properties
You can ignore arbitrary property from comparision by marking them with the `DiffIgnore` property attribute. See the example below.

##### Ignoring array element order
You can ignore the order of the arrays' elements when comparing them using the `DiffIgnoreOrder` property attribute. See the example below.

#### Example

```CSharp
using rblt.Tools;

public class TestClass
{
    public string PropString { get; set; }

    [DiffIgnore]
    public object PropObject { get; set; }

    [DiffIgnoreOrder]
    public int[] PropArray { get; set; }
}

public static void Main(string[] args)
{
    var t1 = new TestClass()
    {
        PropString = "string1",
        PropObject = new object(),
        PropArray = new int[] { 1, 2, 3 }
    };

    var t2 = new TestClass()
    {
        PropString = "string2",
        PropObject = new object(),
        PropArray = new int[] { 2, 3, 1}
    };

    IDictionary<string, object> delta = t1.Versus(t2);

    /*

      The resulting dictionary contains the
      different propertyname/value pairs of "t2".

      delta = {
        { "PropString", "string2" }
      };

    */
}
```

#### Remarks
The comparision is not recursive, so child properties of complex properties are not targeted for comparision.

#### Todos
The comparision could be made recursive for child properties.


text:
import * as React from 'react';
import { useEffect } from 'react';

import { Slider, InputNumber, Select } from 'antd';

import { Tyr } from 'tyranid/client';

import { mapPropsToForm, onTypeChange } from './type';
import { TyrFilter, FilterDdProps } from '../core/filter';
import { byName, TyrTypeProps } from './type';
import { decorateField, getValue } from '../core';
import { registerComponent } from '../common';
import { withThemedTypeContext } from '../core/theme';

type SliderValue = [number, number] | undefined;

const { Option } = Select;

const filterOptions = [
  'Equals',
  'Not equal',
  'Less Than',
  'Less Than or equals',
  'Greater than',
  'Greater than or equals',
];

export const TyrDoubleBase = <D extends Tyr.Document = Tyr.Document>(
  props: TyrTypeProps<D>
) => {
  useEffect(() => mapPropsToForm(props), [
    props.path && props.path.name,
    props.document,
  ]);

  return decorateField('double', props, () => {
    const onTypeChangeFunc = (ev: any) => {
      onTypeChange(props, ev, null);
      props.onChange && props.onChange(ev, null, props);
    };

    return (
      <InputNumber
        {...(props.searchRange
          ? {
              min: props.searchRange[0] as number,
              max: props.searchRange[1] as number,
            }
          : {})}
        onChange={onTypeChangeFunc}
        placeholder={props.placeholder}
        tabIndex={props.tabIndex}
        step={0.1}
        {...(props.min !== undefined && { min: props.min })}
        {...(props.max !== undefined && { max: props.max })}
      />
    );
  });
};

export const TyrDouble = withThemedTypeContext('double', TyrDoubleBase);

byName.double = {
  component: TyrDoubleBase,
  filter(component, props) {
    const path = props.path!;
    const pathName = path.name;

    const { searchRange, searchNumber } = props;

    const sliderFilter = (filterDdProps: FilterDdProps) => {
      const defaultValue = (component.filterValue(pathName) || searchRange
        ? (searchRange as [number, number])
        : [0, 100]) as [number, number];

      const compProps = {
        ...(searchRange ? { min: searchRange[0] as number } : { min: 0 }),
        ...(searchRange ? { max: searchRange[1] as number } : { max: 100 }),
      };

      return (
        <TyrFilter<SliderValue>
          typeName="double"
          component={component}
          filterDdProps={filterDdProps}
          pathProps={props}
        >
          {(searchValue, setSearchValue) => (
            <Slider
              range
              {...compProps}
              value={searchValue || (defaultValue.slice() as [number, number])}
              onChange={setSearchValue}
              style={{ width: 188 }}
            />
          )}
        </TyrFilter>
      );
    };

    const numberFilter = (filterDdProps: FilterDdProps) => (
      <TyrFilter<[string, number?]>
        typeName="integer"
        component={component}
        filterDdProps={filterDdProps}
        pathProps={props}
      >
        {(searchValue, setSearchValue, search) => {
          const setSearchValueChoice = (choice: string) => {
            setSearchValue([choice, searchValue ? searchValue[1] : undefined]);
          };

          const setSearchValueNumber = (
            value: string | number | null | undefined
          ) => {
            if (!isNaN(value as any)) {
              setSearchValue([
                searchValue ? searchValue[0] : filterOptions[0],
                value as number,
              ]);
            }
          };

          return (
            <React.Fragment>
              <Select
                defaultValue={searchValue ? searchValue[0] : filterOptions[0]}
                onChange={setSearchValueChoice}
                style={{ width: 188, marginBottom: 8, display: 'block' }}
              >
                {filterOptions.map(op => (
                  <Option key={op} value={op}>
                    {op}
                  </Option>
                ))}
              </Select>

              <InputNumber
                autoFocus={true}
                value={searchValue ? searchValue[1] : undefined}
                onChange={setSearchValueNumber}
                onPressEnter={() => search()}
                style={{ width: 188, marginBottom: 8, display: 'block' }}
              />
            </React.Fragment>
          );
        }}
      </TyrFilter>
    );

    return {
      filterDropdown: searchNumber ? numberFilter : sliderFilter,
      onFilter: (
        value: number[] | [string, number] | undefined,
        doc: Tyr.Document
      ) => {
        if (value === undefined) return true;
        const intVal = (path.get(doc) as number) || 0;

        if (searchNumber) {
          switch (value[0]) {
            case 'Equals':
              return intVal === value[1];
            case 'Not equal':
              return intVal !== value[1];
            case 'Less Than':
              return intVal < value[1];
            case 'Less Than or equals':
              return intVal <= value[1];
            case 'Greater than':
              return intVal > value[1];
            case 'Greater than or equals':
              return intVal >= value[1];
            default:
              throw new Error(`How did you pick this: ${value[0]} ?`);
          }
        }

        return intVal >= value[0] && intVal <= value[1];
      },
      /*
    onFilterDropdownVisibleChange: (visible: boolean) => {
      if (visible) {
        setTimeout(() => searchInputRef!.focus());
      }
    }
    */
    };
  },
  cellValue(path, document, props) {
    const value = getValue(props, document);

    if (!value) {
      return '';
    }

    if (typeof value === 'number') {
      const displayPrecision = 2; //  TODO: add this prop and get it from there
      return value.toFixed(displayPrecision);
    }

    return '[Error]';
  },
  finder(path, opts, searchValue, pathProps) {
    if (searchValue) {
      if (pathProps?.searchNumber) {
        let searchParams: object | undefined = undefined;

        switch (searchValue[0]) {
          case 'Equals':
            searchParams = searchValue[1];
            break;
          case 'Not equal':
            searchParams = { $ne: searchValue[1] };
            break;
          case 'Less Than':
            searchParams = { $lt: searchValue[1] };
            break;
          case 'Less Than or equals':
            searchParams = { $lte: searchValue[1] };
            break;
          case 'Greater than':
            searchParams = { $gt: searchValue[1] };
            break;
          case 'Greater than or equals':
            searchParams = { $gte: searchValue[1] };
            break;
        }

        if (searchParams) {
          if (!opts.query) opts.query = {};
          opts.query[path.spathArr] = searchParams;
        }
      } else {
        if (!opts.query) opts.query = {};

        const searchParams = [
          { [path.spathArr]: { $gte: searchValue[0] } },
          { [path.spathArr]: { $lte: searchValue[1] } },
        ];

        if (opts.query.$and) {
          opts.query.$and = [...opts.query.$and, ...searchParams];
        } else {
          opts.query.$and = searchParams;
        }
      }
    }
  },
};

registerComponent('TyrDouble', TyrDouble);


text:
OptionsSchema.json defines the type for Launch/Attach options.

# GenerateOptionsSchema
If there are any modifications to the OptionsSchema.json file. Please run `npm run gulp generateOptionsSchema` at the repo root.
This will call GenerateOptionsSchema and update the package.json file.


text:
package com.weightwatchers.reactive.kinesis.producer

import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.regions.Regions
import com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration
import com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration.ThreadingModel
import com.amazonaws.services.kinesis.producer.protobuf.Config.AdditionalDimension
import com.typesafe.config.{Config, ConfigFactory}

/** Typed config class for the KPL */
final case class KinesisProducerConfig(
    additionalMetricDimensions: List[AdditionalDimension],
    credentialsProvider: Option[AWSCredentialsProvider],
    metricsCredentialsProvider: Option[AWSCredentialsProvider],
    aggregationEnabled: Boolean,
    aggregationMaxCount: Long,
    aggregationMaxSize: Long,
    cloudwatchEndpoint: Option[String],
    cloudwatchPort: Long,
    collectionMaxCount: Long,
    collectionMaxSize: Long,
    connectTimeout: Long,
    credentialsRefreshDelay: Long,
    enableCoreDumps: Boolean,
    failIfThrottled: Boolean,
    kinesisEndpoint: Option[String],
    kinesisPort: Long,
    logLevel: String,
    maxConnections: Long,
    metricsGranularity: String,
    metricsLevel: String,
    metricsNamespace: String,
    metricsUploadDelay: Long,
    minConnections: Long,
    nativeExecutable: Option[String],
    rateLimit: Long,
    recordMaxBufferedTime: Long,
    recordTtl: Long,
    region: Option[Regions],
    requestTimeout: Long,
    tempDirectory: Option[String],
    verifyCertificate: Boolean,
    threadingModel: ThreadingModel,
    threadPoolSize: Int
) {

  def toAwsConfig: KinesisProducerConfiguration = {
    val initial = new KinesisProducerConfiguration()
      .setAggregationEnabled(aggregationEnabled)
      .setAggregationMaxCount(aggregationMaxCount)
      .setAggregationMaxSize(aggregationMaxSize)
      .setCloudwatchPort(cloudwatchPort)
      .setCollectionMaxCount(collectionMaxCount)
      .setCollectionMaxSize(collectionMaxSize)
      .setConnectTimeout(connectTimeout)
      .setCredentialsRefreshDelay(credentialsRefreshDelay)
      .setEnableCoreDumps(enableCoreDumps)
      .setFailIfThrottled(failIfThrottled)
      .setKinesisPort(kinesisPort)
      .setLogLevel(logLevel)
      .setMaxConnections(maxConnections)
      .setMetricsGranularity(metricsGranularity)
      .setMetricsLevel(metricsLevel)
      .setMetricsNamespace(metricsNamespace)
      .setMetricsUploadDelay(metricsUploadDelay)
      .setMinConnections(minConnections)
      .setRateLimit(rateLimit)
      .setRecordMaxBufferedTime(recordMaxBufferedTime)
      .setRecordTtl(recordTtl)
      .setRequestTimeout(requestTimeout)
      .setVerifyCertificate(verifyCertificate)
      .setThreadingModel(threadingModel)
      .setThreadPoolSize(threadPoolSize)

    KinesisProducerConfig.setAdditionalDimensions(initial, additionalMetricDimensions)

    // This is ugly
    val wCredProv = credentialsProvider.fold(initial)(initial.setCredentialsProvider)
    val wMetricCredProv =
      metricsCredentialsProvider.fold(wCredProv)(wCredProv.setMetricsCredentialsProvider)
    val wCWEP       = cloudwatchEndpoint.fold(wMetricCredProv)(wMetricCredProv.setCloudwatchEndpoint)
    val wKinesisEP  = kinesisEndpoint.fold(wCWEP)(wCWEP.setKinesisEndpoint)
    val wNativeExec = nativeExecutable.fold(wKinesisEP)(wKinesisEP.setNativeExecutable)
    val wRegion     = region.fold(wNativeExec)(reg => wNativeExec.setRegion(reg.getName))
    val wTempDir    = tempDirectory.fold(wRegion)(wRegion.setTempDirectory)

    wTempDir
  }
}

object KinesisProducerConfig {
  def apply(): KinesisProducerConfig                                     = default
  def apply(config: KinesisProducerConfiguration): KinesisProducerConfig = fromAwsConfig(config)
  def apply(config: Config): KinesisProducerConfig =
    fromAwsConfig(ProducerConf.buildKPLConfig(config, None))
  def apply(config: Config, credentialsProvider: AWSCredentialsProvider): KinesisProducerConfig =
    fromAwsConfig(ProducerConf.buildKPLConfig(config, Some(credentialsProvider)))

  // Sets default values as if no typesafe configuration was passed. This ensures that the default
  // KinesisProducerConfiguration is used
  def default: KinesisProducerConfig = {
    val defaultConfig = ProducerConf.buildKPLConfig(ConfigFactory.empty(), None)
    fromAwsConfig(defaultConfig)
  }

  private def fromAwsConfig(config: KinesisProducerConfiguration): KinesisProducerConfig =
    KinesisProducerConfig(
      additionalMetricDimensions = List(), // No way to retrieve this from a KinesisProducerConfiguration
      credentialsProvider = Some(config.getCredentialsProvider),
      metricsCredentialsProvider = Some(config.getMetricsCredentialsProvider),
      aggregationEnabled = config.isAggregationEnabled,
      aggregationMaxCount = config.getAggregationMaxCount,
      aggregationMaxSize = config.getAggregationMaxSize,
      cloudwatchEndpoint = Some(config.getCloudwatchEndpoint),
      cloudwatchPort = config.getCloudwatchPort,
      collectionMaxCount = config.getCollectionMaxCount,
      collectionMaxSize = config.getCollectionMaxSize,
      connectTimeout = config.getConnectTimeout,
      credentialsRefreshDelay = config.getCredentialsRefreshDelay,
      enableCoreDumps = config.isEnableCoreDumps,
      failIfThrottled = config.isFailIfThrottled,
      kinesisEndpoint = Some(config.getKinesisEndpoint),
      kinesisPort = config.getKinesisPort,
      logLevel = config.getLogLevel,
      maxConnections = config.getMaxConnections,
      metricsGranularity = config.getMetricsGranularity,
      metricsLevel = config.getMetricsLevel,
      metricsNamespace = config.getMetricsNamespace,
      metricsUploadDelay = config.getMetricsUploadDelay,
      minConnections = config.getMinConnections,
      nativeExecutable = Some(config.getNativeExecutable),
      rateLimit = config.getRateLimit,
      recordMaxBufferedTime = config.getRecordMaxBufferedTime,
      recordTtl = config.getRecordTtl,
      region = config.getRegion match {
        case x if x.isEmpty => None
        case x              => Some(Regions.fromName(x))
      },
      requestTimeout = config.getRequestTimeout,
      tempDirectory = Some(config.getTempDirectory),
      verifyCertificate = config.isVerifyCertificate,
      threadingModel = config.getThreadingModel,
      threadPoolSize = config.getThreadPoolSize
    )

  private def setAdditionalDimensions(
      conf: KinesisProducerConfiguration,
      dimensions: List[AdditionalDimension]
  ) = dimensions.foldLeft(conf) { (conf, dimension) =>
    conf.addAdditionalMetricsDimension(dimension.getKey,
                                       dimension.getValue,
                                       dimension.getGranularity)
    conf
  }
}


text:
INSERT INTO "Type"
SELECT "id" + 1, 'mds.field.description.relationship.oneToOne','mds.field.relationship.oneToOne','oneToOneRelationshipName','org.motechproject.mds.domain.OneToOneRelationship'
FROM "Type"
ORDER BY "id" DESC
LIMIT 1;

UPDATE "SEQUENCE_TABLE"
SET "NEXT_VAL" = (SELECT "id" + 1 FROM "Type" ORDER BY "id" DESC LIMIT 1)
WHERE "SEQUENCE_NAME" LIKE 'org.motechproject.mds.domain.Type';

INSERT INTO "TYPE_TYPE_SETTING"
SELECT t."id", ts."id", 0
FROM "Type" t, "TypeSetting" ts
WHERE t."typeClass" LIKE 'org.motechproject.mds.domain.OneToOneRelationship' AND ts."name" LIKE 'mds.form.label.cascadePersist';

INSERT INTO "TYPE_TYPE_SETTING"
SELECT t."id", ts."id", 1
FROM "Type" t, "TypeSetting" ts
WHERE t."typeClass" LIKE 'org.motechproject.mds.domain.OneToOneRelationship' AND ts."name" LIKE 'mds.form.label.cascadeUpdate';

INSERT INTO "TYPE_TYPE_SETTING"
SELECT t."id", ts."id", 2
FROM "Type" t, "TypeSetting" ts
WHERE t."typeClass" LIKE 'org.motechproject.mds.domain.OneToOneRelationship' AND ts."name" LIKE 'mds.form.label.cascadeDelete';


text:
'use strict';

var ColorThief = require('../js/color-thief');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['color-thief'] = {
  constructor: function(test) {
    test.equal(typeof ColorThief, 'function', 'ColorThief should be a function');
    test.done();
  },

  color: function(test) {
    var filename =  __dirname + '/../img/photo1.jpg';
    var colorThief = new ColorThief();
    var color = colorThief.getColor(filename);

    test.deepEqual(color, [125, 190, 193], 'correct color returned');
    test.done();
  }
};


text:
if [[ -z "${BASH_SOURCE[0]}" ]] ; then
    echo "Sorry, you need to use a debugger-enabled version of bash." 2>&1
    exit 2
fi

# Code that specifically has to come first.
# Note: "init" comes first and "cmds" has to come after "io".
for _Dbg_file in require pre vars io ; do
    source "${_Dbg_libdir}/init/${_Dbg_file}.sh"
done

for _Dbg_file in "${_Dbg_libdir}/lib/"*.sh "${_Dbg_libdir}/command/"*.sh ; do
    source "$_Dbg_file"
done

if [[ -r /dev/stdin ]] ; then
    _Dbg_do_source /dev/stdin
elif [[ $(tty) != 'not a tty' ]] ; then
    _Dbg_do_source "$(tty)"
fi

# List of command files to process
typeset -a _Dbg_input

# Have we already specified where to read debugger input from?
#
# Note: index 0 is only set by the debugger. It is not used otherwise for
# I/O like those indices >= _Dbg_INPUT_START_DESC are.
if [[ -n "$DBG_INPUT" ]] ; then
    _Dbg_input=("$DBG_INPUT")
    _Dbg_do_source "${_Dbg_input[0]}"
    _Dbg_no_nx=1
fi

typeset _Dbg_startup_cmdfile=${HOME:-~}/.${_Dbg_debugger_name}rc
if (( 0 == _Dbg_o_nx)) && [[ -r "$_Dbg_startup_cmdfile" ]] ; then
    _Dbg_do_source "$_Dbg_startup_cmdfile"
fi

# _Dbg_DEBUGGER_LEVEL is the number of times we are nested inside a debugger
# by virtue of running "debug" for example.
if [[ -z "${_Dbg_DEBUGGER_LEVEL}" ]] ; then
    typeset -xi _Dbg_DEBUGGER_LEVEL=1
fi

# This is put at the so we have something at the end to stop at
# when we debug this. By stopping at the end all of the above functions
# and variables can be tested.

if [[ ${_Dbg_libdir:0:1} == '.' ]] ; then
    # Relative file name
    _Dbg_libdir="$(_Dbg_expand_filename "${_Dbg_init_cwd}/${_Dbg_libdir}")"
fi

for source_file in "${_Dbg_o_init_files[@]}" "$DBG_RESTART_FILE";  do
    if [[ -n "$source_file" ]] ; then
	if [[ -r "$source_file" ]] && [[ -f "$source_file" ]] ; then
	    source "$source_file"
	else
	    _Dbg_errmsg "Unable to read shell script: ${source_file}"
	fi
    fi
done


text:
require 'test_helper'

class Gecko::UserTest < Minitest::Test
  include VCRHelper
  include SharedRecordExamples

  let(:plural_name)   { 'users' }
  let(:record_class)  { Gecko::Record::User }

  def setup
    @json   = load_vcr_hash('users', 'users').first
    @record = record_class.new(client, @json)
  end

  def test_initializes_record
    assert_instance_of(Gecko::Record::User, @record)
  end
end


text:
struct Status_Tag {
    int valor;
    char *mensagem;
};

typedef struct Status_Tag Status;

// Função que retorna um Status com valor 0,
// indicando sucesso, e sem mensagem atribuída.
// Exemplo:
//     ...
//     return sucesso();
Status* sucesso() {
    Status *sts;

    sts = malloc(sizeof(Status));
    sts->valor = 0;

    return sts;
}

// Função que retorna um Status com valor e mensagem
// atribuidos, indicando um erro. Por este motivo,
// o valor passado a ela deve ser diferente de 0,
// pois existe a função "sucesso" para tratar este caso.
// Caso o valor passado a ela seja 0, ela imprime um warning.
// Recebe:
//     int valor: valor representando o tipo de erro
//             (deve ser diferente de 0).
//     char *mensagem: string contendo a mensagem de erro associada.
// Retorna:
//     Status *sts: ponteiro para um Status indicando o estado da
//                  execução
Status* erro(int valor, char *mensagem) {
    Status *sts;

    if (valor == 0) fprintf(stderr, "WARNING: erro com status 0.\n");

    sts = malloc(sizeof(Status));
    sts->valor      = valor;
    sts->mensagem = mensagem;

    return sts;
}

// Trata o Status retornado por alguma função, isto é,
// imprime a mensagem de erro caso valor != 0 (erro).
// Em qualquer caso, porém, libera o Status recebido
// e retorna o valor deste, para poder ser usado
// posteriormente (em loops, por exemplo).
// Recebe:
//     Status *sts: Status a ser tratado
// Retorna:
//     int valor: valor do status recebido
int trata_status(Status *sts) {
    int        valor = sts->valor;
    char *mensagem = sts->mensagem;

    if (valor != 0) {
        fprintf(stderr, "%s\n", mensagem);
    }

    free(sts);
    return valor;
}


text:
namespace HippoDemo
{
    using System;
    using System.Windows.Controls;
    using System.Windows.Markup;
    using System.Windows.Media.Imaging;

    public class ImageExtension : MarkupExtension
    {
        public string Path { get; set; }

        public ImageExtension(string path)
        {
            Path = path;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var source = new BitmapImage(new Uri(Path, UriKind.Relative));
            return new Image() { Source = source, Height=24 };
        }
    }
}


text:
"""add-insecure-baymodel-attr

Revision ID: 1d045384b966
Revises: 1481f5b560dd
Create Date: 2015-09-23 18:17:10.195121

"""

# revision identifiers, used by Alembic.
revision = '1d045384b966'
down_revision = '1481f5b560dd'

from alembic import op  # noqa: E402
import sqlalchemy as sa  # noqa: E402

def upgrade():
    insecure_column = sa.Column('insecure',
                                sa.Boolean(create_constraint=False),
                                default=False)
    op.add_column('baymodel', insecure_column)
    baymodel = sa.sql.table('baymodel',
                            sa.Column('insecure',
                                      sa.Boolean(create_constraint=False),
                                      default=False))
    op.execute(
        baymodel.update().values({'insecure': True})
    )


text:
package org.marketcetera.orderloader;

import static org.marketcetera.orderloader.Messages.*;

import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.cli.*;
import org.marketcetera.client.ClientParameters;
import org.marketcetera.core.ApplicationContainer;
import org.marketcetera.core.ApplicationVersion;
import org.marketcetera.trade.BrokerID;
import org.marketcetera.util.except.I18NException;
import org.marketcetera.util.log.SLF4JLoggerProxy;
import org.marketcetera.util.misc.ClassVersion;
import org.springframework.context.Lifecycle;

/* $License$ */
/**
 * The entry point for running the order loader as an application
 *
 * @author anshul@marketcetera.com
 * @author Colin DuPlantis
 * @version $Id: OrderLoaderMain.java 16841 2014-02-20 19:59:04Z colin $
 * @since 1.0.0
 */
@ClassVersion("$Id: OrderLoaderMain.java 16841 2014-02-20 19:59:04Z colin $")
public class OrderLoaderMain
        implements Lifecycle
{
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#isRunning()
     */
    @Override
    public boolean isRunning()
    {
        return running.get();
    }
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#start()
     */
    @Override
    public void start()
    {
        run(getArgs());
        running.set(true);
        exit();
    }
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#stop()
     */
    @Override
    public void stop()
    {
        running.set(false);
    }
    /**
     * Get the clientUsername value.
     *
     * @return a String value
     */
    public String getClientUsername()
    {
        return clientUsername;
    }
    /**
     * Sets the clientUsername value.
     *
     * @param inClientUsername a String value
     */
    public void setClientUsername(String inClientUsername)
    {
        clientUsername = inClientUsername;
    }
    /**
     * Sets the clientPassword value.
     *
     * @param inClientPassword a char[] value
     */
    public void setClientPassword(char[] inClientPassword)
    {
        clientPassword = inClientPassword;
    }
    /**
     * Get the clientURL value.
     *
     * @return a String value
     */
    public String getClientURL()
    {
        return clientURL;
    }
    /**
     * Sets the clientURL value.
     *
     * @param inClientURL a String value
     */
    public void setClientURL(String inClientURL)
    {
        clientURL = inClientURL;
    }
    /**
     * Get the clientWsHost value.
     *
     * @return a String value
     */
    public String getClientWsHost()
    {
        return clientWsHost;
    }
    /**
     * Sets the clientWsHost value.
     *
     * @param inClientWsHost a String value
     */
    public void setClientWsHost(String inClientWsHost)
    {
        clientWsHost = inClientWsHost;
    }
    /**
     * Get the clientIdPrefix value.
     *
     * @return a String value
     */
    public String getClientIdPrefix()
    {
        return clientIdPrefix;
    }
    /**
     * Sets the clientIdPrefix value.
     *
     * @param inClientIdPrefix a String value
     */
    public void setClientIdPrefix(String inClientIdPrefix)
    {
        clientIdPrefix = inClientIdPrefix;
    }
    /**
     * Get the clientWsPort value.
     *
     * @return a String value
     */
    public String getClientWsPort()
    {
        return clientWsPort;
    }
    /**
     * Sets the clientWsPort value.
     *
     * @param inClientWsPort a String value
     */
    public void setClientWsPort(String inClientWsPort)
    {
        clientWsPort = inClientWsPort;
    }
    /**
     * Sets the stream on which all the messages should be printed.
     *
     * @param inMsgStream the message stream on which all the messages should
     * be printed.
     */
    protected void setMsgStream(PrintStream inMsgStream)
    {
        mMsgStream = inMsgStream;
    }
    /**
     * Exits the current process with the supplied exit code.
     */
    protected void exit()
    {
        ApplicationContainer.stopInstanceWaiting();
    }
    /**
     *
     *
     *
     * @return
     */
    protected String[] getArgs()
    {
        return ApplicationContainer.getInstanceArguments();
    }
    /**
     * Reads the orders from the supplied and sends them to the server.
     *
     * @throws Exception if there were errors.
     */
    protected void doProcessing()
            throws Exception
    {
        // create the order processor
        ClientParameters parameters = new ClientParameters(clientUsername,
                                                           clientPassword,
                                                           clientURL,
                                                           clientWsHost,
                                                           Integer.parseInt(clientWsPort),
                                                           clientIdPrefix);
        OrderProcessor processor = createProcessor(parameters);
        // run the order loader and display the summary of results.
        try {
            displaySummary(new OrderLoader(mMode,
                                           mBrokerID,
                                           processor,
                                           new File(mFilename)));
        } finally {
            processor.done();
        }
    }

    /**
     * Creates a processor given the parameters.
     *

     * This method is an implementation artifact to aid unit testing.
     *
     * @param inParameters the parameters to connect to the server.
     *
     * @return the order processor that will send orders to the server.
     *
     * @throws Exception if there were errors creating the order processor.
     */
    protected OrderProcessor createProcessor(ClientParameters inParameters)
            throws Exception
    {
        return new ServerOrderProcessor(inParameters);
    }
    /**
     * Displays the summary of results after the order loader is done processing.
     *
     * @param inLoader the order loader instance.
     */
    protected void displaySummary(OrderLoader inLoader)
    {
        printMessage(LINE_SUMMARY.getText(inLoader.getNumLines(),
                                          inLoader.getNumBlankLines(),
                                          inLoader.getNumComments()));
        printMessage(ORDER_SUMMARY.getText(inLoader.getNumSuccess(),
                                           inLoader.getNumFailed()));
        List<FailedOrderInfo> list = inLoader.getFailedOrders();
        if(!list.isEmpty()) {
            printMessage(FAILED_ORDERS.getText());
            for(FailedOrderInfo info: list) {
                printMessage(FAILED_ORDER.getText(info.getIndex(),
                                                  Arrays.toString(info.getRow()),
                                                  getExceptionMsg(info.getException())));
            }
        }
    }
    /**
     * Prints the message to the output.
     *
     * @param inMessage the message to print.
     */
    protected void printMessage(String inMessage)
    {
        mMsgStream.println(inMessage);
    }
    /**
     * Prints the supplied exception's message to the output.
     *
     * @param inException the exception whose messages should be
     * printed on the output.
     */
    protected void printError(Exception inException)
    {
        printMessage(getExceptionMsg(inException));
        SLF4JLoggerProxy.debug(this,
                               inException);
    }
    /**
     * Gets the exception message from the supplied exception.
     *
     * @param inException the exception
     *
     * @return the message from the exception.
     */
    protected String getExceptionMsg(Exception inException)
    {
        if(inException instanceof I18NException) {
            return ((I18NException)inException).getLocalizedDetail();
        } else {
            return inException.getLocalizedMessage();
        }
    }
    /**
     * Runs the supplied instance given the arguments.
     *
     * @param inArgs the command line arguments to run.
     */
    private void run(String[] inArgs)
    {
        printMessage(LOG_APP_COPYRIGHT.getText());
        printMessage(LOG_APP_VERSION_BUILD.getText(ApplicationVersion.getVersion(),
                                                   ApplicationVersion.getBuildNumber()));
        try {
            execute(new GnuParser().parse(options(),
                                          inArgs));
        } catch (Exception e) {
            printError(e);
            usage();
        }
    }
    /**
     * Executes the given parsed command line.
     *
     * @param inLine a CommandLine value
     * @throws Exception if an error occurs parsing the command line
     */
    private void execute(CommandLine inLine)
            throws Exception
    {
        if(inLine.hasOption(OPT_USERNAME)) {
            clientUsername = inLine.getOptionValue(OPT_USERNAME);
        }
        if(inLine.hasOption(OPT_PASSWORD)) {
            clientPassword = inLine.getOptionValue(OPT_PASSWORD).toCharArray();
        }
        if(inLine.hasOption(OPT_MODE)) {
            mMode = inLine.getOptionValue(OPT_MODE);
        }
        if(inLine.hasOption(OPT_BROKER)) {
            mBrokerID = new BrokerID(inLine.getOptionValue(OPT_BROKER));
        }
        if(inLine.getArgList().isEmpty()) {
            throw new IllegalArgumentException(ERROR_MISSING_FILE.getText());
        } else {
            mFilename = String.valueOf(inLine.getArgList().remove(0));
        }
        if(!inLine.getArgList().isEmpty()) {
            throw new IllegalArgumentException(ERROR_TOO_MANY_ARGUMENTS.getText());
        }
        doProcessing();
    }
    /**
     * Constructs the command line options for the orderloader.
     *
     * @return an Options value
     */
    @SuppressWarnings("static-access")
    private static Options options()
    {
        Options opts = new Options();
        opts.addOption(OptionBuilder.hasArg().withArgName(ARG_MODE_VALUE.getText()).withDescription(ARG_MODE_DESCRIPTION.getText()).isRequired(false).create(OPT_MODE));
        opts.addOption(OptionBuilder.hasArg().withArgName(ARG_BROKER_VALUE.getText()).withDescription(ARG_BROKER_DESCRIPTION.getText()).isRequired(false).create(OPT_BROKER));
        opts.addOption(OptionBuilder.hasArg().withArgName(ARG_USERNAME_VALUE.getText()).withDescription(ARG_USERNAME_DESCRIPTION.getText()).isRequired(false).create(OPT_USERNAME));
        opts.addOption(OptionBuilder.hasArg().withArgName(ARG_PASSWORD_VALUE.getText()).withDescription(ARG_PASSWORD_DESCRIPTION.getText()).isRequired(false).create(OPT_PASSWORD));
        return opts;
    }
    /**
     * Prints the usage to the output.
     */
    private void usage()
    {
        HelpFormatter formatter = new HelpFormatter();
        PrintWriter pw = new PrintWriter(mMsgStream);
        pw.append(ERROR_USAGE.getText());
        pw.println();
        formatter.printOptions(pw,
                               HelpFormatter.DEFAULT_WIDTH,
                               options,
                               HelpFormatter.DEFAULT_LEFT_PAD,
                               HelpFormatter.DEFAULT_DESC_PAD);
        pw.println();
        pw.flush();
        exit();
    }
    /**
     * options value contains all command line options
     */
    private final Options options = options();
    /**
     * print stream used to render output
     */
    private PrintStream mMsgStream = System.err;
    /**
     * FIX mode to use
     */
    private String mMode;
    /**
     * broker ID to use
     */
    private BrokerID mBrokerID;
    /**
     * filename to parse
     */
    private String mFilename;
    /**
     *
     */
    private static final String OPT_MODE = "m";  //$NON-NLS-1$
    /**
     *
     */
    private static final String OPT_BROKER = "b";  //$NON-NLS-1$
    /**
     *
     */
    private static final String OPT_USERNAME = "u";  //$NON-NLS-1$
    /**
     *
     */
    private static final String OPT_PASSWORD = "p";  //$NON-NLS-1$
    /**
     * indicates if the order loader is running or not
     */
    private final AtomicBoolean running = new AtomicBoolean(false);
    private String clientUsername;
    /**
     *
     */
    private char[] clientPassword;
    /**
     *
     */
    private String clientURL;
    /**
     *
     */
    private String clientWsHost;
    /**
     *
     */
    private String clientIdPrefix;
    /**
     *
     */
    private String clientWsPort;
}