text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cassandra.Data.Linq;
using Cassandra.IntegrationTests.Linq.Structures;
using Cassandra.IntegrationTests.Mapping.Structures;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.Mapping;
using Cassandra.Mapping.Attributes;
using Cassandra.Tests.Mapping.FluentMappings;
using Cassandra.Tests.Mapping.Pocos;
using NUnit.Framework;
#pragma warning disable 618
#pragma warning disable 612

namespace Cassandra.IntegrationTests.Mapping.Tests
{
    [Category("short")]
    public class Attributes : TestGlobals
    {
        ISession _session;
        string _uniqueKsName;
        private const string IgnoredStringAttribute = "ignoredstringattribute";

        [SetUp]
        public void SetupTest()
        {
            _session = TestClusterManager.GetTestCluster(1).Session;
            _uniqueKsName = TestUtils.GetUniqueKeyspaceName();
            _session.CreateKeyspace(_uniqueKsName);
            _session.ChangeKeyspace(_uniqueKsName);
        }

        [TearDown]
        public void TeardownTest()
        {
            TestUtils.TryToDeleteKeyspace(_session, _uniqueKsName);
        }

        private Table<T> GetTable<T>()
        {
            return new Table<T>(_session, new MappingConfiguration());
        }

        private IMapper GetMapper()
        {
            return new Mapper(_session, new MappingConfiguration());
        }

        /// <summary>
        /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore"
        /// </summary>
        [Test]
        public void Attributes_Ignore_TableCreatedWithMappingAttributes()
        {
            var definition = new AttributeBasedTypeDefinition(typeof(PocoWithIgnoredAttributes));
            var table = new Table<PocoWithIgnoredAttributes>(_session, new MappingConfiguration().Define(definition));
            Assert.AreNotEqual(table.Name, table.Name.ToLower());
            table.Create();

            //var mapper = new Mapper(_session, new MappingConfiguration().Define(definition));
            var mapper = new Mapper(_session, new MappingConfiguration());
            PocoWithIgnoredAttributes pocoToUpload = new PocoWithIgnoredAttributes
            {
                SomePartitionKey = Guid.NewGuid().ToString(),
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };
            mapper.Insert(pocoToUpload);
            string cqlSelect = string.Format("SELECT * from \"{0}\" where \"{1}\"='{2}'", table.Name.ToLower(), "somepartitionkey", pocoToUpload.SomePartitionKey);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithIgnoredAttributes> records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey);
            PocoWithIgnoredAttributes defaultPoco = new PocoWithIgnoredAttributes();
            Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute(cqlSelect).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey"));
            Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble"));

            // Verify there was no column created for the ignored column
            var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute));
            string expectedErrMsg = "Column " + IgnoredStringAttribute + " not found";
            Assert.AreEqual(expectedErrMsg, e.Message);
        }
        /// <summary>
        /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore"
        /// </summary>
        [Test]
        public void Attributes_Ignore()
        {
            var table = GetTable<PocoWithIgnoredAttributes>();
            Assert.AreNotEqual(table.Name, table.Name.ToLower());
            table.Create();

            var mapper = GetMapper();
            PocoWithIgnoredAttributes pocoToUpload = new PocoWithIgnoredAttributes
            {
                SomePartitionKey = Guid.NewGuid().ToString(),
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };
            mapper.Insert(pocoToUpload);
            string cqlSelect = string.Format("SELECT * from \"{0}\" where \"{1}\"='{2}'", table.Name.ToLower(), "somepartitionkey", pocoToUpload.SomePartitionKey);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithIgnoredAttributes> records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey);
            PocoWithIgnoredAttributes defaultPoco = new PocoWithIgnoredAttributes();
            Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute(cqlSelect).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey"));
            Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble"));

            // Verify there was no column created for the ignored column
            var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute));
            string expectedErrMsg = "Column " + IgnoredStringAttribute + " not found";
            Assert.AreEqual(expectedErrMsg, e.Message);
        }

        /// <summary>
        /// Validate that the mapping mechanism ignores the class variable marked as "Ignore"
        /// The fact that the request does not fail trying to find a non-existing custom named column proves that
        /// the request is not looking for the column for reads or writes.
        ///
        /// This also validates that attributes from  Cassandra.Mapping and Cassandra.Data.Lync can be used successfully on the same object
        /// </summary>
        [Test]
        public void Attributes_Ignore_LinqAndMappingAttributes()
        {
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(
                typeof(PocoWithIgnrdAttr_LinqAndMapping),
                () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithIgnrdAttr_LinqAndMapping)));
            var table = new Table<PocoWithIgnrdAttr_LinqAndMapping>(_session, config);
            table.Create();

            var cqlClient = GetMapper();
            PocoWithIgnrdAttr_LinqAndMapping pocoToInsert = new PocoWithIgnrdAttr_LinqAndMapping
            {
                SomePartitionKey = Guid.NewGuid().ToString(),
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };
            cqlClient.Insert(pocoToInsert);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithIgnrdAttr_LinqAndMapping> records = cqlClient.Fetch<PocoWithIgnrdAttr_LinqAndMapping>("SELECT * from " + table.Name).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoToInsert.SomePartitionKey, records[0].SomePartitionKey);
            PocoWithIgnrdAttr_LinqAndMapping defaultPoco = new PocoWithIgnrdAttr_LinqAndMapping();
            Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute("SELECT * from " + table.Name).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoToInsert.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey"));
            Assert.AreEqual(pocoToInsert.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble"));
            Assert.AreEqual(null, rows[0].GetValue<string>(IgnoredStringAttribute));
        }

        /// <summary>
        /// Verify that when trying to insert a Poco with the partition key equal to null, it fails silently
        /// Linq and mapping attributes used in the same class
        /// </summary>
        [Test]
        public void Attributes_PartitionKey_ValueNull()
        {
            var table = GetTable<PocoWithIgnoredAttributes>();
            table.Create();

            var mapper = GetMapper();
            PocoWithIgnoredAttributes pocoWithCustomAttributesLynqAndMappingIncluded = new PocoWithIgnoredAttributes
            {
                SomePartitionKey = null,
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };
            var err = Assert.Throws<InvalidQueryException>(() => mapper.Insert(pocoWithCustomAttributesLynqAndMappingIncluded));
            Assert.AreEqual("Invalid null value for partition key part somepartitionkey", err.Message);
        }

        /// <summary>
        /// Verify that when trying to insert a Poco with the partition key equal to null, it fails silently
        /// Linq and mapping attributes used in the same class
        /// </summary>
        [Test]
        public void Attributes_PartitionKey_ValueNull_LinqAndMappingAttributes()
        {
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(
                typeof(PocoWithIgnrdAttr_LinqAndMapping),
                () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithIgnrdAttr_LinqAndMapping)));
            var table = new Table<PocoWithIgnrdAttr_LinqAndMapping>(_session, config);
            table.Create();

            var cqlClient = GetMapper();
            PocoWithIgnrdAttr_LinqAndMapping pocoWithCustomAttributesLinqAndMapping = new PocoWithIgnrdAttr_LinqAndMapping
            {
                SomePartitionKey = null,
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };
            var err = Assert.Throws<InvalidQueryException>(() => cqlClient.Insert(pocoWithCustomAttributesLinqAndMapping));
            Assert.AreEqual("Invalid null value for partition key part somepartitionkey", err.Message);
        }

        /// <summary>
        /// Validate that an insert query which includes a Poco that has the wrong field labeled as "PartitionKey" will silently fail.
        /// </summary>
        [Test, TestCassandraVersion(2, 0)]
        public void Attributes_PartitionKey_OnWrongField()
        {
            // Create table using Linq -- includes partition key that is not assigned by the mapping attribute
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(
                typeof(PocoWithWrongFieldLabeledPk),
                () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithWrongFieldLabeledPk)));
            var table = new Table<PocoWithWrongFieldLabeledPk>(_session, config);
            table.Create();

            string cqlSelectAll = "SELECT * from " + table.Name;

            var cqlClient = GetMapper();
            PocoWithWrongFieldLabeledPk pocoWithCustomAttributes = new PocoWithWrongFieldLabeledPk();
            cqlClient.Insert(pocoWithCustomAttributes);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithWrongFieldLabeledPk> records = cqlClient.Fetch<PocoWithWrongFieldLabeledPk>(cqlSelectAll).ToList();
            Assert.AreEqual(1, records.Count); // for this case, the mapper is not picky about what field is marked as "partition key"

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute(cqlSelectAll).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
        }

        /// <summary>
        /// Verify that inserting a mapped object that totally omits the Cassandra.Mapping.Attributes.PartitionKey silently fails.
        /// However, using mapping and a different Poco that has the key, records can be inserted and fetched into the same table
        /// </summary>
        [Test]
        public void Attributes_InsertFailsWhenPartitionKeyAttributeOmitted_FixedWithMapping()
        {
            // Setup
            string tableName = typeof(PocoWithPartitionKeyOmitted).Name.ToLower();
            string selectAllCql = "SELECT * from " + tableName;
            List<string> stringList = new List<string>() { "string1", "string2" };
            string createTableCql = "Create table " + tableName + "(somestring text PRIMARY KEY, somelist list<varchar>, somedouble double)";
            _session.Execute(createTableCql);

            // Instantiate CqlClient with mapping rule that resolves the missing key issue
            var cqlClientWithMappping = new Mapper(_session, new MappingConfiguration().Define(new PocoWithPartitionKeyIncludedMapping()));
            // insert new record
            PocoWithPartitionKeyIncluded pocoWithCustomAttributesKeyIncluded = new PocoWithPartitionKeyIncluded();
            pocoWithCustomAttributesKeyIncluded.SomeList = stringList; // make it not empty
            cqlClientWithMappping.Insert(pocoWithCustomAttributesKeyIncluded);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithPartitionKeyIncluded> records_1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList();
            Assert.AreEqual(1, records_1.Count);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, records_1[0].SomeString);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, records_1[0].SomeList);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, records_1[0].SomeDouble);
            records_1.Clear();

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute(selectAllCql).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, rows[0].GetValue<string>("somestring"));
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, rows[0].GetValue<List<string>>("somelist"));
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, rows[0].GetValue<double>("somedouble"));

            // try to Select new record using poco that does not contain partition key, validate that the mapping mechanism matches what it can
            var cqlClientNomapping = GetMapper();
            List<PocoWithPartitionKeyOmitted> records_2 = cqlClientNomapping.Fetch<PocoWithPartitionKeyOmitted>(selectAllCql).ToList();
            Assert.AreEqual(1, records_2.Count);
            records_2.Clear();

            // try again with the old CqlClient instance
            records_1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList();
            Assert.AreEqual(1, records_1.Count);

            // Clear out the table, verify
            string truncateCql = "TRUNCATE " + tableName;
            _session.Execute(truncateCql);
            records_1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList();
            Assert.AreEqual(0, records_1.Count); // should have gone from 1 to 0 records
        }

        /// <summary>
        /// Verify that we can use a mapped object to insert / query into a table
        /// if we leave out a column that is not the partition key (in this case the list column)
        /// </summary>
        [Test]
        public void Attributes_NonPartitionKeyFieldOmittedFromPocoClass()
        {
            string tableName = typeof(PocoWithPartitionKeyIncluded).Name.ToLower();
            string selectAllCql = "SELECT * from " + tableName;
            string createTableCql = "Create table " + tableName + "(somestring text PRIMARY KEY, somelist list<text>, somelist2 list<text>, somedouble double)";
            _session.Execute(createTableCql);
            var cqlClient = GetMapper();

            // insert new record
            PocoWithPartitionKeyIncluded pocoWithCustomAttributesKeyIncluded = new PocoWithPartitionKeyIncluded();
            cqlClient.Insert(pocoWithCustomAttributesKeyIncluded);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithPartitionKeyIncluded> records = cqlClient.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, records[0].SomeString);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, records[0].SomeDouble);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute(selectAllCql).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, rows[0].GetValue<string>("somestring"));
            Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, rows[0].GetValue<double>("somedouble"));
        }

        /// <summary>
        /// Verify that inserting a mapped object without specifying Cassandra.Mapping.Attributes.PartitionKey does not fail
        /// This also validates that not all columns need to be included for the Poco insert / fetch to succeed
        /// </summary>
        [Test, TestCassandraVersion(2, 0)]
        public void Attributes_PartitionKeyNotLabeled()
        {
            string tableName = typeof(PocoWithOnlyPartitionKeyNotLabeled).Name.ToLower();
            string createTableCql = "Create table " + tableName + "(somestring text PRIMARY KEY, somelist list<text>, somedouble double)";
            _session.Execute(createTableCql);

            var cqlClient = GetMapper();
            PocoWithOnlyPartitionKeyNotLabeled pocoWithOnlyCustomAttributes = new PocoWithOnlyPartitionKeyNotLabeled();
            cqlClient.Insert(pocoWithOnlyCustomAttributes);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithOnlyPartitionKeyNotLabeled> records = cqlClient.Fetch<PocoWithOnlyPartitionKeyNotLabeled>("SELECT * from " + tableName).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, records[0].SomeString);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute("SELECT * from " + tableName).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, rows[0].GetValue<string>("somestring"));
        }

        /// <summary>
        /// Verify that inserting a mapped object without including PartitionKey succeeds when it is not the only field in the Poco class
        /// </summary>
        [Test, TestCassandraVersion(2, 0)]
        public void Attributes_PartitionKeyNotLabeled_AnotherNonLabelFieldIncluded()
        {
            string tableName = typeof(PocoWithPartitionKeyNotLabeledAndOtherField).Name.ToLower();
            string createTableCql = "Create table " + tableName + "(somestring text PRIMARY KEY, someotherstring text, somelist list<text>, somedouble double)";
            _session.Execute(createTableCql);

            var cqlClient = GetMapper();
            PocoWithPartitionKeyNotLabeledAndOtherField pocoWithOnlyCustomAttributes = new PocoWithPartitionKeyNotLabeledAndOtherField();
            cqlClient.Insert(pocoWithOnlyCustomAttributes);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithPartitionKeyNotLabeledAndOtherField> records = cqlClient.Fetch<PocoWithPartitionKeyNotLabeledAndOtherField>("SELECT * from " + tableName).ToList();
            Assert.AreEqual(1, records.Count);
        }

        /// <summary>
        /// Verify that inserting a mapped object, mislabeling the PartitionKey as a Clustering Key does not fail
        /// </summary>
        [Test]
        public void Attributes_MislabledClusteringKey()
        {
            string tableName = typeof(PocoMislabeledClusteringKey).Name.ToLower();
            string createTableCql = "Create table " + tableName + "(somestring varchar PRIMARY KEY)";
            _session.Execute(createTableCql);

            var cqlClient = GetMapper();
            PocoMislabeledClusteringKey pocoWithCustomAttributes = new PocoMislabeledClusteringKey();
            cqlClient.Insert(pocoWithCustomAttributes); // TODO: Should this fail?

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoMislabeledClusteringKey> records = cqlClient.Fetch<PocoMislabeledClusteringKey>("SELECT * from " + tableName).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoWithCustomAttributes.SomeString, records[0].SomeString);

        }

        /// <summary>
        /// Successfully insert Poco object which have values that are part of a composite key
        /// </summary>
        [Test]
        public void Attributes_CompositeKey()
        {
            var definition = new AttributeBasedTypeDefinition(typeof(PocoWithCompositeKey));
            var table = new Table<PocoWithCompositeKey>(_session, new MappingConfiguration().Define(definition));
            table.Create();

            List<Guid> listOfGuids = new List<Guid>() { new Guid(), new Guid() };

            var mapper = new Mapper(_session, new MappingConfiguration().Define(definition));
            PocoWithCompositeKey pocoWithCustomAttributes = new PocoWithCompositeKey
            {
                ListOfGuids = listOfGuids,
                SomePartitionKey1 = Guid.NewGuid().ToString(),
                SomePartitionKey2 = Guid.NewGuid().ToString(),
                IgnoredString = Guid.NewGuid().ToString(),
            };

            mapper.Insert(pocoWithCustomAttributes);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithCompositeKey> records = mapper.Fetch<PocoWithCompositeKey>("SELECT * from " + table.Name).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2);
            Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, records[0].ListOfGuids);
            Assert.AreEqual(new PocoWithCompositeKey().IgnoredString, records[0].IgnoredString);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute("SELECT * from " + table.Name).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1"));
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2"));
            Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, rows[0].GetValue<List<Guid>>("listofguids"));
            var ex = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>("ignoredstring"));
            Assert.AreEqual("Column ignoredstring not found", ex.Message);
        }

        /// <summary>
        /// Attempt to insert Poco object which leaves part of the composite key null.
        /// Expect the CqlClient to fail silently
        /// </summary>
        [Test]
        public void Attributes_CompositeKey_FirstPartOfKeyNull()
        {
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PocoWithCompositeKey), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithCompositeKey)));
            var table = new Table<PocoWithCompositeKey>(_session, config);
            table.Create();
            List<Guid> listOfGuids = new List<Guid>() { new Guid(), new Guid() };

            var cqlClient = GetMapper();
            PocoWithCompositeKey pocoWithCustomAttributes = new PocoWithCompositeKey
            {
                ListOfGuids = listOfGuids,
                SomePartitionKey1 = Guid.NewGuid().ToString(),
                SomePartitionKey2 = null,
                IgnoredString = Guid.NewGuid().ToString(),
            };
            var err = Assert.Throws<InvalidQueryException>(() => cqlClient.Insert(pocoWithCustomAttributes));
            Assert.AreEqual("Invalid null value for partition key part somepartitionkey2", err.Message);
        }

        /// <summary>
        /// Attempt to insert Poco object which leaves all values equal to null.
        /// Expect the CqlClient to fail silently
        /// </summary>
        [Test]
        public void Attributes_CompositeKey_AllFieldsNull()
        {
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PocoWithCompositeKey), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithCompositeKey)));
            var table = new Table<PocoWithCompositeKey>(_session, config);
            table.Create();
            var cqlClient = GetMapper();
            PocoWithCompositeKey pocoWithCustomAttributes = new PocoWithCompositeKey
            {
                ListOfGuids = null,
                SomePartitionKey1 = null,
                SomePartitionKey2 = null,
                IgnoredString = null,
            };

            var err = Assert.Throws<InvalidQueryException>(() => cqlClient.Insert(pocoWithCustomAttributes));
            Assert.AreEqual("Invalid null value for partition key part somepartitionkey1", err.Message);
        }

        /// <summary>
        /// Successfully insert Poco object which have values that are part of a composite key
        /// </summary>
        [Test]
        public void Attributes_MultipleClusteringKeys()
        {
            MappingConfiguration config = new MappingConfiguration();
            config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PocoWithClusteringKeys), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithClusteringKeys)));
            var table = new Table<PocoWithClusteringKeys>(_session, config);
            table.Create();

            var cqlClient = new Mapper(_session, config);
;
            PocoWithClusteringKeys pocoWithCustomAttributes = new PocoWithClusteringKeys
            {
                SomePartitionKey1 = Guid.NewGuid().ToString(),
                SomePartitionKey2 = Guid.NewGuid().ToString(),
                Guid1 = Guid.NewGuid(),
                Guid2 = Guid.NewGuid(),
            };

            cqlClient.Insert(pocoWithCustomAttributes);

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            List<PocoWithClusteringKeys> records = cqlClient.Fetch<PocoWithClusteringKeys>("SELECT * from " + table.Name).ToList();
            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2);
            Assert.AreEqual(pocoWithCustomAttributes.Guid1, records[0].Guid1);
            Assert.AreEqual(pocoWithCustomAttributes.Guid2, records[0].Guid2);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            List<Row> rows = _session.Execute("SELECT * from " + table.Name).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1"));
            Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2"));
            Assert.AreEqual(pocoWithCustomAttributes.Guid1, rows[0].GetValue<Guid>("guid1"));
            Assert.AreEqual(pocoWithCustomAttributes.Guid2, rows[0].GetValue<Guid>("guid2"));
        }

        /// <summary>
        /// Expect a "missing partition key" failure upon create since there was no field specific to the class being created
        /// that was marked as partition key.
        /// This happens despite the matching partition key names since they reside in different classes.
        /// </summary>
        [Test]
        public void Attributes_Mapping_MisMatchedClassTypesButTheSamePartitionKeyName()
        {
            var mapping = new Map<SimplePocoWithPartitionKey>();
            mapping.CaseSensitive();
            mapping.PartitionKey(u => u.StringType);
            var table = new Table<ManyDataTypesPoco>(_session, new MappingConfiguration().Define(mapping));

            // Validate expected Exception
            var ex = Assert.Throws<InvalidOperationException>(table.Create);
            StringAssert.Contains("No partition key defined", ex.Message);
        }

        /// <summary>
        /// The Partition key Attribute from the Poco class is used to create a table with a partition key
        /// </summary>
        [Test]
        public void Attributes_PartitionKey()
        {
            var table = GetTable<SimplePocoWithPartitionKey>();
            Assert.AreNotEqual(table.Name, table.Name.ToLower());
            table.Create();

            var cqlClient = GetMapper();
            SimplePocoWithPartitionKey pocoToUpload = new SimplePocoWithPartitionKey();
            cqlClient.Insert(pocoToUpload);
            string cqlSelect = string.Format("SELECT * from \"{0}\" where \"{1}\"='{2}'", table.Name.ToLower(), "stringtype", pocoToUpload.StringType);
            List<SimplePocoWithPartitionKey> instancesQueried = cqlClient.Fetch<SimplePocoWithPartitionKey>(cqlSelect).ToList();
            Assert.AreEqual(1, instancesQueried.Count);
            Assert.AreEqual(pocoToUpload.StringType, instancesQueried[0].StringType);
            Assert.AreEqual(pocoToUpload.StringTyp, instancesQueried[0].StringTyp);
            Assert.AreEqual(pocoToUpload.StringTypeNotPartitionKey, instancesQueried[0].StringTypeNotPartitionKey);
        }

        /// <summary>
        /// Expect the mapping mechanism to recognize / use the Partition key Attribute from
        /// the Poco class it's derived from
        /// </summary>
        [Test, TestCassandraVersion(2, 0)]
        public void Attributes_SecondaryIndex()
        {
            var table = GetTable<SimplePocoWithSecondaryIndex>();
            table.Create();

            var cqlClient = GetMapper();
            int expectedTotalRecords = 10;
            SimplePocoWithSecondaryIndex defaultInstance = new SimplePocoWithSecondaryIndex();
            for (int i = 0; i < expectedTotalRecords; i++)
                cqlClient.Insert(new SimplePocoWithSecondaryIndex(i));
            List<SimplePocoWithSecondaryIndex> instancesQueried = cqlClient.Fetch<SimplePocoWithSecondaryIndex>().ToList();
            Assert.AreEqual(expectedTotalRecords, instancesQueried.Count);

            // Select using basic cql
            string cqlSelect = string.Format("SELECT * from \"{0}\" where {1}={2} order by {3} desc", table.Name.ToLower(), "somesecondaryindex", defaultInstance.SomeSecondaryIndex, "somepartitionkey");
            var ex = Assert.Throws<InvalidQueryException>(() => cqlClient.Fetch<SimplePocoWithSecondaryIndex>(cqlSelect));
            Assert.AreEqual("ORDER BY with 2ndary indexes is not supported.", ex.Message);
        }

        /// <summary>
        /// Expect the mapping mechanism to recognize / use the Column Attribute from
        /// the Poco class it's derived from
        /// </summary>
        [Test]
        public void Attributes_Column_NoCustomLabel()
        {
            // Setup
            int expectedTotalRecords = 1;
            var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnAttribute));
            var table = new Table<SimplePocoWithColumnAttribute>(_session, new MappingConfiguration().Define(definition));
            Assert.AreNotEqual(table.Name, table.Name.ToLower());
            table.Create();

            SimplePocoWithColumnAttribute defaultInstance = new SimplePocoWithColumnAttribute();
            var mapper = new Mapper(_session, new MappingConfiguration().Define(definition));
            mapper.Insert(defaultInstance);

            // Validate using mapped Fetch
            string cqlSelectAll = "select * from " + table.Name.ToLower();
            List<SimplePocoWithColumnAttribute> instancesQueried = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelectAll).ToList();
            Assert.AreEqual(expectedTotalRecords, instancesQueried.Count);

            string cqlSelect = string.Format("SELECT * from \"{0}\" where {1}='{2}'", table.Name.ToLower(), "somepartitionkey", defaultInstance.SomePartitionKey);
            List<SimplePocoWithColumnAttribute> actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelect).ToList();
            Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count);

            // Validate using straight cql to verify column names
            List<Row> rows = _session.Execute(cqlSelect).GetRows().ToList();
            Assert.AreEqual(expectedTotalRecords, rows.Count);
            Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("somecolumn"));
        }

        /// <summary>
        /// Expect the mapping mechanism to recognize / use the Column Attribute from
        /// the Poco class it's derived from, including the custom label option
        /// </summary>
        [Test, TestCassandraVersion(2,0)]
        public void Attributes_Column_CustomLabels()
        {
            // Setup
            int expectedTotalRecords = 1;
            var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnLabel_CustomColumnName));
            var table = new Table<SimplePocoWithColumnLabel_CustomColumnName>(_session, new MappingConfiguration().Define(definition));
            Assert.AreEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, table.Name); // Assert table name is case sensitive now
            Assert.AreNotEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, typeof(SimplePocoWithColumnLabel_CustomColumnName).Name.ToLower()); // Assert table name is case senstive
            table.Create();

            SimplePocoWithColumnLabel_CustomColumnName defaultInstance = new SimplePocoWithColumnLabel_CustomColumnName();
            var mapper = new Mapper(_session, new MappingConfiguration().Define(definition));
            mapper.Insert(defaultInstance);

            // Validate using mapped Fetch
            string cqlSelect = string.Format("SELECT * from \"{0}\" where {1}='{2}'", table.Name.ToLower(), "someCaseSensitivePartitionKey", defaultInstance.SomePartitionKey);
            List<SimplePocoWithColumnLabel_CustomColumnName> actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnLabel_CustomColumnName>(cqlSelect).ToList();
            Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count);
            Assert.AreEqual(defaultInstance.SomeColumn, actualObjectsInOrder[0].SomeColumn);

            // Validate using straight cql to verify column names
            List<Row> rows = _session.Execute(cqlSelect).GetRows().ToList();
            Assert.AreEqual(expectedTotalRecords, rows.Count);
            Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("some_column_label_thats_different"));
        }

        /////////////////////////////////////////
        /// Private test classes
        /////////////////////////////////////////

        [Cassandra.Mapping.Attributes.Table("SimplePocoWithColumnLabel_CustomColumnName")]
        public class SimplePocoWithColumnLabel_CustomColumnName
        {
            [Cassandra.Mapping.Attributes.Column("someCaseSensitivePartitionKey")]
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string SomePartitionKey = "defaultPartitionKeyVal";
            [Cassandra.Mapping.Attributes.Column("some_column_label_thats_different")]
            public int SomeColumn = 191991919;
        }

        public class SimplePocoWithColumnAttribute
        {
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string SomePartitionKey = "defaultPartitionKeyVal";
            [Cassandra.Mapping.Attributes.Column]
            public int SomeColumn = 121212121;
        }

        public class SimplePocoWithSecondaryIndex
        {
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string SomePartitionKey;
            [Cassandra.Mapping.Attributes.SecondaryIndex]
            public int SomeSecondaryIndex = 1;

            public SimplePocoWithSecondaryIndex() { }

            public SimplePocoWithSecondaryIndex(int i)
            {
                SomePartitionKey = "partitionKey_" + i;
            }
        }

        private class SimplePocoWithPartitionKey
        {
            public string StringTyp = "someStringValue";
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string StringType = "someStringValue";
            public string StringTypeNotPartitionKey = "someStringValueNotPk";
        }

        private class PocoWithIgnoredAttributes
        {
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string SomePartitionKey = "somePartitionKeyDefaultValue";
            public double SomeNonIgnoredDouble = 123456;
            [Cassandra.Mapping.Attributes.Ignore]
            public string IgnoredStringAttribute = "someIgnoredString";
        }

        /// <summary>
        /// Test poco class that uses both Linq and Cassandra.Mapping attributes at the same time
        /// </summary>
        [Cassandra.Data.Linq.Table("pocowithignrdattr_linqandmapping")]
        private class PocoWithIgnrdAttr_LinqAndMapping
        {
            [Cassandra.Data.Linq.PartitionKey]
            [Cassandra.Mapping.Attributes.PartitionKey]
            [Cassandra.Data.Linq.Column("somepartitionkey")]
            public string SomePartitionKey = "somePartitionKeyDefaultValue";

            [Cassandra.Data.Linq.Column("somenonignoreddouble")]
            public double SomeNonIgnoredDouble = 123456;

            [Cassandra.Mapping.Attributes.Ignore]
            [Cassandra.Data.Linq.Column(Attributes.IgnoredStringAttribute)]
            public string IgnoredStringAttribute = "someIgnoredString";
        }

        /// <summary>
        /// See PocoWithIgnoredAttributes for correctly implemented counterpart
        /// </summary>
        [Cassandra.Data.Linq.Table("pocowithwrongfieldlabeledpk")]
        private class PocoWithWrongFieldLabeledPk
        {
            [Cassandra.Data.Linq.PartitionKey]
            [Cassandra.Data.Linq.Column("somepartitionkey")]
            public string SomePartitionKey = "somePartitionKeyDefaultValue";

            [Cassandra.Data.Linq.Column("somenonignoreddouble")]
            public double SomeNonIgnoredDouble = 123456;

            [Cassandra.Mapping.Attributes.PartitionKey]
            [Cassandra.Data.Linq.Column("someotherstring")]
            public string SomeOtherString = "someOtherString";
        }

        /// <summary>
        /// Class with Mapping.Attributes.Partition key ommitted
        /// </summary>
        private class PocoWithOnlyPartitionKeyNotLabeled
        {
            public string SomeString = "somestring_value";
        }

        /// <summary>
        /// Class with Mapping.Attributes.Partition key ommitted, as well as another field that is not labeled
        /// </summary>
        private class PocoWithPartitionKeyNotLabeledAndOtherField
        {
            public string SomeString = "somestring_value";
            public string SomeOtherString = "someotherstring_value";
        }

        /// <summary>
        /// Class with Mapping.Attributes.Partition key ommitted
        /// </summary>
        private class PocoMislabeledClusteringKey
        {
            [Cassandra.Mapping.Attributes.ClusteringKey]
            public string SomeString = "someStringValue";
        }

        /// <summary>
        /// Class with Mapping.Attributes.Partition key ommitted
        /// </summary>
        private class PocoWithPartitionKeyOmitted
        {
            public double SomeDouble = (double)123456;
            public List<string> SomeList = new List<string>();
        }

        /// <summary>
        /// Class with Mapping.Attributes.Partition key included, which was missing from PocoWithPartitionKeyOmitted
        /// </summary>
        private class PocoWithPartitionKeyIncluded
        {
            [Cassandra.Mapping.Attributes.PartitionKey]
            public string SomeString = "somePartitionKeyDefaultValue";
            public double SomeDouble = (double)123456;
            public List<string> SomeList = new List<string>();
        }

        /// <summary>
        /// Class designed to fix the issue with PocoWithPartitionKeyOmitted, which is implied by the name
        /// </summary>
        class PocoWithPartitionKeyIncludedMapping : Map<PocoWithPartitionKeyIncluded>
        {
            public PocoWithPartitionKeyIncludedMapping()
            {
                TableName(typeof(PocoWithPartitionKeyOmitted).Name.ToLower());
                PartitionKey(u => u.SomeString);
                Column(u => u.SomeString, cm => cm.WithName("somestring"));
            }
        }

        [Cassandra.Data.Linq.Table("pocowithcompositekey")]
        private class PocoWithCompositeKey
        {
            [Cassandra.Data.Linq.PartitionKey(1)]
            [Cassandra.Mapping.Attributes.PartitionKey(1)]
            [Cassandra.Data.Linq.Column("somepartitionkey1")]
            public string SomePartitionKey1 = "somepartitionkey1_val";

            [Cassandra.Data.Linq.PartitionKey(2)]
            [Cassandra.Mapping.Attributes.PartitionKey(2)]
            [Cassandra.Data.Linq.Column("somepartitionkey2")]
            public string SomePartitionKey2 = "somepartitionkey2_val";

            [Cassandra.Data.Linq.Column("listofguids")]
            public List<Guid> ListOfGuids;

            [Cassandra.Mapping.Attributes.Ignore]
            [Cassandra.Data.Linq.Column("ignoredstring")]
            public string IgnoredString = "someIgnoredString_val";
        }

        [Cassandra.Data.Linq.Table("pocowithclusteringkeys")]
        private class PocoWithClusteringKeys
        {
            [Cassandra.Data.Linq.PartitionKey(1)]
            [Cassandra.Mapping.Attributes.PartitionKey(1)]
            [Cassandra.Data.Linq.Column("somepartitionkey1")]
            public string SomePartitionKey1 = "somepartitionkey1_val";

            [Cassandra.Data.Linq.PartitionKey(2)]
            [Cassandra.Mapping.Attributes.PartitionKey(2)]
            [Cassandra.Data.Linq.Column("somepartitionkey2")]
            public string SomePartitionKey2 = "somepartitionkey2_val";

            [Cassandra.Data.Linq.ClusteringKey(1)]
            [Cassandra.Mapping.Attributes.ClusteringKey(1)]
            [Cassandra.Data.Linq.Column("guid1")]
            public Guid Guid1;

            [Cassandra.Data.Linq.ClusteringKey(2)]
            [Cassandra.Mapping.Attributes.ClusteringKey(2)]
            [Cassandra.Data.Linq.Column("guid2")]
            public Guid Guid2;

        }

        public object pocoToUpload { get; set; }
    }
}


text:
layout: nil
---
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Eric Helgeson | Blog</title>
 <link href="http://erichelgeson.github.com/atom.xml" rel="self"/>
 <link href="http://erichelgeson.github.com/"/>
 <updated>{{ site.time | date_to_xmlschema }}</updated>
 <id>http://erichelgeson.github.com/</id>
 <author>
   <name>Eric Helgeson</name>
   <email>erichelgeson@gmail.com</email>
 </author>

 {% for post in site.posts %}
 <entry>
   <title>{{ post.title }}</title>
   <link href="http://erichelgeson.github.com{{ post.url }}"/>
   <updated>{{ post.date | date_to_xmlschema }}</updated>
   <id>http://erichelgeson.github.com{{ post.id }}</id>
   <content type="html">{{ post.content | xml_escape }}</content>
 </entry>
 {% endfor %}

</feed>

redpajama_set_name: RedPajamaGithub


text:
"use strict";
const definitions = require("../../lib/definitions");

function addIsHelper(type) {
  return `export function is${type}(node: Object, opts?: Object): boolean {
    return is("${type}", node, opts) }
  `;
}

module.exports = function generateValidators() {
  let output = `// @flow
/*
 * This file is auto-generated! Do not modify it directly.
 * To re-generate run 'make build'
 */
import is from "../is";\n\n`;

  Object.keys(definitions.VISITOR_KEYS).forEach(type => {
    output += addIsHelper(type);
  });

  Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
    output += addIsHelper(type);
  });

  Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
    const newType = definitions.DEPRECATED_KEYS[type];
    output += `export function is${type}(node: Object, opts: Object): boolean {
  console.trace("The node type ${type} has been renamed to ${newType}");
  return is("${type}", node, opts);
}\n`;
  });

  return output;
};


text:
Setting up the container
===================

Currently, we support [WildFly](http://www.wildfly.org) 8.2.0 Final as container only.
JavaEE portability is a difficult terrain, and we do not have the resources to manoeuvre around this.
We're sorry for the inconvenience.

Quick start
-----------

Not all of the information in this file is necessary to get started with ATLAS.
At the bare minimum, you need to take the following steps:

* Download WildFly
* [Download and integrate ModeShape](#download-and-integrate-modeshape)
* Use the supplied [example WildFly configuration](#using-the-example-wildfly-configuration)
* Add the [messaging user](#set-up-a-user-for-messaging)
* [Deploy ATLAS](#deploying-the-application)

Download and extract WildFly
----------------------------

Download [WildFly 8.2.0.Final](http://www.wildfly.org/downloads/) and extract the archive to a folder on your disk.

Using the example WildFly configuration
---------------------------------------

To shorten startup times we've included a set of configuration files in this repository.
It includes the data storage and messaging configuration detailed in the rest of this document.

Copy the contents of the `example-configuration` directory to your WildFly `standalone/configuration/` directory.
You may need to overwrite the existing file there.

If you need to run something else apart from ATLAS on your WildFly, you probably need to configure some other things.
The detailed changes necessary can be found in the rest of this document.

Adding users to WildFly
-----------------------

### Set up a management user

In order to manage the server via the web interface, add a new user via the wildfly CLI, as follows.
Execute the `add-user` script from the `bin` folder, and feed it the following answers:

* __Type:__ Management user
* __Name:__ (the username you want to use for the web admin panel)
* __Password:__ (some safe password)
* __Groups:__ (leave empty)
* __Used to connect to another process:__ no

### Set up a user for Messaging

ATLAS' import worker connects to the container through HornetQ's STOMP interface.
Since this requires authentication, you need to add another user using the `add-user` script:

* __Type:__ Application user
* __Name:__ (the username you want to use for STOMP)
* __Password:__ (some safe password)
* __Groups:__ guest

Note: if you are going to use COMPASS along with ATLAS, you might want to use the stomp user created for COMPASS for ATLAS as well.

Install modeshape
-------------------

To store asset data, ATLAS uses the JCR (Java Content Repository) interface.
The JCR implementation for WildFly is called ModeShape, which is what we are going to install and configure here.

Detailed instructions for [installation](https://docs.jboss.org/author/display/MODE40/Installing+ModeShape+into+Wildfly) and [configuration](https://docs.jboss.org/author/display/MODE40/Configuring+ModeShape+in+Wildfly) can be found on the ModeShape site.
However, we will summarize the essentials here.

### Download and integrate ModeShape

Download the [ModeShape subsystem for Wildfly 8.0 - Version 4.1.0.Final](http://modeshape.jboss.org/downloads/downloads4-1-0-final.html).
Unzip the archive, it should contain `docs`, `domain`, `modules` and `standalone` directories.
Copy these directories into the root of your Wildfly installation.
This should add the files of ModeShape into the already existing directories of WildFly.
No overwriting of files should be necessary.

### Add modeshape user configuration

In the `standalone/configuration` folder, add a file `modeshape-roles.properties`, containing the following user role properties:

	#<userName>=[readonly[.<workspaceName>] | readwrite[.<workspaceName>]][, [readonly[.<workspaceName>] | readwrite[.<workspaceName>]]]*
	admin=admin,connect,readonly,readwrite
	guest=connect,readonly

Analogously, create `modeshape-users.properties`, containing

	# A users.properties file for use with the UsersRolesLoginModule
	# username=password
	admin=admin
	guest=guest

### Configure cache containers

Add the necessary *cache containers* for atlas in the infinispan subsystem defined in the `standalone.xml`:

	<cache-container name="modeshape" default-cache="data" module="org.modeshape">
		<local-cache name="atlas">
			<locking isolation="READ_COMMITTED"/>
			<transaction mode="NON_XA"/>
			<file-store passivation="false" purge="false" path="modeshape/store/atlas"/>
		</local-cache>
		<local-cache name="artifacts">
			<locking isolation="READ_COMMITTED"/>
			<transaction mode="NON_XA"/>
			<file-store passivation="false" purge="false" path="modeshape/store/artifacts"/>
		</local-cache>
	</cache-container>

### Setting up the security domain

Make sure the *security domain* you added while installing modeshape contains all necessary entries:

	<security-domain name="modeshape-security" cache-type="default">
		<authentication>
			<login-module code="UsersRoles" flag="required">
				<module-option name="usersProperties" value="${jboss.server.config.dir}/modeshape-users.properties"/>
				<module-option name="rolesProperties" value="${jboss.server.config.dir}/modeshape-roles.properties"/>
			</login-module>
		</authentication>
	</security-domain>

### Configure subsystem

Finally, the ModeShape subsystem needs to have (at least) these things configured:

* an `atlas` workspace
* access for the `admin` role to said workspace
* the bundled REST application needs to be enabled for the worker to function

This can be achieved using the following snippet:

    <subsystem xmlns="urn:jboss:domain:modeshape:2.0">
        <repository name="atlas" anonymous-roles="admin">
            <workspaces allow-workspace-creation="false">
                <workspace name="default"/>
            </workspaces>
        </repository>
        <webapp name="modeshape-rest.war"/>
    </subsystem>

### Setting the maximum upload size

Since assets to be imported can be relatively large, it may be necessary to increase the maximum POST request size.
This can be achieved by adding a `max-post-size` attribute to WildFly's http listener configuration tag, which is in the `urn:jboss:domain:undertow:1.2` subsystem.
For example, a maximum upload size of around 4.2 GB might look like this:

    <http-listener name="default" socket-binding="http" max-post-size="4515430400"/>

Messaging configuration
------------------------------

The messaging service makes use of the jboss messaging submodule. If you haven't configured this module yet, e.g. when setting up another project, do this as a first step before adding the ATLAS jms destinations.

### Setting up the messaging submodule

Most of the configuration can be found in WildFly's `standalone-full.xml` example file, here we'll highlight the core elements necessary to allow ATLAS to communicate with the worker.

Add the module for the messaging service to the list of extension modules:

	<extension module="org.jboss.as.messaging"/>

Add the Message-Driven Bean (MDB) resource adapter to the ejb subsystem:

	<mdb>
		<resource-adapter-ref resource-adapter-name="${ejb.resource-adapter-name:hornetq-ra.rar}"/>
		<bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>
	</mdb>

Finally, add a new subsystem for HornetQ using the following settings (note the `<connector>` and `<acceptor>` tags for STOMP, the rest is pretty much copied and pasted from `standalone-full.xml`):

	<subsystem xmlns="urn:jboss:domain:messaging:2.0">
		<hornetq-server>
			<journal-file-size>102400</journal-file-size>
			<connectors>
				<http-connector name="http-connector" socket-binding="http">
					<param key="http-upgrade-endpoint" value="http-acceptor"/>
				</http-connector>
				<http-connector name="http-connector-throughput" socket-binding="http">
					<param key="http-upgrade-endpoint" value="http-acceptor-throughput"/>
					<param key="batch-delay" value="50"/>
				</http-connector>
				<in-vm-connector name="in-vm" server-id="0"/>
				<connector name="netty-connector">
					<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
				</connector>
			</connectors>
			<acceptors>
				<http-acceptor http-listener="default" name="http-acceptor"/>
				<http-acceptor http-listener="default" name="http-acceptor-throughput">
					<param key="batch-delay" value="50"/>
					<param key="direct-deliver" value="false"/>
				</http-acceptor>
				<in-vm-acceptor name="in-vm" server-id="0"/>
				<acceptor name="stomp-websocket">
					<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
					<param key="host" value="0.0.0.0"/>
					<param key="port" value="61614"/>
				</acceptor>
				<acceptor name="stomp">
					<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
					<param key="host" value="0.0.0.0"/>
					<param key="port" value="61613"/>
				</acceptor>
			</acceptors>
			<security-settings>
				<security-setting match="#">
					<permission type="send" roles="guest"/>
					<permission type="consume" roles="guest"/>
					<permission type="createNonDurableQueue" roles="guest"/>
					<permission type="deleteNonDurableQueue" roles="guest"/>
				</security-setting>
			</security-settings>
			<address-settings>
				<address-setting match="#">
					<dead-letter-address>jms.queue.DLQ</dead-letter-address>
					<expiry-address>jms.queue.ExpiryQueue</expiry-address>
					<max-size-bytes>10485760</max-size-bytes>
					<page-size-bytes>2097152</page-size-bytes>
					<message-counter-history-day-limit>10</message-counter-history-day-limit>
				</address-setting>
			</address-settings>
			<jms-connection-factories>
				<connection-factory name="InVmConnectionFactory">
					<connectors>
						<connector-ref connector-name="in-vm"/>
					</connectors>
					<entries>
						<entry name="java:/ConnectionFactory"/>
					</entries>
				</connection-factory>
				<connection-factory name="RemoteConnectionFactory">
					<connectors>
						<connector-ref connector-name="http-connector"/>
					</connectors>
					<entries>
						<entry name="java:jboss/exported/jms/RemoteConnectionFactory"/>
					</entries>
				</connection-factory>
				<pooled-connection-factory name="hornetq-ra">
					<transaction mode="xa"/>
					<connectors>
						<connector-ref connector-name="in-vm"/>
					</connectors>
					<entries>
						<entry name="java:/JmsXA"/>
						<entry name="java:jboss/DefaultJMSConnectionFactory"/>
					</entries>
				</pooled-connection-factory>
			</jms-connection-factories>
			<jms-destinations>
				<jms-queue name="ExpiryQueue">
					<entry name="java:/jms/queue/ExpiryQueue"/>
				</jms-queue>
				<jms-queue name="DLQ">
					<entry name="java:/jms/queue/DLQ"/>
				</jms-queue>
			</jms-destinations>
		</hornetq-server>
	</subsystem>

### Add ATLAS jms queues

Add the ATLAS jms destinations to the JMS destinations of the HornetQ messaging subsystems `<jms-destinations>` tag defined (as per the example above) in `standalone.xml`:

	<jms-queue name="atlas.work.import">
		<entry name="queue/atlas/work/import"/>
		<entry name="/queue/atlas.work.import"/>
		<entry name="java:/jms/queue/atlas/work/import"/>
	</jms-queue>
	<jms-queue name="atlas.work.feedback">
		<entry name="queue/atlas/work/feedback"/>
		<entry name="/queue/atlas.work.feedback"/>
		<entry name="java:/jms/queue/atlas/work/feedback"/>
	</jms-queue>

Increasing the memory limit
-----------------------------

To increase the amount of memory available for ATLAS, open the configuration file `bin/standalone.conf` (or `bin/standalone.conf.bat` on Windows systems) located in you WildFly installation's. Go to the the options to be passed to the Java VM.
The memory maximum can be adjusted in the line

	JAVA_OPTS="-Xms64m -Xmx512m -XX:MaxPermSize=256m -Djava.net.preferIPv4Stack=true"

by increasing the `-Xmx`, `-Xms` and `-XX:MaxPermSize` value.

Since ATLAS probably needs to serialise large amounts of binary data to text, which requires a decent amount of memory, you are encouraged to adjust the default values. At any rate, the container log will tell you when you run out of memory.

Deploying the application
-------------------------

Once the container is configured, you can deploy the ATLAS WAR.
After compilation (see the [README file](README.md)), you can find this file in the `target/` directory in your source folder.

To deploy the application, WildFly needs to be running.
Unless it already is, start the `standalone` script in WildFly's `bin` folder.
Once the container is running, it should suffice to copy the EAR archive to the `standalone/deployments/` folder of WildFly.

After allowing the container some time to bring up all the classes and services needed for ATLAS,
it should be available from your container's `atlas/` context.
With the configuration supplied, you can reach this via `http://localhost:8080/atlas/`.


text:
#ifndef MEMQUOTA_H_
#define MEMQUOTA_H_

#include "nodes/plannodes.h"
#include "cdb/cdbplan.h"

typedef enum ResManagerMemoryPolicy
{
	RESMANAGER_MEMORY_POLICY_NONE,
	RESMANAGER_MEMORY_POLICY_AUTO,
	RESMANAGER_MEMORY_POLICY_EAGER_FREE
} ResManagerMemoryPolicy;

extern ResManagerMemoryPolicy gp_resmanager_memory_policy_default;
extern bool						gp_log_resmanager_memory_default;
extern int						gp_resmanager_memory_policy_auto_fixed_mem_default;
extern bool						gp_resmanager_print_operator_memory_limits_default;

extern ResManagerMemoryPolicy	*gp_resmanager_memory_policy;
extern bool						*gp_log_resmanager_memory;
extern int						*gp_resmanager_memory_policy_auto_fixed_mem;
extern bool						*gp_resmanager_print_operator_memory_limits;

#define GP_RESMANAGER_MEMORY_LOG_LEVEL NOTICE

#define IsResManagerMemoryPolicyNone() (*gp_resmanager_memory_policy == RESMANAGER_MEMORY_POLICY_NONE)
#define IsResManagerMemoryPolicyAuto() (*gp_resmanager_memory_policy == RESMANAGER_MEMORY_POLICY_AUTO)
#define IsResManagerMemoryPolicyEagerFree() (*gp_resmanager_memory_policy == RESMANAGER_MEMORY_POLICY_EAGER_FREE)

#define LogResManagerMemory() (*gp_log_resmanager_memory == true)
#define ResManagerPrintOperatorMemoryLimits() (*gp_resmanager_print_operator_memory_limits == true)

extern void PolicyAutoAssignOperatorMemoryKB(PlannedStmt *stmt, uint64 memoryAvailable);
extern void PolicyEagerFreeAssignOperatorMemoryKB(PlannedStmt *stmt, uint64 memoryAvailable);

/**
 * Inverse for explain analyze.
 */
extern uint64 PolicyAutoStatementMemForNoSpillKB(PlannedStmt *stmt, uint64 minOperatorMemKB);

/**
 * Is result node memory intensive?
 */
extern bool IsResultMemoryIntesive(Result *res);

/**
 * Is operator memory intensive
 */
extern bool IsMemoryIntensiveOperator(Node *node, PlannedStmt *stmt);

/*
 * Calculate the amount of memory reserved for the query
 */
extern int64 ResourceManagerGetQueryMemoryLimit(PlannedStmt* stmt);

#endif /* MEMQUOTA_H_ */


text:
module Convolution
	class WaveformLegend
		include Rubygame
		include Sprites::Sprite

		attr_reader :parent
		attr_accessor :font

		def initialize(parent, options = {})
			@parent = parent
			@font = options[:font]
			@labels = options[:labels] || Color[:black]
			@image = Surface.new([@parent.image.width, @parent.image.height], 32, [HWSURFACE])
		end

		def y_labels
			[0, @parent.peak, -@parent.peak]
		end

		def float_s(f)
			((f*100).truncate / 100.0).to_s
		end

		def update
			@image.fill(@parent.background)
			@rect = @parent.rect.dup
			@rect.x -= y_labels.collect { |y| @font.size_text(float_s(y))[0] }.max

			y_labels.each do |y|
				text = @font.render(float_s(y), true, @labels)
				text.blit(@image, [0, @parent.image_y(y) - text.height/2])
			end
		end
	end
end


text:
namespace orwell
{

namespace game
{
class Game;
}

class IServer
{
public:
	virtual ~IServer();

	virtual bool processMessageIfAvailable() = 0;

	/// Wait for 1 message and process it. Execute timed operations if needed.
	virtual void loopUntilOneMessageIsProcessed() = 0;

	/// Loop eternaly to process all incoming messages.
	virtual void loop() = 0;

	/// Correctly stop the server
	virtual void stop() = 0;

	virtual orwell::game::Game & accessContext() = 0;

	virtual void feedAgentProxy(bool const iBlocking) = 0;
};

}


text:
using System;
using Ccr.Std.Core.Extensions;
using JetBrains.Annotations;

namespace Ccr.Std.Introspective.Infrastructure.Context
{
	public class IntrospectiveStaticContext
	  : IntrospectiveContext
	{
		protected internal override Type TargetType { get; }

		protected internal override object TargetObject => null;

		public IntrospectiveStaticContext(
			[NotNull] Type targetType)
		{
			targetType.IsNotNull(nameof(targetType));

			TargetType = targetType;
		}
	}

	public class IntrospectiveStaticContext<TValue>
	  : IntrospectiveStaticContext
	{
		public IntrospectiveStaticContext() : base(
			typeof(TValue))
		{

		}
	}
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0109_v370_job_template_organization_field'),
    ]

    operations = [
        migrations.AddField(
            model_name='instance',
            name='ip_address',
            field=models.CharField(blank=True, default=None, max_length=50, null=True, unique=True),
        ),
    ]


text:
// Copyright (c) 2013 Jonathan Magnan (http://zzzportal.com) All rights reserved. Licensed under MIT License (MIT) License can be found here: https://zextensionmethods.codeplex.com/license

using System.Drawing;

namespace Oragon.Architecture.Extensions
{
	public static partial class OragonExtensions
	{
		#region Public Methods

		/// <id>15F029B4-36FB-49E7-A7DC-EA063AC4C6A3</id>
		/// <summary>
		///     An Image extension method that cuts an image.
		/// </summary>
		/// <param name="this">The @this to act on.</param>
		/// <param name="width">The width.</param>
		/// <param name="height">The height.</param>
		/// <param name="x">The x coordinate.</param>
		/// <param name="y">The y coordinate.</param>
		/// <returns>The cutted image.</returns>
		public static Image Cut(this Image @this, int width, int height, int x, int y)
		{
			var r = new Bitmap(width, height);
			var destinationRectange = new Rectangle(0, 0, width, height);
			var sourceRectangle = new Rectangle(x, y, width, height);

			using (Graphics g = Graphics.FromImage(r))
			{
				g.DrawImage(@this, destinationRectange, sourceRectangle, GraphicsUnit.Pixel);
			}

			return r;
		}

		#endregion Public Methods
	}
}


text:
FROM alpine:3.6

#
# Copy release to container and set command
#

# Add faster mirror and upgrade packages in base image, Erlang needs ncurses, NIF libstdc++
RUN printf "http://mirror.leaseweb.com/alpine/v3.6/main\nhttp://mirror.leaseweb.com/alpine/v3.6/community" > etc/apk/repositories && \
    apk update && \
    apk upgrade && \
    apk add zeromq ca-certificates && \
    rm -rf /var/cache/apk/*

# Do not run as root
USER element43:element43

# Copy build
COPY market-streamer market-streamer

CMD ["/market-streamer"]


text:
package it.unisa.dia.gas.crypto.jpbc.fe.ip.lostw10.generators;

import it.unisa.dia.gas.crypto.jpbc.fe.ip.lostw10.params.IPLOSTW10Parameters;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;

/**
 * @author Angelo De Caro (jpbclib@gmail.com)
 */
public class IPLOSTW10ParametersGenerator {
    private PairingParameters parameters;
    private int n;

    private Pairing pairing;

    public IPLOSTW10ParametersGenerator init(PairingParameters parameters, int n) {
        this.parameters = parameters;
        this.n = n;
        this.pairing = PairingFactory.getPairing(this.parameters);

        return this;
    }

    public IPLOSTW10Parameters generateParameters() {
        Element g = pairing.getG1().newElement().setToRandom();

        return new IPLOSTW10Parameters(parameters, g.getImmutable(), n);
    }

}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression;

import com.yahoo.searchlib.rankingexpression.rule.Arguments;
import com.yahoo.searchlib.rankingexpression.rule.NameNode;
import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author bratseth
 */
public class ReferenceTestCase {

    @Test
    public void testSimple() {
        assertTrue(new Reference("foo", new Arguments(new ReferenceNode("arg")), null).isSimple());
        assertTrue(new Reference("foo", new Arguments(new ReferenceNode("arg")), "out").isSimple());
        assertTrue(new Reference("foo", new Arguments(new NameNode("arg")), "out").isSimple());
        assertFalse(new Reference("foo", new Arguments(), null).isSimple());
    }

    @Test
    public void testToString() {
        assertEquals("foo(arg_1)", new Reference("foo", new Arguments(new ReferenceNode("arg_1")), null).toString());
        assertEquals("foo(arg_1).out", new Reference("foo", new Arguments(new ReferenceNode("arg_1")), "out").toString());
        assertEquals("foo(arg_1).out", new Reference("foo", new Arguments(new NameNode("arg_1")), "out").toString());
        assertEquals("foo", new Reference("foo", new Arguments(), null).toString());
    }

}


text:
class WelcomeController < ApplicationController
  def index
	@work_orders = WorkOrder.all
	@opportunities = Opportunity.all
  end
end


text:
var button = document.getElementById('handian-btn');
if (button) {
    console.log('handian-btn exist');
    button.style.position = "fixed";
}
var button = document.getElementById('handian-input');
if (button) {
    console.log('handian-btn exist');
    button.style.position = "fixed";
}
//--->

----------------------------------------------------------
function moveBtn2Center() { //get center of visible zone in vertical mode

}
var ele = $('div.taketori-col');
var origX = ele.scrollLeft() + ele.width() / 2; //orig.x
var origY = ele.scrollTop() + ele.height() / 2; //orig.x

var oldLeft = button.offsetLeft;
var newLeft = origX;
button.style['left'] = origX + 'px';

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
var button = document.getElementById('handian-btn');
var oldLeft = button.offsetLeft;
var newLeft = oldLeft - document.body.offsetWidth;
var newLeft = Math.abs(newLeft)
button.style['left'] = newLeft + 'px';

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
var button = document.getElementById('handian-btn');
button.style['left'] = 0 + 'px';

-- -- -- -- -- -- -- -- -- -- -- -- -- --


text:
/* jshint undef: false */

const {BrowserWindow, app} = require('electron');

let mainWindow = null;

app.on('window-all-closed', function onWindowAllClosed() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('ready', function onReady() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    });

    delete mainWindow.module;

    if (process.env.EMBER_ENV === 'test') {
        mainWindow.loadURL('file://' + __dirname + '/index.html');
    } else {
        mainWindow.loadURL('file://' + __dirname + '/dist/index.html');
    }

    mainWindow.on('closed', function onClosed() {
        mainWindow = null;
    });
});

/* jshint undef: true */


text:
    Skills

Technical Skills

				Category
				Proficency In Decreasing Order

				Programming Languages
				C, Java, C++, Python, R

				Technologies and Tools
				Git, Linux, Android and Android Studio, Shell Scripting, LaTeX

				Web Technologies
				HTML, CSS, JavaScript, MySQL/SQLite, AngularJS, Bootstrap, PHP

Project Management

    Lead a team of undergradate and graduate researchers throughout the course of a 2-year behavioural neuroscience research project. Managed and oversaw the planning and implementation of the project while reporting to an advisory committee, and provided mentorship and supervision to new researchers.


text:
package com.example;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FoobarController {

	private final FoobarService service;

	public FoobarController(FoobarService service) {
		this.service = service;
	}

	@GetMapping("/foobar")
	public Object getAll() {
		return service.findAll();
	}
}


text:
'use strict';

module.exports = angular.module('temperature', ['ngResource', 'hateoas'])
    .controller('TemperatureCtrl', require('./temperature-controller'))
    .factory('TemperatureResource', require('./temperature-resource').temperature);


text:
fuckdown2
=========

Fuckdown2 is a JIT compiler for Brainfuck to x86-64 native linux code. It
should work on any modern Linux computer.

It's called fuckdown2 because I had originally started to work on a Brainfuck
compiler about a year or so ago but didn't make it anywhere; that compiler was
simply called "fuckdown".

In case you were wondering, the goal of this project is to work as many
expletives as possible into the source code.

Features
========

#### Can parse Brainfuck programs from files into a high-level AST

This is Brainfuck, so take the term "high-level" with a grain of salt.

#### Can compile a Brainfuck AST into a high-level x86 AST

This happens in particular in `src/Compiler.hs`. I've developed an EDSL for
creating these x86 ASTs, so it essentially just looks like you're writing
assembly straight into Haskell. Under the hood, this is all just syntactic
sugar for the `AsmF` free monad that is built in `src/Asm.hs`.

Another cool thing about this representation is that the label type and address
type are kept abstract as much as possible. This allows us to reuse the exact
same data structure for both pretty-printing and compilation.

#### Can pretty-print Brainfuck and x86 ASTs

The pretty-printed Brainfuck AST should look just like the input program. It is
a known bug that it currently doesn't. The pretty-printed x86 code is properly
labelled, but is nonetheless pretty hard to read.

#### Can assemble an x86-64 AST into a ByteString

This was definitely the most tedious part of the project, since it involved
frequently looking up the opcode specifications for different instructions, and
figuring exactly which bytes to emit to the bytestring. This all takes place in
`src/Assembler.hs`.

The labelling mechanism is again probably the most interesting part. In our x86
DSL, we would like to be able to jump to labels that are declared further in
the code, since we want to be able to jump over a section of code to a later
one. Since we're using the do notation, we can't exactly do this; labels aren't
associated with string names, they're just magical opaque values. The
workaround that I came up with was to give some kind of syntax for "forward
declaring" a label, and at a later time filling in its value.

The implementation of this label forward declaration mechanism is tricky. The
assembler is a state monad, and it keeps track of all the labels that have been
declared so far in a map. We represent the fact that labels might be _empty_
with `Maybe` in this map. When a label is given an explicit value, we fill it
into the map with `Just`. We have to keep track of how many bytes we've emitted
to the output string in order to be able to correctly assign values to the
labels.

The output of this state monad is then a reader monad which takes as its
configuration a map from labels to values. This is precisely the map that has
been built up by the state monad. If when the state monad completes, the map
has some labels undefined, we simply raise an error. If all the labels are
defined, then we can sequence the map of Maybe values into a map of plain
values and feed it to the reader monad computation that has been built up. This
reader monad computation then will then use the label addresses in the map to
compute the offsets for jump instructions.

The final output of that is the assembled byte array that is essentially the
body of a compiled C function. In order to make it into a bona fide function,
we wrap it with the function intro and outro code for setting up a stack frame.

#### Can invoke a ByteString as a function

This is where the real black magic happens.

We allocate a chunk of memory at least as bit as our assembled ByteString and
ensure that this memory region has the executable permission set. We do this
with an FFI call to `mmap`. Then we copy the assembled ByteString into that
region and using a call to `unsafeCoerce`, convert a pointer to the start of
that region into a pointer to a function having the type `Ptr a -> IO ()` which
essentially corresponds to a C function `void bf(void *mem)`. The argument to
this function is a pointer to a region in memory where our brainfuck program
can play around.

Next we use a _dynamic_ FFI call to convert the function pointer that we
created with `unsafeCoerce` into a bona fide Haskell function. We allocate a
chunk of read-write memory (4KiB should be enough, right?) and pass it to this
function that we've synthesized with the FFI to obtain an IO action. We run the
IO action in main, and that executes our compiled program. Hooray!

Bugs
=====

The major known bug is that the pretty-printer for the Brainfuck AST produces
bogus text. It's not clear exactly why that happens yet.


text:
package com.appslandia.plum.base;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.appslandia.common.base.MemoryStreamImpl;
import com.appslandia.common.utils.FileUtils;
import com.appslandia.plum.mocks.MockHttpServletResponse;
import com.appslandia.plum.mocks.MockServletContext;
import com.appslandia.plum.mocks.MockSessionCookieConfig;

public class MemoryResponseWrapperTest {

	MockServletContext servletContext;
	MockHttpServletResponse response;

	@Before
	public void init() {
		servletContext = new MockServletContext(new MockSessionCookieConfig());
		response = new MockHttpServletResponse(servletContext);
	}

	@Test
	public void testMemoryResponseWrapper() {
		MemoryResponseWrapper wrapper = new MemoryResponseWrapper(response, new MemoryStreamImpl(512), false);
		try {
			wrapper.getOutputStream().write("data".getBytes(StandardCharsets.UTF_8));
			wrapper.finishWrapper();

			Assert.assertEquals(wrapper.getContent().toString(StandardCharsets.UTF_8.name()), "data");
		} catch (IOException ex) {
			Assert.fail(ex.getMessage());
		}
	}

	@Test
	public void testMemoryResponseWrapper_gzip() {
		MemoryResponseWrapper wrapper = new MemoryResponseWrapper(response, new MemoryStreamImpl(512), true);
		try {
			wrapper.getOutputStream().write("data".getBytes(StandardCharsets.UTF_8));
			wrapper.finishWrapper();

			// wrapper.getContent(): Compressed content
			Assert.assertNotEquals(wrapper.getContent().toString(StandardCharsets.UTF_8.name()), "data");

			ByteArrayOutputStream gzipMem = new ByteArrayOutputStream();
			wrapper.getContent().writeTo(gzipMem);

			ByteArrayOutputStream ungzipMem = new ByteArrayOutputStream();
			FileUtils.copy(new GZIPInputStream(new ByteArrayInputStream(gzipMem.toByteArray())), ungzipMem);

			// ungzipMem
			Assert.assertEquals(ungzipMem.toString(StandardCharsets.UTF_8.name()), "data");
		} catch (IOException ex) {
			Assert.fail(ex.getMessage());
		}
	}

	@Test
	public void testMemoryResponseWrapper_resetBuffer() {
		MemoryResponseWrapper wrapper = new MemoryResponseWrapper(response, new MemoryStreamImpl(512), false);
		try {
			wrapper.getOutputStream().write("data".getBytes(StandardCharsets.UTF_8));
			wrapper.resetBuffer();
			Assert.assertEquals(wrapper.getContent().size(), 0);

		} catch (IOException ex) {
			Assert.fail(ex.getMessage());
		}
	}

	@Test
	public void testMemoryResponseWrapper_sendError() {
		MemoryResponseWrapper wrapper = new MemoryResponseWrapper(response, new MemoryStreamImpl(512), false);
		try {
			wrapper.getOutputStream().write("data".getBytes(StandardCharsets.UTF_8));
			wrapper.sendError(500);

			Assert.assertEquals(wrapper.getContent().size(), 0);
			Assert.assertEquals(wrapper.getStatus(), 500);
			Assert.assertFalse(wrapper.isCommitted());

		} catch (IOException ex) {
			Assert.fail(ex.getMessage());
		}
	}
}


text:
using System.Collections.Generic;

namespace CSharp2nem.ResponseObjects.Nis
{
    /// <summary>
    /// Communication timestamps contain information about the network time of a remote NIS.
    /// </summary>
    /// <remarks>
    /// NEM uses a time synchronization mechanism to synchronize time across the network. Each node maintains a network time which is the time of the computer clock plus an offset which compensates for the deviation from the computer clocks of other nodes.
    /// </remarks>
    public class NetworkTime
    {
        /// <summary>
        /// The network time at the moment the reply was sent.
        /// </summary>
        public long SendTimeStamp { get; set; }

        /// <summary>
        /// The network time at the moment the request was received.
        /// </summary>
        public long ReceiveTimeStamp { get; set; }
    }

    /// <summary>
    /// Determines if NIS is up and responsive.
    /// </summary>
    public class NemRequestResult
    {
        /// <summary>
        /// The meaning of the code is dependent on the type. For type 1 (validation result) only 0 and 1 mean there was no failure.
        /// </summary>
        /// <remarks>
        /// The following codes are the most frequent ones occurring:
        ///
        /// 0:Neutral result. A typical example would be that a node validates an incoming transaction and realizes that it already knows about the transaction. In this case it is neither a success (meaning the node has a new transaction) nor a failure (because the transaction itself is valid).
        /// 1:Success result. A typical example would be that a node validates a new valid transaction.
        /// 2:Unknown failure. The validation failed for unknown reasons.
        /// 3:The entity that was validated has already past its deadline.
        /// 4:The entity used a deadline which lies too far in the future.
        /// 5:There was an account involved which had an insufficient balance to perform the operation.
        /// 6:The message supplied with the transaction is too large.
        /// 7:The hash of the entity which got validated is already in the database.
        /// 8:The signature of the entity could not be validated.
        /// 9:The entity used a timestamp that lies too far in the past.
        /// 10:The entity used a timestamp that lies in the future which is not acceptable.
        /// 11:The entity is unusable.
        /// 12:The score of the remote block chain is inferior (although a superior score was promised).
        /// 13:The remote block chain failed validation.
        /// 14:There was a conflicting importance transfer detected.
        /// 15:There were too many transaction in the supplied block.
        /// 16:The block contains a transaction that was signed by the harvester.
        /// 17:A previous importance transaction conflicts with a new transaction.
        /// 18:An importance transfer activation was attempted while previous one is active.
        /// 19:An importance transfer deactivation was attempted but is not active.
        /// For type 2 the following codes are supported:
        ///
        /// 1:Successful heart beat detected.
        /// For type 3 the following codes are supported:
        ///
        /// 0:Unknown status.
        /// 1:NIS is stopped.
        /// 2:NIS is starting.
        /// 3:NIS is running.
        /// 4:NIS is booting the local node (implies NIS is running).
        /// 5:The local node is booted (implies NIS is running).
        /// 6:The local node is synchronized (implies NIS is running and the local node is booted).
        /// 7:There is no remote node available (implies NIS is running and the local node is booted).
        /// 8:NIS is currently loading the block chain.
        /// </remarks>
        public int Code { get; set; }
        /// <summary>
        /// The type is dependent on the request which was answered.
        /// </summary>
        /// <remarks>
        /// The interpretation of the code field depends on the type. Currently the following types are supported:
        ///
        /// 1: The result is a validation result.
        /// 2: The result is a heart beat result.
        /// 4: The result indicates a status.
        /// </remarks>
        public int Type { get; set; }
        /// <summary>
        /// The message associated with the code.
        /// </summary>
        public string Message { get; set; }
    }

    /// <summary>
    /// A time synchronization result is the outcome of the network time synchronization of a node with other remote nodes. To agree upon a common time nodes need to synchronize time every hour.
    /// </summary>
    public class TimeSynchronizationResult
    {
        /// <summary>
        /// The date and time when the synchronization was performed.
        /// </summary>
        public string DateTime { get; set; }
        /// <summary>
        /// The current offset to the local computer clock in milliseconds.
        /// </summary>
        public int CurrentTimeOffset { get; set; }
        /// <summary>
        /// The change in milliseconds compared to the last synchronization.
        /// </summary>
        public int Change { get; set; }
    }

    /// <summary>
    /// Time sync data
    /// </summary>
    public class TimeSync
    {
        /// <summary>
        /// Contains a list of <see cref="TimeSynchronizationResult"/> instances returned from nis.
        /// </summary>
        public List<TimeSynchronizationResult> Data { get; set; }
    }
}


text:
package org.door.dbflute.cbean.cq.ciq;

import java.util.Map;
import org.dbflute.cbean.*;
import org.dbflute.cbean.ckey.*;
import org.dbflute.cbean.coption.ConditionOption;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.door.dbflute.cbean.*;
import org.door.dbflute.cbean.cq.bs.*;
import org.door.dbflute.cbean.cq.*;

/**
 * The condition-query for in-line of door.
 * @author DBFlute(AutoGenerator)
 */
public class DoorCIQ extends AbstractBsDoorCQ {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected BsDoorCQ _myCQ;

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public DoorCIQ(ConditionQuery referrerQuery, SqlClause sqlClause
                        , String aliasName, int nestLevel, BsDoorCQ myCQ) {
        super(referrerQuery, sqlClause, aliasName, nestLevel);
        _myCQ = myCQ;
        _foreignPropertyName = _myCQ.xgetForeignPropertyName(); // accept foreign property name
        _relationPath = _myCQ.xgetRelationPath(); // accept relation path
        _inline = true;
    }

    // ===================================================================================
    //                                                             Override about Register
    //                                                             =======================
    protected void reflectRelationOnUnionQuery(ConditionQuery bq, ConditionQuery uq)
    { throw new IllegalConditionBeanOperationException("InlineView cannot use Union: " + bq + " : " + uq); }

    @Override
    protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col)
    { regIQ(k, v, cv, col); }

    @Override
    protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col, ConditionOption op)
    { regIQ(k, v, cv, col, op); }

    @Override
    protected void registerWhereClause(String wc)
    { registerInlineWhereClause(wc); }

    @Override
    protected boolean isInScopeRelationSuppressLocalAliasName() {
        if (_onClause) { throw new IllegalConditionBeanOperationException("InScopeRelation on OnClause is unsupported."); }
        return true;
    }

    // ===================================================================================
    //                                                                Override about Query
    //                                                                ====================
    protected ConditionValue xgetCValueDoorId() { return _myCQ.xdfgetDoorId(); }
    public String keepDoorId_ExistsReferrer_DoorSensorLogList(DoorSensorLogCQ sq)
    { throwIICBOE("ExistsReferrer"); return null; }
    public String keepDoorId_NotExistsReferrer_DoorSensorLogList(DoorSensorLogCQ sq)
    { throwIICBOE("NotExistsReferrer"); return null; }
    public String keepDoorId_SpecifyDerivedReferrer_DoorSensorLogList(DoorSensorLogCQ sq)
    { throwIICBOE("(Specify)DerivedReferrer"); return null; }
    public String keepDoorId_QueryDerivedReferrer_DoorSensorLogList(DoorSensorLogCQ sq)
    { throwIICBOE("(Query)DerivedReferrer"); return null; }
    public String keepDoorId_QueryDerivedReferrer_DoorSensorLogListParameter(Object vl)
    { throwIICBOE("(Query)DerivedReferrer"); return null; }
    protected ConditionValue xgetCValueDoorName() { return _myCQ.xdfgetDoorName(); }
    protected ConditionValue xgetCValueMin() { return _myCQ.xdfgetMin(); }
    protected ConditionValue xgetCValueMax() { return _myCQ.xdfgetMax(); }
    protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String pp) { return null; }
    public String keepScalarCondition(DoorCQ sq)
    { throwIICBOE("ScalarCondition"); return null; }
    public String keepSpecifyMyselfDerived(DoorCQ sq)
    { throwIICBOE("(Specify)MyselfDerived"); return null;}
    public String keepQueryMyselfDerived(DoorCQ sq)
    { throwIICBOE("(Query)MyselfDerived"); return null;}
    public String keepQueryMyselfDerivedParameter(Object vl)
    { throwIICBOE("(Query)MyselfDerived"); return null;}
    public String keepMyselfExists(DoorCQ sq)
    { throwIICBOE("MyselfExists"); return null;}

    protected void throwIICBOE(String name)
    { throw new IllegalConditionBeanOperationException(name + " at InlineView is unsupported."); }

    // ===================================================================================
    //                                                                       Very Internal
    //                                                                       =============
    // very internal (for suppressing warn about 'Not Use Import')
    protected String xinCB() { return DoorCB.class.getName(); }
    protected String xinCQ() { return DoorCQ.class.getName(); }
}


text:
package org.deidentifier.arx.gui.view.impl.menu;

import org.deidentifier.arx.DataSelector;

/**
 *
 */
public class DialogQueryResult {

    /**  TODO */
    public final DataSelector selector;

    /**  TODO */
    public final String query;

    /**
     *
     *
     * @param query
     * @param selector
     */
    protected DialogQueryResult(String query, DataSelector selector) {
        this.query = query;
        this.selector = selector;
    }
}


text:
#include "mongoc-prelude.h"

#ifndef MONGOC_TOPOLOGY_DESCRIPTION_PRIVATE_H
#define MONGOC_TOPOLOGY_DESCRIPTION_PRIVATE_H

#include "mongoc-set-private.h"
#include "mongoc-server-description.h"
#include "mongoc-array-private.h"
#include "mongoc-topology-description.h"
#include "mongoc-apm-private.h"

typedef enum {
   MONGOC_TOPOLOGY_UNKNOWN,
   MONGOC_TOPOLOGY_SHARDED,
   MONGOC_TOPOLOGY_RS_NO_PRIMARY,
   MONGOC_TOPOLOGY_RS_WITH_PRIMARY,
   MONGOC_TOPOLOGY_SINGLE,
   MONGOC_TOPOLOGY_LOAD_BALANCED,
   MONGOC_TOPOLOGY_DESCRIPTION_TYPES
} mongoc_topology_description_type_t;

struct _mongoc_topology_description_t {
   bson_oid_t topology_id;
   bool opened;
   mongoc_topology_description_type_t type;
   int64_t heartbeat_msec;
   mongoc_set_t *_servers_;
   char *set_name;
   int64_t max_set_version;
   bson_oid_t max_election_id;
   bson_error_t compatibility_error;
   uint32_t max_server_id;
   int32_t max_hosts; /* srvMaxHosts */
   bool stale;
   unsigned int rand_seed;

   /* the greatest seen cluster time, for a MongoDB 3.6+ sharded cluster.
    * see Driver Sessions Spec. */
   bson_t cluster_time;

   /* smallest seen logicalSessionTimeoutMinutes, or -1 if any server has no
    * logicalSessionTimeoutMinutes. see Server Discovery and Monitoring Spec */
   int64_t session_timeout_minutes;

   mongoc_apm_callbacks_t apm_callbacks;
   void *apm_context;
};

typedef enum {
   MONGOC_SS_READ,
   MONGOC_SS_WRITE,
   MONGOC_SS_AGGREGATE_WITH_WRITE
} mongoc_ss_optype_t;

void
mongoc_topology_description_init (mongoc_topology_description_t *description,
                                  int64_t heartbeat_msec);

/**
 * @brief Get a pointer to the set of server descriptions in the topology
 * description.
 */
static BSON_INLINE mongoc_set_t *
mc_tpld_servers (mongoc_topology_description_t *tpld)
{
   BSON_ASSERT_PARAM (tpld);
   return tpld->_servers_;
}

static BSON_INLINE const mongoc_set_t *
mc_tpld_servers_const (const mongoc_topology_description_t *tpld)
{
   BSON_ASSERT_PARAM (tpld);
   return tpld->_servers_;
}

void
_mongoc_topology_description_copy_to (const mongoc_topology_description_t *src,
                                      mongoc_topology_description_t *dst);

void
mongoc_topology_description_cleanup (
   mongoc_topology_description_t *description);

void
mongoc_topology_description_handle_hello (
   mongoc_topology_description_t *topology,
   uint32_t server_id,
   const bson_t *hello_response,
   int64_t rtt_msec,
   const bson_error_t *error /* IN */);

mongoc_server_description_t const *
mongoc_topology_description_select (
   const mongoc_topology_description_t *description,
   mongoc_ss_optype_t optype,
   const mongoc_read_prefs_t *read_pref,
   bool *must_use_primary,
   int64_t local_threshold_ms);

mongoc_server_description_t *
mongoc_topology_description_server_by_id (
   mongoc_topology_description_t *description,
   uint32_t id,
   bson_error_t *error);

const mongoc_server_description_t *
mongoc_topology_description_server_by_id_const (
   const mongoc_topology_description_t *description,
   uint32_t id,
   bson_error_t *error);

int32_t
mongoc_topology_description_lowest_max_wire_version (
   const mongoc_topology_description_t *td);

bool
mongoc_topology_description_all_sds_have_write_date (
   const mongoc_topology_description_t *td);

bool
_mongoc_topology_description_validate_max_staleness (
   const mongoc_topology_description_t *td,
   int64_t max_staleness_seconds,
   bson_error_t *error);

void
mongoc_topology_description_suitable_servers (
   mongoc_array_t *set, /* OUT */
   mongoc_ss_optype_t optype,
   const mongoc_topology_description_t *topology,
   const mongoc_read_prefs_t *read_pref,
   bool *must_use_primary,
   size_t local_threshold_ms);

bool
mongoc_topology_description_has_data_node (
   const mongoc_topology_description_t *td);

void
mongoc_topology_description_invalidate_server (
   mongoc_topology_description_t *topology,
   uint32_t id,
   const bson_error_t *error /* IN */);

bool
mongoc_topology_description_add_server (mongoc_topology_description_t *topology,
                                        const char *server,
                                        uint32_t *id /* OUT */);

void
mongoc_topology_description_update_cluster_time (
   mongoc_topology_description_t *td, const bson_t *reply);

void
mongoc_topology_description_reconcile (mongoc_topology_description_t *td,
                                       mongoc_host_list_t *host_list);

/**
 * @brief Invalidate open connnections to a server.
 *
 * Pooled clients with open connections will discover the invalidation
 * the next time they fetch a stream to the server.
 *
 * @param td The topology description that will be updated.
 * @param server_id The ID of the server to invalidate.
 * @param service_id A service ID for load-balanced deployments. Use
 * kZeroServiceID if not applicable.
 *
 * @note Not applicable to single-threaded clients, which only maintain a
 * single connection per server and therefore have no connection pool.
 */
void
_mongoc_topology_description_clear_connection_pool (
   mongoc_topology_description_t *td,
   uint32_t server_id,
   const bson_oid_t *service_id);

#endif /* MONGOC_TOPOLOGY_DESCRIPTION_PRIVATE_H */


text:
Go

I have written the following Go code through trial & error and 'Googling'.

**Instructions:**

Using docker-compose:

* `docker-compose up`

Using `docker run`:

* Build the image `./build_docker.sh`
* Run the example `./run_docker.sh <num_requests> <url>`
 * If you do not pass a URL raspberrypi.org will be used by default.


text:
require 'set'

require 'harp-runtime/resources/rds/db_security_group'
require 'harp-runtime/resources/rds/db_instance'

module Harp
  module Resources
    extend self
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>OpModeRegister</title>
<meta name="date" content="2015-11-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.qualcomm.robotcore.eventloop.opmode

Interface OpModeRegister

public interface OpModeRegister

Register Op Modes

Method Summary

Methods

Modifier and Type
Method and Description

void
register(OpModeManager manager)

The Op Mode Manager will call this method when it wants a list of all
 available op modes.

Method Detail

register

void register(OpModeManager manager)

The Op Mode Manager will call this method when it wants a list of all
 available op modes. Add you op mode to the list to enable it.

Parameters:

manager - op mode manager

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method