text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using TableDependency.SqlClient.Base.Enums;
using TableDependency.SqlClient.Base.EventArgs;

namespace TableDependency.SqlClient.Test
{
    public class GuidSmallMoneyTypesModel
    {
        public Guid UniqueidentifierColumn { get; set; }
        public TimeSpan? Time7Column { get; set; }
        public byte TinyintColumn { get; set; }
        public DateTime SmalldatetimeColumn { get; set; }
        public short SmallintColumn { get; set; }
        public Decimal MoneyColumn { get; set; }
        public Decimal SmallmoneyColumn { get; set; }
    }

    [TestClass]
    public class GuidSmallMoneyTypesTest : Base.SqlTableDependencyBaseTest
    {
        private static readonly string TableName = typeof(GuidSmallMoneyTypesModel).Name;
        private static Dictionary<string, Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>> _checkValues = new Dictionary<string, Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>>();
        private static Dictionary<string, Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>> _checkValuesOld = new Dictionary<string, Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>>();

        [ClassInitialize]
        public static void ClassInitialize(TestContext testContext)
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
                    sqlCommand.ExecuteNonQuery();

                    sqlCommand.CommandText = $"CREATE TABLE {TableName}(" +
                        "uniqueidentifierColumn uniqueidentifier, " +
                        "time7Column time(7) NULL, " +
                        "tinyintColumn tinyint NULL, " +
                        "smalldatetimeColumn smalldatetime NULL, " +
                        "smallintColumn smallint NULL, " +
                        "moneyColumn money NULL," +
                        "smallmoneyColumn smallmoney NULL)";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }

        [TestInitialize]
        public void TestInitialize()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"DELETE FROM [{TableName}];";
                    sqlCommand.ExecuteNonQuery();
                }
            }

            _checkValues.Clear();
            _checkValuesOld.Clear();

            // https://msdn.microsoft.com/en-us/library/bb675168%28v=vs.110%29.aspx
            _checkValues.Add(ChangeType.Insert.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = Guid.NewGuid(), Time7Column = DateTime.Parse("23:59:59").TimeOfDay, TinyintColumn = 1, SmalldatetimeColumn = DateTime.Now.Date, SmallintColumn = 1, MoneyColumn = 123.77M, SmallmoneyColumn = 2.3M }, new GuidSmallMoneyTypesModel()));
            _checkValues.Add(ChangeType.Update.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = Guid.NewGuid(), Time7Column = DateTime.Parse("13:59:59").TimeOfDay, TinyintColumn = 2, SmalldatetimeColumn = DateTime.Now.Date.AddDays(1), SmallintColumn = 1, MoneyColumn = 23.77M, SmallmoneyColumn = 1.3M }, new GuidSmallMoneyTypesModel()));
            _checkValues.Add(ChangeType.Delete.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = _checkValues[ChangeType.Update.ToString()].Item2.UniqueidentifierColumn, Time7Column = DateTime.Parse("13:59:59").TimeOfDay, TinyintColumn = 2, SmalldatetimeColumn = DateTime.Now.Date.AddDays(1), SmallintColumn = 1, MoneyColumn = 23.77M, SmallmoneyColumn = 1.3M }, new GuidSmallMoneyTypesModel()));

            _checkValuesOld.Add(ChangeType.Insert.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = Guid.NewGuid(), Time7Column = DateTime.Parse("23:59:59").TimeOfDay, TinyintColumn = 1, SmalldatetimeColumn = DateTime.Now.Date, SmallintColumn = 1, MoneyColumn = 123.77M, SmallmoneyColumn = 2.3M }, new GuidSmallMoneyTypesModel()));
            _checkValuesOld.Add(ChangeType.Update.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = Guid.NewGuid(), Time7Column = DateTime.Parse("13:59:59").TimeOfDay, TinyintColumn = 2, SmalldatetimeColumn = DateTime.Now.Date.AddDays(1), SmallintColumn = 1, MoneyColumn = 23.77M, SmallmoneyColumn = 1.3M }, new GuidSmallMoneyTypesModel()));
            _checkValuesOld.Add(ChangeType.Delete.ToString(), new Tuple<GuidSmallMoneyTypesModel, GuidSmallMoneyTypesModel>(new GuidSmallMoneyTypesModel { UniqueidentifierColumn = _checkValues[ChangeType.Update.ToString()].Item2.UniqueidentifierColumn, Time7Column = DateTime.Parse("13:59:59").TimeOfDay, TinyintColumn = 2, SmalldatetimeColumn = DateTime.Now.Date.AddDays(1), SmallintColumn = 1, MoneyColumn = 23.77M, SmallmoneyColumn = 1.3M }, new GuidSmallMoneyTypesModel()));
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }

        [TestCategory("SqlServer")]
        [TestMethod]
        public void Test()
        {
            SqlTableDependency<GuidSmallMoneyTypesModel> tableDependency = null;
            string naming;

            try
            {
                tableDependency = new SqlTableDependency<GuidSmallMoneyTypesModel>(ConnectionStringForTestUser, tableName: TableName);
                tableDependency.OnChanged += this.TableDependency_Changed;
                tableDependency.Start();
                naming = tableDependency.DataBaseObjectsNamingConvention;

                var t = new Task(ModifyTableContent);
                t.Start();
                Thread.Sleep(1000 * 15 * 1);
            }
            finally
            {
                tableDependency?.Dispose();
            }

            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.UniqueidentifierColumn, _checkValues[ChangeType.Insert.ToString()].Item1.UniqueidentifierColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.Time7Column, _checkValues[ChangeType.Insert.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Insert.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmallmoneyColumn);
            Assert.IsNull(_checkValuesOld[ChangeType.Insert.ToString()]);

            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.Time7Column, _checkValues[ChangeType.Update.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Update.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Update.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallmoneyColumn);
            Assert.IsNull(_checkValuesOld[ChangeType.Update.ToString()]);

            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.Time7Column, _checkValues[ChangeType.Delete.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Delete.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallmoneyColumn);
            Assert.IsNull(_checkValuesOld[ChangeType.Delete.ToString()]);

            Assert.IsTrue(base.AreAllDbObjectDisposed(naming));
            Assert.IsTrue(base.CountConversationEndpoints(naming) == 0);
        }

        [TestCategory("SqlServer")]
        [TestMethod]
        public void TestWithOldValues()
        {
            SqlTableDependency<GuidSmallMoneyTypesModel> tableDependency = null;
            string naming;

            try
            {
                tableDependency = new SqlTableDependency<GuidSmallMoneyTypesModel>(ConnectionStringForTestUser, includeOldValues: true, tableName: TableName);
                tableDependency.OnChanged += this.TableDependency_Changed;
                tableDependency.Start();
                naming = tableDependency.DataBaseObjectsNamingConvention;

                var t = new Task(ModifyTableContent);
                t.Start();
                Thread.Sleep(1000 * 5 * 1);
            }
            finally
            {
                tableDependency?.Dispose();
            }

            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.UniqueidentifierColumn, _checkValues[ChangeType.Insert.ToString()].Item1.UniqueidentifierColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.Time7Column, _checkValues[ChangeType.Insert.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Insert.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Insert.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item1.SmallmoneyColumn);
            Assert.IsNull(_checkValuesOld[ChangeType.Insert.ToString()]);

            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.Time7Column, _checkValues[ChangeType.Update.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Update.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Update.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Update.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Update.ToString()].Item1.SmallmoneyColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Insert.ToString()].Item2.SmallintColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.Time7Column, _checkValues[ChangeType.Insert.ToString()].Item2.Time7Column);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Insert.ToString()].Item2.TinyintColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Insert.ToString()].Item2.SmalldatetimeColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Insert.ToString()].Item2.SmallintColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item2.MoneyColumn);
            Assert.AreEqual(_checkValuesOld[ChangeType.Update.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Insert.ToString()].Item2.SmallmoneyColumn);

            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.Time7Column, _checkValues[ChangeType.Delete.ToString()].Item1.Time7Column);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.TinyintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.TinyintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmalldatetimeColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmalldatetimeColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallintColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallintColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.MoneyColumn, _checkValues[ChangeType.Delete.ToString()].Item1.MoneyColumn);
            Assert.AreEqual(_checkValues[ChangeType.Delete.ToString()].Item2.SmallmoneyColumn, _checkValues[ChangeType.Delete.ToString()].Item1.SmallmoneyColumn);
            Assert.IsNull(_checkValuesOld[ChangeType.Delete.ToString()]);

            Assert.IsTrue(base.AreAllDbObjectDisposed(naming));
            Assert.IsTrue(base.CountConversationEndpoints(naming) == 0);
        }

        private void TableDependency_Changed(object sender, RecordChangedEventArgs<GuidSmallMoneyTypesModel> e)
        {
            switch (e.ChangeType)
            {
                case ChangeType.Insert:
                    _checkValues[ChangeType.Insert.ToString()].Item2.UniqueidentifierColumn = e.Entity.UniqueidentifierColumn;
                    _checkValues[ChangeType.Insert.ToString()].Item2.Time7Column = e.Entity.Time7Column;
                    _checkValues[ChangeType.Insert.ToString()].Item2.TinyintColumn = e.Entity.TinyintColumn;
                    _checkValues[ChangeType.Insert.ToString()].Item2.SmalldatetimeColumn = e.Entity.SmalldatetimeColumn;
                    _checkValues[ChangeType.Insert.ToString()].Item2.SmallintColumn = e.Entity.SmallintColumn;
                    _checkValues[ChangeType.Insert.ToString()].Item2.MoneyColumn = e.Entity.MoneyColumn;
                    _checkValues[ChangeType.Insert.ToString()].Item2.SmallmoneyColumn = e.Entity.SmallmoneyColumn;

                    if (e.EntityOldValues != null)
                    {
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.UniqueidentifierColumn = e.EntityOldValues.UniqueidentifierColumn;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.Time7Column = e.EntityOldValues.Time7Column;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.TinyintColumn = e.EntityOldValues.TinyintColumn;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.SmalldatetimeColumn = e.EntityOldValues.SmalldatetimeColumn;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.SmallintColumn = e.EntityOldValues.SmallintColumn;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.MoneyColumn = e.EntityOldValues.MoneyColumn;
                        _checkValuesOld[ChangeType.Insert.ToString()].Item2.SmallmoneyColumn = e.EntityOldValues.SmallmoneyColumn;
                    }
                    else
                    {
                        _checkValuesOld[ChangeType.Insert.ToString()] = null;
                    }

                    break;

                case ChangeType.Update:
                    _checkValues[ChangeType.Update.ToString()].Item2.UniqueidentifierColumn = e.Entity.UniqueidentifierColumn;
                    _checkValues[ChangeType.Update.ToString()].Item2.Time7Column = e.Entity.Time7Column;
                    _checkValues[ChangeType.Update.ToString()].Item2.TinyintColumn = e.Entity.TinyintColumn;
                    _checkValues[ChangeType.Update.ToString()].Item2.SmalldatetimeColumn = e.Entity.SmalldatetimeColumn;
                    _checkValues[ChangeType.Update.ToString()].Item2.SmallintColumn = e.Entity.SmallintColumn;
                    _checkValues[ChangeType.Update.ToString()].Item2.MoneyColumn = e.Entity.MoneyColumn;
                    _checkValues[ChangeType.Update.ToString()].Item2.SmallmoneyColumn = e.Entity.SmallmoneyColumn;

                    if (e.EntityOldValues != null)
                    {
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.UniqueidentifierColumn = e.EntityOldValues.UniqueidentifierColumn;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.Time7Column = e.EntityOldValues.Time7Column;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.TinyintColumn = e.EntityOldValues.TinyintColumn;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.SmalldatetimeColumn = e.EntityOldValues.SmalldatetimeColumn;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.SmallintColumn = e.EntityOldValues.SmallintColumn;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.MoneyColumn = e.EntityOldValues.MoneyColumn;
                        _checkValuesOld[ChangeType.Update.ToString()].Item2.SmallmoneyColumn = e.EntityOldValues.SmallmoneyColumn;
                    }
                    else
                    {
                        _checkValuesOld[ChangeType.Update.ToString()] = null;
                    }

                    break;

                case ChangeType.Delete:
                    _checkValues[ChangeType.Delete.ToString()].Item2.UniqueidentifierColumn = e.Entity.UniqueidentifierColumn;
                    _checkValues[ChangeType.Delete.ToString()].Item2.Time7Column = e.Entity.Time7Column;
                    _checkValues[ChangeType.Delete.ToString()].Item2.TinyintColumn = e.Entity.TinyintColumn;
                    _checkValues[ChangeType.Delete.ToString()].Item2.SmalldatetimeColumn = e.Entity.SmalldatetimeColumn;
                    _checkValues[ChangeType.Delete.ToString()].Item2.SmallintColumn = e.Entity.SmallintColumn;
                    _checkValues[ChangeType.Delete.ToString()].Item2.MoneyColumn = e.Entity.MoneyColumn;
                    _checkValues[ChangeType.Delete.ToString()].Item2.SmallmoneyColumn = e.Entity.SmallmoneyColumn;

                    if (e.EntityOldValues != null)
                    {
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.UniqueidentifierColumn = e.EntityOldValues.UniqueidentifierColumn;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.Time7Column = e.EntityOldValues.Time7Column;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.TinyintColumn = e.EntityOldValues.TinyintColumn;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.SmalldatetimeColumn = e.EntityOldValues.SmalldatetimeColumn;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.SmallintColumn = e.EntityOldValues.SmallintColumn;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.MoneyColumn = e.EntityOldValues.MoneyColumn;
                        _checkValuesOld[ChangeType.Delete.ToString()].Item2.SmallmoneyColumn = e.EntityOldValues.SmallmoneyColumn;
                    }
                    else
                    {
                        _checkValuesOld[ChangeType.Delete.ToString()] = null;
                    }

                    break;
            }
        }

        private static void ModifyTableContent()
        {
            using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
            {
                sqlConnection.Open();
                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"INSERT INTO [{TableName}] (uniqueidentifierColumn, time7Column, tinyintColumn, smalldatetimeColumn, smallintColumn, moneyColumn, smallmoneyColumn) " +
                        "values (@uniqueidentifierColumn, @time7Column, @tinyintColumn, @smalldatetimeColumn, @smallintColumn, @moneyColumn, @smallmoneyColumn)";

                    sqlCommand.Parameters.Add(new SqlParameter("@uniqueidentifierColumn", SqlDbType.UniqueIdentifier) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.UniqueidentifierColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@time7Column", SqlDbType.Time) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.Time7Column });
                    sqlCommand.Parameters.Add(new SqlParameter("@tinyintColumn", SqlDbType.TinyInt) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.TinyintColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smalldatetimeColumn", SqlDbType.SmallDateTime) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.SmalldatetimeColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smallintColumn", SqlDbType.SmallInt) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.SmallintColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@moneyColumn", SqlDbType.Money) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.MoneyColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smallmoneyColumn", SqlDbType.SmallMoney) { Value = _checkValues[ChangeType.Insert.ToString()].Item1.SmallmoneyColumn });

                    sqlCommand.ExecuteNonQuery();
                }

                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"UPDATE [{TableName}] SET uniqueidentifierColumn = @uniqueidentifierColumn, time7Column = @time7Column, tinyintColumn = @tinyintColumn, smalldatetimeColumn = @smalldatetimeColumn, smallintColumn = @smallintColumn, moneyColumn = @moneyColumn, smallmoneyColumn = @smallmoneyColumn";

                    sqlCommand.Parameters.Add(new SqlParameter("@uniqueidentifierColumn", SqlDbType.UniqueIdentifier) { Value = _checkValues[ChangeType.Update.ToString()].Item1.UniqueidentifierColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@time7Column", SqlDbType.Time) { Value = _checkValues[ChangeType.Update.ToString()].Item1.Time7Column });
                    sqlCommand.Parameters.Add(new SqlParameter("@tinyintColumn", SqlDbType.TinyInt) { Value = _checkValues[ChangeType.Update.ToString()].Item1.TinyintColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smalldatetimeColumn", SqlDbType.SmallDateTime) { Value = _checkValues[ChangeType.Update.ToString()].Item1.SmalldatetimeColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smallintColumn", SqlDbType.SmallInt) { Value = _checkValues[ChangeType.Update.ToString()].Item1.SmallintColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@moneyColumn", SqlDbType.Money) { Value = _checkValues[ChangeType.Update.ToString()].Item1.MoneyColumn });
                    sqlCommand.Parameters.Add(new SqlParameter("@smallmoneyColumn", SqlDbType.SmallMoney) { Value = _checkValues[ChangeType.Update.ToString()].Item1.SmallmoneyColumn });

                    sqlCommand.ExecuteNonQuery();
                }

                using (var sqlCommand = sqlConnection.CreateCommand())
                {
                    sqlCommand.CommandText = $"DELETE FROM [{TableName}]";
                    sqlCommand.ExecuteNonQuery();
                }
            }
        }
    }
}


text:
package org.levigo.jadice.server.converterclient.configurations;

import com.levigo.jadice.server.Job;
import com.levigo.jadice.server.msoffice.MSWordNode;
import com.levigo.jadice.server.nodes.StreamInputNode;
import com.levigo.jadice.server.nodes.StreamOutputNode;

public class WordToPdfAConfig implements WorkflowConfiguration {

	public void configureWorkflow(Job job) {
		final MSWordNode wordNode = new MSWordNode();
		wordNode.setTargetMimeType("application/pdf;version=A-1");

		job.attach(new StreamInputNode() //
				.appendSuccessor(wordNode) //
				.appendSuccessor(new StreamOutputNode()));
	}

	public String getDescription() {
		return "MS Word file to PDF/A-1";
	}

	public String getID() {
		return "word2pdfA";
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.izforge.izpack.panels;

/**
 * Additional metadata for password elements.
 *
 * @author Dennis Reil
 *
 */
public class PasswordUIElement extends UIElement
{

    public PasswordUIElement()
    {
        super();
    }

    PasswordGroup passwordGroup;

    public PasswordGroup getPasswordGroup()
    {
        return passwordGroup;
    }

    public void setPasswordGroup(PasswordGroup passwordGroup)
    {
        this.passwordGroup = passwordGroup;
    }
}


text:
from __future__ import absolute_import
from __future__ import print_function
import logging

import numpy as np
from numpy.lib.recfunctions import append_fields

from sklearn.cluster import DBSCAN

from lmatools.coordinateSystems import GeographicSystem

from lmatools.flashsort.flash_stats import calculate_flash_stats, Flash

def gen_stream(vec, IDs): #<1>
    for v, vi in zip(vec, IDs):
        yield (v, vi)

def reset_buffer():
    buf = []
    return buf, buf.append

def gen_chunks(stream, start_time, max_duration, t_idx=-1):
    """ Generator function that consumes a stream of points, one at a
        time, and their unique index. These points are bundled together
        into a chunks of length max_duration along the time coordinate.

        For each point vector v, the time coordinate is given by v[t_idx]
    """
    next_time = start_time + max_duration
    v_buffer, append = reset_buffer() # slight optimization since attr lookup is avoided
    i_buffer, append_idx = reset_buffer()
    for v, vi in stream:
        append(v)
        append_idx(vi)
        t = v[t_idx]
        if t >= next_time:
            yield (np.asarray(v_buffer), np.asarray(i_buffer))
            v_buffer, append = reset_buffer()
            i_buffer, append_idx = reset_buffer()
            next_time = t+max_duration
    yield (np.asarray(v_buffer), np.asarray(i_buffer))

class ChunkedFlashSorter(object):
    """
    Sort LMA data from points to flashes using many small chunks
    of points. Allows for algorithms that do not scale efficiently with
    large numbers of points.

    The __init__ and geo_to_cartesian
    methods are more generally useful, and could be factored out into a
    generic flash sorting class.

    The actual clustering algorithm must be implemented in identify_clusters.
    A prototype method is provided below which indicates the necessary call
    signature.
    """
    def __init__(self, params, min_points=1, **kwargs):
        """
            params: dictionary of parameters used to perform data QC and clustering
            min_points: the minimum number of points allowed in a cluster

        """
        self.logger = logging.getLogger('FlashAutorunLogger')
        self.logger.info('%s', params)

        self.params = params
        self.min_points = min_points
        self.ctr_lat, self.ctr_lon, self.ctr_alt =  (
                            params['ctr_lat'], params['ctr_lon'], 0.0)

    def geo_to_cartesisan(self, lon, lat, alt):
        """ Convert lat, lon in degrees and altitude in meters to
            Earth-centered, Earth-fixed cartesian coordinates. Translate
            to coordinate center location. Returns X,Y,Z in meters.
        """
        geoCS = GeographicSystem()
        X,Y,Z = geoCS.toECEF(lon, lat, alt)
        Xc, Yc, Zc = geoCS.toECEF(self.ctr_lon, self.ctr_lat, self.ctr_alt)
        X, Y, Z = X-Xc, Y-Yc, Z-Zc
        return (X, Y, Z)

    def identify_clusters(self, data):
        """ For data with shape (N, D) in D dimensions, return
            a vector of labels of length N.

            min_points is the minimum number of points required to form a
            a cluster. For the DBSCAN algorithm, this is min_samples for
            a core cluster.

            This function adopts the convention that clusters labeled
            with an ID of -1 are singleton points not belonging to a
            cluster, consistent with the convention of sklearn.cluster.DBSCAN
        """
        err = "Please create a new subclass and implement this method"
        raise NotImplementedError(err)

    def gen_cluster_chunk_pairs(self, stream):
        """ Generator function that consumes a stream of chunks of data,
            and processes overlapping pairs. The stream is to consist of
            tuples of (chunk, pt_id), where pt_id is a unique index for
            each vector in chunk.
            Chunk is of shape (N, D) for N point vectors in D dimensions
            pt_id has shape (N,)

            Calls self.identify_clusters, which returns a vector N labels.
            The labels are presumed to adopt the convention that clusters labeled
            with an ID of -1 are singleton points not belonging to a
            cluster, consistent with the convention of sklearn.cluster.DBSCAN
        """
        chunk1, id1 = next(stream)
        for chunk2, id2 in stream:
            len1 = chunk1.shape[0]
            len2 = chunk2.shape[0]
            if len2 == 0:
                conc = chunk1
                concID = id1
                chunk2 = chunk1[0:0,:]
                id2 = id1[0:0]
            elif len1 == 0:
                conc = chunk2
                concID = id2
                chunk1 = chunk2[0:0,:]
                id1 = id2[0:0]
            else:
                print(id1.shape, id2.shape)
                conc = np.vstack((chunk1, chunk2))
                concID = np.concatenate((id1, id2))

            # do stuff with chunk 1 and 2
            labels = self.identify_clusters(conc)

            # defer sending these in one bundle ... need to ensure all labels
            # from this run of clustering stay together
            # clustered_output_target.send((chunk1, labels[:len1])) IS BAD

            # pull data out of chunk2 that was clustered as part of chunk 1
            chunk1_labelset = set(labels[:len1])
            if -1 in chunk1_labelset:
                chunk1_labelset.remove(-1) # remove the singleton cluster ID - we want to retain these from chunk 2.
            clustered_in_chunk2 = np.fromiter( ( True if label in chunk1_labelset else False for i,label in enumerate(labels[len1:])) , dtype=bool)
            clustered_in_chunk1 = np.ones(chunk1.shape[0], dtype = bool)
            clustered_mask = np.hstack((clustered_in_chunk1, clustered_in_chunk2))
            bundle_chunks = conc[clustered_mask,:]
            bundle_IDs = concID[clustered_mask]

            bundle_labels = np.concatenate((labels[:len1], labels[len1:][clustered_in_chunk2]))
            assert bundle_chunks.shape[0] == bundle_labels.shape[0]
            yield (bundle_chunks, bundle_labels, bundle_IDs)
            del bundle_chunks, bundle_labels
            # clustered_output_target.send((chunk2[clustered_in_chunk2], labels[len1:][clustered_in_chunk2]))

            residuals = conc[clustered_mask==False,:]
            # Because we pull some points from chunk2 and combine them with
            # flashes that started in chunk1, the data are now out of their
            # original order. Therefore, send along the data IDs that go with the
            # pulled points so that the original order is still tracked.
            residualIDs = concID[clustered_mask==False]

            # optimization TODO: pull clusters out of chunk 2 whose final point is greater
            # than the distance threshold from the end of the second chunk interval. They're already clustered
            # and don't need to be clustered again.

            # prepare for another chunk
            if len(residuals) == 0:
                residuals = chunk1[0:0,:] # empty array that preserves the number of dimensions in the data vector - no obs.
                residualIDs = id1[0:0]
            del chunk1, id1
            chunk1 = np.asarray(residuals)
            id1 = np.asarray(residualIDs)
            del residuals, residualIDs
        if chunk1.shape[0] != 0:
            labels = self.identify_clusters(chunk1)
            yield (chunk1, labels, id1)

    def aggregate_ids(self, stream):
        """ Final step in streamed clustering: consume clustered output from
            one or more chunks of data, ensuring that the IDs increment
            across chunk boundaries.
        """
        # TODO: remove v from loop below; not needed.
        unique_labels = set([-1])
        total = 0
        point_labels = []
        all_IDs = []
        # all_v = []
            # n_last = 0
        for (v, orig_labels, IDs) in stream:
            labels = np.atleast_1d(orig_labels).copy()
            if len(unique_labels) > 0:
                # Only add those labels that represent valid clusters (nonnegative) to the unique set.
                # Make sure labels increment continuously across all chunks received
                nonsingleton = (labels >= 0)
                labels[nonsingleton] = labels[nonsingleton] + (max(unique_labels) + 1)

            for l in set(labels):
                unique_labels.add(l)

            all_IDs.append(np.asarray(IDs))
            point_labels.append(labels)
            total += v.shape[0]

            del v, orig_labels, labels, IDs
        print("done with {0} total points".format(total))
        if total == 0:
            point_labels = np.asarray(point_labels, dtype=int)
            point_labels = np.asarray(all_IDs, dtype=int)
        else:
            point_labels = np.concatenate(point_labels)
            all_IDs = np.concatenate(all_IDs)
        print("returning {0} total points".format(total))
        return (unique_labels, point_labels, all_IDs)

    def create_flash_objs(self, lma, good_data, unique_labels, point_labels, all_IDs):
        """ lma is an LMADataset object. Its data instance gets overwritten
            with the qc'd, flash_id'd data, and it gains a flashes attribute
            with a list of flash objects resulting from flash sorting.

            all_IDs gives the index in the original data array to
            which each point_label corresponds.
            unique_labels is the set of all labels produced by previous stages
            in the flash sorting algorithm, including a -1 ID for all singleton flashes.
        """
        logger = self.logger

        # add flash_id column
        empty_labels = np.empty_like(point_labels)
        # placing good_data in a list due to this bug when good_data has length 1
        # http://stackoverflow.com/questions/36440557/typeerror-when-appending-fields-to-a-structured-array-of-size-one
        if 'flash_id' not in good_data.dtype.names:
            data = append_fields([good_data], ('flash_id',), (empty_labels,))
        else:
            data = good_data.copy()

        # all_IDs gives the index in the original data array to
        # which each point_label corresponds
        data['flash_id'][all_IDs] = point_labels

        # In the case of no data, lma.data.shape will have
        # length zero, i.e., a 0-d array

        if (len(data.shape) == 0) | (data.shape[0] == 0):
            # No data
            flashes = []
        else:
            # work first with non-singleton flashes
            # to have strictly positive flash ids
            print(data.shape)
            singles = (data['flash_id'] == -1)
            non_singleton = data[ np.logical_not(singles) ]
            print(non_singleton['flash_id'].shape)
            order = np.argsort(non_singleton['flash_id'])

            ordered_data = non_singleton[order]
            flid = ordered_data['flash_id']
            if (flid.shape[0]>0):
                max_flash_id = flid[-1]
            else:
                max_flash_id = 0
            try:
                assert max_flash_id == max(unique_labels)
            except AssertionError:
                print("Max flash ID {0} is not as expected from unique labels {1}".format(max_flash_id, max(unique_labels)))

            boundaries, = np.where(flid[1:]-flid[:-1])    # where indices are nonzero
            boundaries = np.hstack(([0], boundaries+1))

            max_idx = len(flid) #- 1
            slice_lower_edges = tuple(boundaries)
            slice_upper_edges = slice_lower_edges[1:] + (max_idx,)
            slices = list(zip(slice_lower_edges, slice_upper_edges))

            flashes = [ Flash(ordered_data[slice(*sl)]) for sl in slices ]

            print("finished non-singletons")

            # Now deal with the nonsingleton points.
            # Each singleton point will have a high flash_id,
            # starting with the previous maximum flash id.
            singleton = data[singles]
            n_singles = singleton.shape[0]

            # this operation works on a view of the original data array,
            # so it modifies the original data array
            singleton['flash_id'] += max_flash_id + 1 + np.arange(n_singles, dtype=int)

            singleton_flashes = [ Flash(singleton[i:i+1]) for i in range(n_singles)]

            data[singles] = singleton
            print("finished singletons")

            flashes += singleton_flashes

            logtext = "Calculating flash initation, centroid, area, etc. for %d flashes" % (len(flashes), )
            logger.info(logtext)
            # print flashes[0].points.dtype
            for fl in flashes:
                # header = ''.join(lma.header)
                fl.metadata = lma.metadata #FlashMetadata(header)
                calculate_flash_stats(fl)
                # logger.info(fl.points.shape[0])
            logger.info('finished setting flash metadata')

            lma.raw_data = lma.data
            lma.data = data
            assert (lma.data['flash_id'].min() >=0) # this should be true since the singletons were modified in the original data array above

        lma.flashes = flashes

    def perform_chunked_clustering(self, XYZT, ptIDs, chunk_duration):
        """ Perform clustering of a 4D data vector in overlapping chunks of
            data,

        XYZT: (N,4) array of N 4D point vectors
        ptIDs: array of N unique identifiers of each point vector.
        chunk_duration: duration of chunk in the units along the T coordinate

        """
        if XYZT.shape[0] < 1:
            # no data, so minimum time is zero. Assume nothing is done with the
            # data, so that time doesn't matter. No flashes can result.
            t_min = 0
        else:
            t_min = XYZT[:,-1].min()

        point_stream = gen_stream(XYZT.astype('float64'), ptIDs)
        chunk_stream = gen_chunks(point_stream, t_min, chunk_duration)
        cluster_stream = self.gen_cluster_chunk_pairs(chunk_stream)
        unique_labels, point_labels, all_IDs = self.aggregate_ids(cluster_stream)
        return unique_labels, point_labels, all_IDs

    def cluster(self, dataset, **kwargs):
        """ Cluster an lmatools LMADataset provided in the dataset argument.
            Basic filtering of the data is performed by calling the filter_data
            method of the dataset, which returns a filtered data array. The
            params are provided by the argument used to initialize this class.

            This method modifies dataset as a side effect.
        """

        data = dataset.filter_data(self.params)
        print("sorting {0} total points".format(data.shape[0]))

        # Transform to cartesian coordiantes
        X, Y, Z = self.geo_to_cartesisan(data['lon'], data['lat'], data['alt'])

        # Assemble a normalized data vector using flash sorting parameters
        D_max, t_max = (self.params['distance'], # meters
                        self.params['thresh_critical_time']) # seconds
        duration_max = self.params['thresh_duration'] # seconds

        IDs = np.arange(X.shape[0]) # Vector of unique point IDs
        X_vector = np.hstack((X[:,None],Y[:,None],Z[:,None])) / D_max
        T_vector = data['time'][:,None] / t_max
        XYZT = np.hstack((X_vector, T_vector))

        # Perform chunked clustering of the data
        normed_chunk_duration = duration_max/t_max
        unique_labels, point_labels, all_IDs = self.perform_chunked_clustering(XYZT, IDs, normed_chunk_duration)

        # Calculate flash metadata and store it in flash objects
        # This should be factored out into somehting that modifies the data table
        # and something that creates the flash objects themselves
        self.create_flash_objs(dataset, data, unique_labels, point_labels, all_IDs)

class DBSCANFlashSorter(ChunkedFlashSorter):
    def identify_clusters(self, data):
        """ For data with shape (N, D) in D dimensions, return
            a vector of labels of length N.

            min_points is the minimum number of points required to form a
            a cluster. For the DBSCAN algorithm, this is min_samples for
            a core cluster.

            This function adopts the convention that clusters labeled
            with an ID of -1 are singleton points not belonging to a
            cluster, consistent with the convention of sklearn.cluster.DBSCAN
        """
        db = DBSCAN(eps=1.0, min_samples=self.min_points, metric='euclidean')
        clusters = db.fit(data)
        labels = clusters.labels_.astype(int)
        return labels


text:
include_recipe 'travis_groovy'

ark 'gradle' do
  url node['travis_build_environment']['gradle_url']
  version node['travis_build_environment']['gradle_version']
  checksum node['travis_build_environment']['gradle_checksum']
  has_binaries %w[bin/gradle]
  owner 'root'
  group 'root'
end


text:
#pragma once

#include "kitBase/robotModel/robotParts/display.h"

#include "twoDModel/twoDModelDeclSpec.h"

namespace twoDModel {

namespace engine {
class TwoDModelEngineInterface;
}

namespace robotModel {
namespace parts {

/// An implementation of the display emulation device for the 2D model window.
/// Configuration is perfomed immediately.
class Display : public kitBase::robotModel::robotParts::Display
{
	Q_OBJECT

public:
	Display(const kitBase::robotModel::DeviceInfo &info
			, const kitBase::robotModel::PortInfo &port
			, engine::TwoDModelEngineInterface &engine);

private:
	engine::TwoDModelEngineInterface &mEngine;
};

}
}
}


text:
<meta charset="UTF-8">
<title>SequenceMatcher.detector - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.common / SequenceMatcher / detector

detector

val detector: SequenceDetector<T, U>


text:
package com.xti.jenkins.plugin.awslambda.invoke;

import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor;
import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils;
import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy;
import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.util.Secret;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;

import java.util.ArrayList;
import java.util.List;

public class LambdaInvokeVariables extends AbstractDescribableImpl<LambdaInvokeVariables> {
    private boolean useInstanceCredentials;
    private String awsAccessKeyId;
    private String awsSecretKey;
    private String clearTextAwsSecretKey;
    private String awsRegion;
    private String functionName;
    private String payload;
    private boolean synchronous;
    private boolean successOnly;
    private List<JsonParameterVariables> jsonParameters = new ArrayList<JsonParameterVariables>();

    @DataBoundConstructor
    public LambdaInvokeVariables(String awsRegion, String functionName, boolean synchronous) {
        this.awsRegion = awsRegion;
        this.functionName = functionName;
        this.synchronous = synchronous;
    }

    @Deprecated
    public LambdaInvokeVariables(boolean useInstanceCredentials, String awsAccessKeyId, Secret awsSecretKey, String awsRegion, String functionName, String payload, boolean synchronous, boolean successOnly, List<JsonParameterVariables> jsonParameters) {
        this.useInstanceCredentials = useInstanceCredentials;
        this.awsAccessKeyId = awsAccessKeyId;
        this.awsSecretKey = awsSecretKey != null ? awsSecretKey.getEncryptedValue() : null;
        this.awsRegion = awsRegion;
        this.functionName = functionName;
        this.payload = payload;
        this.synchronous = synchronous;
        this.successOnly = successOnly;
        this.jsonParameters = jsonParameters;
    }

    public boolean getUseInstanceCredentials() {
        return useInstanceCredentials;
    }

    @DataBoundSetter
    public void setUseInstanceCredentials(boolean useInstanceCredentials) {
        this.useInstanceCredentials = useInstanceCredentials;
    }

    public String getAwsAccessKeyId() {
        return awsAccessKeyId;
    }

    @DataBoundSetter
    public void setAwsAccessKeyId(String awsAccessKeyId) {
        this.awsAccessKeyId = awsAccessKeyId;
    }

    public String getAwsSecretKey() {
        return awsSecretKey;
    }

    @DataBoundSetter
    public void setAwsSecretKey(String awsSecretKey) {
        this.awsSecretKey = Secret.fromString(awsSecretKey).getEncryptedValue();
    }

    public String getAwsRegion() {
        return awsRegion;
    }

    public String getFunctionName() {
        return functionName;
    }

    public String getPayload() {
        return payload;
    }

    @DataBoundSetter
    public void setPayload(String payload) {
        this.payload = payload;
    }

    public boolean getSynchronous() {
        return synchronous;
    }

    public boolean getSuccessOnly() {
        return successOnly;
    }

    @DataBoundSetter
    public void setSuccessOnly(boolean successOnly) {
        this.successOnly = successOnly;
    }

    public List<JsonParameterVariables> getJsonParameters() {
        if(jsonParameters == null){
            return new ArrayList<>();
        } else {
            return jsonParameters;
        }
    }

    @DataBoundSetter
    public void setJsonParameters(List<JsonParameterVariables> jsonParameters) {
        this.jsonParameters = jsonParameters;
    }

    public void expandVariables(EnvVars env) {
        awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env);
        clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env);
        awsRegion = ExpansionUtils.expand(awsRegion, env);
        functionName = ExpansionUtils.expand(functionName, env);
        payload = ExpansionUtils.expand(payload, env);
        if(jsonParameters != null) {
            for (JsonParameterVariables jsonParameter : jsonParameters) {
                jsonParameter.expandVariables(env);
            }
        }
    }

    public LambdaInvokeVariables getClone(){
        LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous);
        lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials);
        lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId);
        lambdaInvokeVariables.setAwsSecretKey(awsSecretKey);
        lambdaInvokeVariables.setPayload(payload);
        lambdaInvokeVariables.setSuccessOnly(successOnly);
        lambdaInvokeVariables.setJsonParameters(jsonParameters);
        return lambdaInvokeVariables;
    }

    public InvokeConfig getInvokeConfig(){
        List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>();
        for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) {
            jsonParameters.add(jsonParameterVariables.buildJsonParameter());
        }
        return new InvokeConfig(functionName, payload, synchronous, jsonParameters);
    }

    public LambdaClientConfig getLambdaClientConfig(){
        if(useInstanceCredentials){
            return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
        } else {
            return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig());
        }
    }

    @Extension // This indicates to Jenkins that this is an implementation of an extension point.
    public static class DescriptorImpl extends AWSLambdaDescriptor<LambdaInvokeVariables> {

        /**
         * This human readable name is used in the configuration screen.
         */
        public String getDisplayName() {
            return "Invoke Lambda function";
        }

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        LambdaInvokeVariables that = (LambdaInvokeVariables) o;

        if (getUseInstanceCredentials() != that.getUseInstanceCredentials()) return false;
        if (getSynchronous() != that.getSynchronous()) return false;
        if (getSuccessOnly() != that.getSuccessOnly()) return false;
        if (getAwsAccessKeyId() != null ? !getAwsAccessKeyId().equals(that.getAwsAccessKeyId()) : that.getAwsAccessKeyId() != null)
            return false;
        if (getAwsSecretKey() != null ? !getAwsSecretKey().equals(that.getAwsSecretKey()) : that.getAwsSecretKey() != null)
            return false;
        if (getAwsRegion() != null ? !getAwsRegion().equals(that.getAwsRegion()) : that.getAwsRegion() != null)
            return false;
        if (getFunctionName() != null ? !getFunctionName().equals(that.getFunctionName()) : that.getFunctionName() != null)
            return false;
        if (getPayload() != null ? !getPayload().equals(that.getPayload()) : that.getPayload() != null) return false;
        return !(getJsonParameters() != null ? !getJsonParameters().equals(that.getJsonParameters()) : that.getJsonParameters() != null);

    }

    @Override
    public int hashCode() {
        int result = (getUseInstanceCredentials() ? 1 : 0);
        result = 31 * result + (getAwsAccessKeyId() != null ? getAwsAccessKeyId().hashCode() : 0);
        result = 31 * result + (getAwsSecretKey() != null ? getAwsSecretKey().hashCode() : 0);
        result = 31 * result + (getAwsRegion() != null ? getAwsRegion().hashCode() : 0);
        result = 31 * result + (getFunctionName() != null ? getFunctionName().hashCode() : 0);
        result = 31 * result + (getPayload() != null ? getPayload().hashCode() : 0);
        result = 31 * result + (getSynchronous() ? 1 : 0);
        result = 31 * result + (getSuccessOnly() ? 1 : 0);
        result = 31 * result + (getJsonParameters() != null ? getJsonParameters().hashCode() : 0);
        return result;
    }
}


text:
from networkapiclient.ApiGenericClient import ApiGenericClient
from networkapiclient.utils import build_uri_with_ids

class ApiCIDREnvironment(ApiGenericClient):

    def __init__(self, networkapi_url, user, password, user_ldap=None):
        """Class constructor receives parameters to connect to the networkAPI.
        :param networkapi_url: URL to access the network API.
        :param user: User for authentication.
        :param password: Password for authentication.
        """

        super(ApiCIDREnvironment, self).__init__(
            networkapi_url,
            user,
            password,
            user_ldap
        )

    def get(self, ids=None, **kwargs):
        """
        Method to get dc environments by their ids or list all.

        :param ids: List containing identifiers of environments
        :param include: Array containing fields to include on response.
        :param exclude: Array containing fields to exclude on response.
        :param fields: Array containing fields to override default fields.
        :param kind: Determine if result will be detailed ('detail') or basic ('basic').
        :return: Dict containing environments
        """
        url = build_uri_with_ids('api/v3/cidr/', ids)
        return super(ApiCIDREnvironment, self).get(self.prepare_url(url, kwargs))

    def get_by_env(self, env_id=None, **kwargs):

        url = build_uri_with_ids('api/v3/cidr/environment/%s', env_id)
        return super(ApiCIDREnvironment, self).get(self.prepare_url(url, kwargs))

    def search(self, **kwargs):
        """
        Method to search environments based on extends search.

        :param search: Dict containing QuerySets to find environments.
        :param include: Array containing fields to include on response.
        :param exclude: Array containing fields to exclude on response.
        :param fields:  Array containing fields to override default fields.
        :param kind: Determine if result will be detailed ('detail') or basic ('basic').
        :return: Dict containing environments
        """

        return super(ApiCIDREnvironment, self).get(self.prepare_url('api/v3/cidr/', kwargs))

    def post(self, cidrs):
        """
        Method to allocate a new network block.
        :param cidrs: List containing cidr objects.
        :return: The cidr id.
        """

        data = dict(cidr=cidrs)
        return super(ApiCIDREnvironment, self).post('api/v3/cidr/', data)

    def delete(self, cidr_id=None, environment_id=None):
        """
        Method to delete cidrs by their id's

        :param ids: Identifiers of cidrs
        :return: None
        """

        if cidr_id:
            url = build_uri_with_ids('api/v3/cidr/%s/', cidr_id)
        else:
            url = build_uri_with_ids('api/v3/cidr/environment/%s/', environment_id)

        return super(ApiCIDREnvironment, self).delete(url)


text:
const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 8895, 'localhost', (err) => {
	client.close();
    });


text:
package com.aol.cyclops.featuretoggle;

import java.util.Objects;
import java.util.Optional;

import com.aol.cyclops.lambda.api.AsAnyM;
import com.aol.cyclops.lambda.monads.AnyM;

import lombok.Value;

/**
 * An disabled switch
 *
 * <pre>
 *
 * Switch<Data> data = Switch.disabled(data);
 *
 * data.map(this::load);  //data will NOT be loaded because Switch is of type Disabled
 *
 * </pre>
 * @author johnmcclean
 *
 * @param <F> Type of value Enabled Switch holds
 */
@Value
public class Disabled<F> implements FeatureToggle<F>{

	private final F disabled;

    /**
     * Constructs a left.
     *
     * @param disabled The value of this Left
     */
    public Disabled(F disabled) {
        this.disabled = disabled;
    }

    /**
	 * @return This monad, wrapped as AnyM
	 */
	public AnyM<F> anyM(){
		return AsAnyM.notTypeSafeAnyM(Optional.empty());
	}
	/**
	 * @return This monad, wrapped as AnyM of Disabled
	 */
	public AnyM<F> anyMDisabled(){
		return  AsAnyM.notTypeSafeAnyM(this);
	}
	/**
	 * @return This monad, wrapped as AnyM of Enabled
	 */
	public AnyM<F> anyMEnabled(){
		return anyM();
	}
	/**
	 * Create a new disabled switch
	 *
	 * @param f switch value
	 * @return disabled switch
	 */
	public static <F> Disabled<F> of(F f){
		return new Disabled<F>(f);
	}
	/**
	 * Create a new disabled switch
	 *
	 * @param f switch value
	 * @return disabled switch
	 */
	public static <F> AnyM<F> anyMOf(F f){
		return new Disabled<F>(f).anyM();
	}
    /*
     *	@return value of this Disabled
     * @see com.aol.cyclops.enableswitch.Switch#get()
     */
    public F get(){
    	return disabled;
    }

    /*
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        return (obj == this) || (obj instanceof Disabled && Objects.equals(disabled, ((Disabled<?>) obj).disabled));
    }

    /*
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return Objects.hashCode(disabled);
    }

    /*
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("Disabled(%s)", disabled );
    }

	/*
	 *	@return false - is NOT enabled
	 * @see com.aol.cyclops.enableswitch.Switch#isEnabled()
	 */
	@Override
	public final boolean isEnabled() {
		return false;
	}

	/*
	 *	@return true - is Disabled
	 * @see com.aol.cyclops.enableswitch.Switch#isDisabled()
	 */
	@Override
	public final boolean isDisabled() {
		return true;
	}
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/services/customer_extension_setting_service.proto

package com.google.ads.googleads.v12.services;

public interface MutateCustomerExtensionSettingResultOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.services.MutateCustomerExtensionSettingResult)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * The mutated CustomerExtensionSetting with only mutable fields after mutate.
   * The field will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CustomerExtensionSetting customer_extension_setting = 2;
   * @return Whether the customerExtensionSetting field is set.
   */
  boolean hasCustomerExtensionSetting();
  /**
   *

   * The mutated CustomerExtensionSetting with only mutable fields after mutate.
   * The field will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CustomerExtensionSetting customer_extension_setting = 2;
   * @return The customerExtensionSetting.
   */
  com.google.ads.googleads.v12.resources.CustomerExtensionSetting getCustomerExtensionSetting();
  /**
   *

   * The mutated CustomerExtensionSetting with only mutable fields after mutate.
   * The field will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CustomerExtensionSetting customer_extension_setting = 2;
   */
  com.google.ads.googleads.v12.resources.CustomerExtensionSettingOrBuilder getCustomerExtensionSettingOrBuilder();
}


text:
package ru.fly.client.ui.panel.fieldset;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;
import ru.fly.client.F;
import ru.fly.client.ui.FElement;
import ru.fly.client.ui.panel.Margin;
import ru.fly.client.ui.panel.SingleLayout;

/**
 *
 * Created by fil on 06.01.14.
 */
public class FieldSetPanel extends SingleLayout {

    private final FieldSetDecor decor = GWT.create(FieldSetDecor.class);
    private final FElement container;
    private final FElement header;

    public FieldSetPanel(){
        super(DOM.createDiv());
        container = DOM.createFieldSet().cast();
        container.setClassName(decor.css().fieldset());
        header = DOM.createLegend().cast();
        F.setEnableTextSelection(header, false);
    }

    @Override
    public FElement getContainerElement() {
        return container;
    }

    public FieldSetPanel(String headerText){
        this();
        setHeaderText(headerText);
    }

    public void setHeaderText(String text){
        header.setInnerText(text);
    }

    @Override
    protected void onAfterFirstAttach() {
        super.onAfterFirstAttach();
        getElement().appendChild(container);
        container.insertFirst(header);
    }

    @Override
    public void setPixelSize(int width, int height) {
        super.setPixelSize(width, height);
        container.setPixelSize(width-2, height-2);
    }

    @Override
    protected void doLayout() {
        Widget child = getWidget();
        if(child != null && isAttached()){
            int w = getWidth(true) - 2;
            int h = getHeight(true) - header.getOffsetHeight() - 2;
            if(child.getLayoutData() instanceof Margin){
                Margin m = (Margin) child.getLayoutData();
                m.fillMargins(child);
                w = w - m.getLeft() - m.getRight();
                h = h - m.getTop() - m.getBottom();
            }
            child.setPixelSize(w, h);
        }
    }
}


text:
'use babel';

import LinkCreatorEquipdView from '../lib/link-creator-equipd-view';

describe('LinkCreatorEquipdView', () => {
  it('has one valid test', () => {
    expect('life').toBe('easy');
  });
});


text:
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif

#include "rpc.h"
#include "rpcndr.h"

#ifndef __RPCNDR_H_VERSION__
#error This stub requires an updated version of <rpcndr.h>
#endif

#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif

#ifndef __ctxtcall_h__
#define __ctxtcall_h__

#ifndef __IContextCallback_FWD_DEFINED__
#define __IContextCallback_FWD_DEFINED__
typedef struct IContextCallback IContextCallback;
#endif

#include "wtypes.h"
#include "objidl.h"
#ifdef __cplusplus
extern "C"{
#endif

#ifndef __MIDL_user_allocate_free_DEFINED__
#define __MIDL_user_allocate_free_DEFINED__
  void *__RPC_API MIDL_user_allocate(size_t);
  void __RPC_API MIDL_user_free(void *);
#endif

  typedef struct tagComCallData {
    DWORD dwDispid;
    DWORD dwReserved;
    void *pUserDefined;
  } ComCallData;

  extern RPC_IF_HANDLE __MIDL_itf_ctxtcall_0000_v0_0_c_ifspec;
  extern RPC_IF_HANDLE __MIDL_itf_ctxtcall_0000_v0_0_s_ifspec;

#ifndef __IContextCallback_INTERFACE_DEFINED__
#define __IContextCallback_INTERFACE_DEFINED__
  typedef HRESULT (WINAPI *PFNCONTEXTCALL)(ComCallData *pParam);
  EXTERN_C const IID IID_IContextCallback;
#if defined(__cplusplus) && !defined(CINTERFACE)
  struct IContextCallback : public IUnknown {
  public:
    virtual HRESULT WINAPI ContextCallback(PFNCONTEXTCALL pfnCallback,ComCallData *pParam,REFIID riid,int iMethod,IUnknown *pUnk) = 0;
  };
#else
  typedef struct IContextCallbackVtbl {
    BEGIN_INTERFACE
      HRESULT (WINAPI *QueryInterface)(IContextCallback *This,REFIID riid,void **ppvObject);
      ULONG (WINAPI *AddRef)(IContextCallback *This);
      ULONG (WINAPI *Release)(IContextCallback *This);
      HRESULT (WINAPI *ContextCallback)(IContextCallback *This,PFNCONTEXTCALL pfnCallback,ComCallData *pParam,REFIID riid,int iMethod,IUnknown *pUnk);
    END_INTERFACE
  } IContextCallbackVtbl;
  struct IContextCallback {
    CONST_VTBL struct IContextCallbackVtbl *lpVtbl;
  };
#ifdef COBJMACROS
#define IContextCallback_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject)
#define IContextCallback_AddRef(This) (This)->lpVtbl->AddRef(This)
#define IContextCallback_Release(This) (This)->lpVtbl->Release(This)
#define IContextCallback_ContextCallback(This,pfnCallback,pParam,riid,iMethod,pUnk) (This)->lpVtbl->ContextCallback(This,pfnCallback,pParam,riid,iMethod,pUnk)
#endif
#endif
  HRESULT WINAPI IContextCallback_ContextCallback_Proxy(IContextCallback *This,PFNCONTEXTCALL pfnCallback,ComCallData *pParam,REFIID riid,int iMethod,IUnknown *pUnk);
  void __RPC_STUB IContextCallback_ContextCallback_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
#endif

#ifdef __cplusplus
}
#endif
#endif


text:
var sinon = require('sinon'),
    path = require('path'),
    fs = require('fs');

var Record = require('../lib/record'),
    FileHandler = require('../lib/handler/file');

function rmdirSync(p) {
    try {
        var stat = fs.lstatSync(p);
    } catch (err) {
        if (err.code === "ENOENT") {
            return;
        } else {
            throw err;
        }
    }

    if (!stat.isDirectory()) {
        fs.unlinkSync(p);
    } else {
        fs.readdirSync(p).forEach(function (f) {
            rmdirSync(path.join(p, f))
        });

        fs.rmdirSync(p);
    }
}

var LOG_FOLDER = path.join(__dirname, 'log');

exports["FileHandler"] = {
    setUp: function(callback) {
        rmdirSync(LOG_FOLDER);
        fs.mkdirSync(LOG_FOLDER);

        this.record1 = new Record(Level.INFO, 'message1', undefined, 'logger');
        this.record2 = new Record(Level.INFO, 'message2', undefined, 'logger');

        this.formatter = sinon.stub();
        this.formatter.withArgs(this.record1).returns(this.record1.message);
        this.formatter.withArgs(this.record2).returns(this.record2.message);

        this.handler = new FileHandler(this.formatter, path.join(LOG_FOLDER, 'test.log'));

        callback();
    },

    tearDown: function(callback) {
        rmdirSync(LOG_FOLDER);
        callback();
    },

    "log record should have been written to disk when flushed event is emitted": function(test) {
        test.expect(1);

        this.handler.on('flushed', function() {
            var content = fs.readFileSync(path.join(LOG_FOLDER, 'test.log'));
            test.equal(content, this.record1.message + '\n');
            test.done();
        }.bind(this));

        this.handler.publish(this.record1);
    },

    "calling reopen should reopen the file (logrotate use case)": function(test) {
        test.expect(2);

        this.handler.once('flushed', function() {
            this.handler.once('flushed', function() {
                var content1 = fs.readFileSync(path.join(LOG_FOLDER, 'test.log.1'));
                var content2 = fs.readFileSync(path.join(LOG_FOLDER, 'test.log'));
                test.equal(content1, this.record1.message + '\n');
                test.equal(content2, this.record2.message + '\n');
                test.done();
            }.bind(this));

            fs.renameSync(path.join(LOG_FOLDER, 'test.log'),
                          path.join(LOG_FOLDER, 'test.log.1'));

            this.handler.reopen();
            this.handler.publish(this.record2);
        }.bind(this));

        this.handler.publish(this.record1);
    },

    "the handler should emit an error if the file can't be opened/created": function(test) {
        test.expect(1);

        var handler = new FileHandler(this.formatter, path.join(__dirname, 'foo/test.log'));

        handler.on('error', function() {
            test.ok(true);
            test.done();
        });

        handler.open();
    },

    "explicitly calling flush should trigger a flushed event": function(test) {
        test.expect(1);

        this.handler.on('flushed', function() {
            test.ok(true);
            test.done();
        }.bind(this));

        this.handler.flush();
    }
};


text:
import Attribute from '../../../src/finitio/support/attribute';
import Heading from '../../../src/finitio/support/heading';
import BuiltinType from '../../../src/finitio/type/builtin_type';
import should from 'should';
import { anyType, intType } from '../../spec_helpers';

describe('Heading#multi', () => {

  const red = new Attribute('red', intType);
  const blue = new Attribute('blue', intType);
  const maybe_blue = new Attribute('blue', intType, false);

  const subject = (attributes, options) => new Heading(attributes, options).multi();

  describe('with no attribute', () => it('should be false', () => subject([]).should.equal(false)));

  describe('with required attributes only', () => it('should be false', () => subject([red, blue]).should.equal(false)));

  describe('with some optional attributes', () => it('should be true', () => subject([red, maybe_blue]).should.equal(true)));

  describe('with allowExtra set to AnyType', () => it('should be true', () => subject([red, blue], { allowExtra: anyType }).should.equal(true)));

  return describe('with allowExtra set a specific Type', () => it('should be true', () => subject([red, blue], { allowExtra: intType }).should.equal(true)));
});


text:
package ro.stancalau.lombok.examples.correct;

import com.github.peterwippermann.junit4.parameterizedsuite.ParameterizedSuite;
import org.junit.runner.RunWith;
import ro.stancalau.lombok.tests.FieldVisibilityTests;
import ro.stancalau.lombok.tests.base.TestParam;
import ro.stancalau.lombok.tests.person.PersonConstructorAndGetterTests;
import ro.stancalau.lombok.tests.person.PersonSetterTests;

import static org.junit.runners.Parameterized.Parameter;
import static org.junit.runners.Parameterized.Parameters;
import static org.junit.runners.Suite.SuiteClasses;

@RunWith(ParameterizedSuite.class)
@SuiteClasses({
        FieldVisibilityTests.class,
        PersonConstructorAndGetterTests.class,
        PersonSetterTests.class
})
public class CorrectMutablePersonSuite {

    private static final Class CLASS_UNDER_TEST = CorrectMutablePerson.class;

    @Parameters(name = "Class under test is {0}")
    public static Object[] params() {
        return new Object[][]{{new TestParam(CLASS_UNDER_TEST)}};
    }

    @Parameter
    public TestParam param;
}


text:
package pe.com.equifax.informa.web.iris.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import pe.com.equifax.informa.common.beans.BusquedaBean;
import pe.com.equifax.informa.common.beans.ProductoBean;
import pe.com.equifax.informa.common.beans.UsuarioBean;
import pe.com.equifax.informa.iris.beans.ConsumoSectorBean;
import pe.com.equifax.informa.iris.beans.IdentificacionBean;
import pe.com.equifax.informa.iris.beans.PersonaJuridicaBean;
import pe.com.equifax.informa.web.utils.CommonUtils;
import pe.com.equifax.informa.web.utils.Constants;

@Controller
public class IdentificacionController {

	@Autowired
	private RestTemplate restTemplate;
	private static Logger logger = Logger.getLogger(IdentificacionController.class);
	public static final int CANT_MESES_DEFECTO = 6;
	private static String url = CommonUtils.readValueProperties("rutaBaseDIFUSION");

	public IdentificacionController() {
	}

	@RequestMapping(value="identificacionEMP", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView doService(
			@RequestParam(value = Constants.REQUEST_IDPROD) String idProd,
			HttpServletRequest request, HttpSession session) {

		ModelAndView model = new ModelAndView();
		String page = "layout_templates/error";
		String type = request.getParameter(Constants.REQUEST_TIPO);
		String idMod = request.getParameter(Constants.REQUEST_IDMOD);
		String view = null;

		BusquedaBean busqueda = (BusquedaBean)session.getAttribute(Constants.SESSION_BUSQUEDA);
		ProductoBean producto = CommonUtils.getProducto(idProd, idMod);
		UsuarioBean usuario = CommonUtils.getUsuario();
		if (busqueda == null) {
			logger.info("Intento de acceso a un producto sin previa busqueda");
			model.setViewName("redirect:" + usuario.getBusqueda().getController() + "&idProd=" + usuario.getBusqueda().getCodigo());
			return model;
		}
		if(producto == null) {
			logger.info("Intento de acceso a un producto no disponible para el usuario");
			//TODO redireccionar a pagina de error
			//VIEW : pagina de error por defecto para accesos a productos no disponibles
		}
		String ici = busqueda.getIciEncontrado();
		String idioma = CommonUtils.getIdioma(request);

		if (CommonUtils.isValidICI(ici, false)) {
			try {
				String service = url + "comp/identificacion/" + idioma + "/" + ici;
				IdentificacionBean identificacion = restTemplate.getForObject(service, IdentificacionBean.class);
				service = url + "ficha_empresa/"+ici;
				PersonaJuridicaBean fichaEmpresa = restTemplate.getForObject(service, PersonaJuridicaBean.class);

				boolean data = false;
				if (identificacion != null) {
					model.addObject("identificacion", identificacion);
					data = true;
				}

				if (fichaEmpresa!=null) {
					List<String> cabecera=new ArrayList<String>();
			        cabecera=CommonUtils.getListaFechas(CANT_MESES_DEFECTO);
			        int[] totales={0,0,0,0,0,0};
			        for (ConsumoSectorBean consumoSector:fichaEmpresa.getConsumoSector()){
			            for (int j=0;j<consumoSector.getConsumosMeses().length;j++){
			                totales[j]=totales[j]+consumoSector.getConsumosMeses()[j];
			            }
			        }
			        model.addObject("empresa",fichaEmpresa);
			        model.addObject("cabecera",cabecera);
			        model.addObject("totales",totales);
					data = true;
				}

				if (data) {
					page = "empresas/componentes/identificacion";
				} else {
					page = "layout_templates/vacio";
				}

			} catch (RestClientException e) {
				logger.error("Comunicacion con el Rest: " + e.getMessage(), e);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		} else {
			logger.info("ICI(" + ici + ") recibido con formato invalido.");
		}

		if (CommonUtils.isModular(request)) {
            view = "empresas/modulo";
		} else {
			view = page;
		}

		model.addObject(Constants.MODEL_PRODUCTO, producto);
		model.addObject(Constants.MODEL_BUSQUEDA, busqueda);
		model.addObject(Constants.MODEL_CONTENIDO, page);
		model.addObject(Constants.MODEL_TIME, new Date());
		model.addObject(Constants.REQUEST_TIPO, type);
		model.setViewName(view);
		return model;
	}
}


text:
package com.percolate.sdk.android.dto;

import android.os.Parcel;
import android.os.Parcelable;
import com.percolate.sdk.dto.InstagramUserData;

import java.util.HashMap;

/**
 * Android version of {@link com.percolate.sdk.dto.InstagramUser}.  Implements {@link Parcelable}
 */
public class InstagramUser extends com.percolate.sdk.dto.InstagramUser implements Parcelable {
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeSerializable(this.meta);
        dest.writeSerializable(this.data);
        dest.writeMap(this.extraFields);
    }

    public InstagramUser() {
    }

    protected InstagramUser(Parcel in) {
        this.meta = (com.percolate.sdk.dto.InstagramRequestMetaData) in.readSerializable();
        this.data = (InstagramUserData) in.readSerializable();
        this.extraFields = new HashMap<>();
        in.readMap(this.extraFields, HashMap.class.getClassLoader());
    }

    public static final Creator<InstagramUser> CREATOR = new Creator<InstagramUser>() {
        public InstagramUser createFromParcel(Parcel source) {
            return new InstagramUser(source);
        }

        public InstagramUser[] newArray(int size) {
            return new InstagramUser[size];
        }
    };
}


text:
package org.drools.workbench.models.commons.backend.rule.classes;

public class RuleFactor {

    private String name;

    private int defaultPriority;

    private int defaultWeightage;

    private int priorityImpact;

    private int weightageImpact;

    public String getName() {
        return name;
    }

    public void setName( String name ) {
        this.name = name;
    }

    public int getDefaultPriority() {
        return defaultPriority;
    }

    public void setDefaultPriority( int defaultPriority ) {
        this.defaultPriority = defaultPriority;
    }

    public int getDefaultWeightage() {
        return defaultWeightage;
    }

    public void setDefaultWeightage( int defaultWeightage ) {
        this.defaultWeightage = defaultWeightage;
    }

    public int getPriorityImpact() {
        return priorityImpact;
    }

    public void setPriorityImpact( int priorityImpact ) {
        this.priorityImpact = priorityImpact;
    }

    public int getWeightageImpact() {
        return weightageImpact;
    }

    public void setWeightageImpact( int weightageImpact ) {
        this.weightageImpact = weightageImpact;
    }
}


text:
package burai.app.project.viewer.modeler.slabmodel;

import burai.atoms.model.Cell;

public class SlabModelLeaf extends SlabModel {

    private SlabModelStem stem;

    public SlabModelLeaf(SlabModelStem stem, double offset) {
        super();

        if (stem == null) {
            throw new IllegalArgumentException("stem is null.");
        }

        this.stem = stem;
        this.offset = offset;
    }

    @Override
    public SlabModel[] getSlabModels() {
        return new SlabModel[] { this };
    }

    @Override
    protected boolean updateCell(Cell cell) {
        return this.stem.updateCell(cell, this);
    }

}


text:
The  Security Model is multilayer, includes:
* Login Authentication
* User verification for SQL Calls
* User settings via Phaidra Statistics Administration
* SSL support
* SSH Tunneling
* LDAP/AD Services
* Spring Services

#Authentication Flow
![](securitymodel.png)

# User Database Table for Login
The application uses a database table to authenticate users (login). User information (username, passwords, etc.) is managed using the Phaidra Statistics Management Application.

![](servercomponents.png)

#Active Users
Only "Active" users can log in into Phaidra Statistics. User Management is performed with the Phaidra Statistics Administration application.

More information regarding User configuration can be found in the Phaidra Statistics Administration documentation.


text:
require 'time_crisis/tzinfo/timezone_definition'

module TimeCrisis::TZInfo
  module Definitions
    module Etc
      module GMT__m__10
        include TimezoneDefinition

        timezone 'Etc/GMT-10' do |tz|
          tz.offset :o0, 36000, 0, :'GMT-10'

        end
      end
    end
  end
end


text:
YUI.add('attribute-events', function(Y) {

    /**
     * The attribute module provides an augmentable Attribute implementation, which
     * adds configurable attributes and attribute change events to the class being
     * augmented. It also provides a State class, which is used internally by Attribute,
     * but can also be used independently to provide a name/property/value data structure to
     * store state.
     *
     * @module attribute
     */

    /**
     * The attribute-events submodule provides augmentable attribute change event support
     * for AttributeCore based implementations.
     *
     * @module attribute
     * @submodule attribute-events
     */
    var EventTarget = Y.EventTarget,

        CHANGE = "Change",
        BROADCAST = "broadcast",
        PUBLISHED = "published";

    /**
     * Provides an augmentable implementation of attribute change events for
     * AttributeCore.
     *
     * @class AttributeEvents
     * @uses EventTarget
     */
    function AttributeEvents() {
        // Perf tweak - avoid creating event literals if not required.
        this._ATTR_E_FACADE = {};
        EventTarget.call(this, {emitFacade:true});
    }

    AttributeEvents._ATTR_CFG = [BROADCAST];

    AttributeEvents.prototype = {

        /**
         * Sets the value of an attribute.
         *
         * @method set
         * @chainable
         *
         * @param {String} name The name of the attribute. If the
         * current value of the attribute is an Object, dot notation can be used
         * to set the value of a property within the object (e.g. set("x.y.z", 5)).
         *
         * @param {Any} value The value to set the attribute to.
         *
         * @param {Object} opts (Optional) Optional event data to be mixed into
         * the event facade passed to subscribers of the attribute's change event. This
         * can be used as a flexible way to identify the source of a call to set, allowing
         * the developer to distinguish between set called internally by the host, vs.
         * set called externally by the application developer.
         *
         * @return {Object} A reference to the host object.
         */
        set : function(name, val, opts) {
            return this._setAttr(name, val, opts);
        },

        /**
         * Allows setting of readOnly/writeOnce attributes. See set for argument details.
         *
         * @method _set
         * @protected
         * @chainable
         *
         * @param {String} name The name of the attribute.
         * @param {Any} val The value to set the attribute to.
         * @param {Object} opts (Optional) Optional event data to be mixed into
         * the event facade passed to subscribers of the attribute's change event.
         * @return {Object} A reference to the host object.
         */
        _set : function(name, val, opts) {
            return this._setAttr(name, val, opts, true);
        },

        /**
         * Sets multiple attribute values.
         *
         * @method setAttrs
         * @param {Object} attrs  An object with attributes name/value pairs.
         * @param {Object} opts  Properties to mix into the event payload. These are shared and mixed into each set
         * @return {Object} A reference to the host object.
         * @chainable
         */
        setAttrs : function(attrs, opts) {
            return this._setAttrs(attrs, opts);
        },

        /**
         * Implementation behind the public setAttrs method, to set multiple attribute values.
         *
         * @method _setAttrs
         * @protected
         * @param {Object} attrs  An object with attributes name/value pairs.
         * @param {Object} opts  Properties to mix into the event payload. These are shared and mixed into each set
         * @return {Object} A reference to the host object.
         * @chainable
         */
        _setAttrs : function(attrs, opts) {
            var attr;
            for (attr in attrs) {
                if ( attrs.hasOwnProperty(attr) ) {
                    this.set(attr, attrs[attr], opts);
                }
            }
            return this;
        },

        /**
         * Utility method to help setup the event payload and fire the attribute change event.
         *
         * @method _fireAttrChange
         * @private
         * @param {String} attrName The name of the attribute
         * @param {String} subAttrName The full path of the property being changed,
         * if this is a sub-attribute value being change. Otherwise null.
         * @param {Any} currVal The current value of the attribute
         * @param {Any} newVal The new value of the attribute
         * @param {Object} opts Any additional event data to mix into the attribute change event's event facade.
         */
        _fireAttrChange : function(attrName, subAttrName, currVal, newVal, opts) {
            var host = this,
                eventName = attrName + CHANGE,
                state = host._state,
                facade,
                broadcast,
                evtCfg;

            if (!state.get(attrName, PUBLISHED)) {

                evtCfg = {
                    queuable:false,
                    defaultTargetOnly: true,
                    defaultFn:host._defAttrChangeFn,
                    silent:true
                };

                broadcast = state.get(attrName, BROADCAST);
                if (broadcast !== undefined) {
                    evtCfg.broadcast = broadcast;
                }

                host.publish(eventName, evtCfg);

                state.add(attrName, PUBLISHED, true);
            }

            facade = (opts) ? Y.merge(opts) : host._ATTR_E_FACADE;

            // Not using the single object signature for fire({type:..., newVal:...}), since
            // we don't want to override type. Changed to the fire(type, {newVal:...}) signature.

            // facade.type = eventName;
            facade.attrName = attrName;
            facade.subAttrName = subAttrName;
            facade.prevVal = currVal;
            facade.newVal = newVal;

            // host.fire(facade);
            host.fire(eventName, facade);
        },

        /**
         * Default function for attribute change events.
         *
         * @private
         * @method _defAttrChangeFn
         * @param {EventFacade} e The event object for attribute change events.
         */
        _defAttrChangeFn : function(e) {
            if (!this._setAttrVal(e.attrName, e.subAttrName, e.prevVal, e.newVal)) {
                // Prevent "after" listeners from being invoked since nothing changed.
                e.stopImmediatePropagation();
            } else {
                e.newVal = this.get(e.attrName);
            }
        }
    };

    // Basic prototype augment - no lazy constructor invocation.
    Y.mix(AttributeEvents, EventTarget, false, null, 1);

    Y.AttributeEvents = AttributeEvents;

}, '@VERSION@' ,{requires:['event-custom']});


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Mood',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date', models.DateField()),
                ('rating', models.IntegerField(default=0, max_length=1)),
                ('remark', models.TextField()),
                ('pubtime', models.DateTimeField(auto_now_add=True)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]