text:
using MetaDslx.CodeAnalysis.Meta.Test.Languages.PropertiesTest;
using MetaDslx.Modeling;
using MetaDslx.Tests;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;

namespace MetaDslx.CodeAnalysis.Meta.Test
{
    public class AssociationTest : DebugAssertUnitTest
    {
        [Fact]
        public void TestEndToAssociation()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEnd();
            end.Association = assoc;
            Assert.Equal(end, assoc.First);
            Assert.Equal(end, assoc.Second);
            Assert.Equal(assoc, end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Equal(iend, iassoc.First);
            Assert.Equal(iend, iassoc.Second);
            Assert.Equal(iassoc, iend.Association);
        }

        [Fact]
        public void TestAssociationToEnd()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEnd();
            var end2 = factory.AssociationEnd();
            assoc.First = end1;
            Assert.Equal(end1, assoc.First);
            Assert.Null(assoc.Second);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.Second = end2;
            Assert.Equal(end1, assoc.First);
            Assert.Equal(end2, assoc.Second);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Equal(iend1, iassoc.First);
            Assert.Equal(iend2, iassoc.Second);
            Assert.Equal(iassoc, iend1.Association);
            Assert.Equal(iassoc, iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationReset()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEnd();
            end.Association = assoc;
            Assert.Equal(end, assoc.First);
            Assert.Equal(end, assoc.Second);
            Assert.Equal(assoc, end.Association);
            end.Association = null;
            Assert.Null(assoc.First);
            Assert.Null(assoc.Second);
            Assert.Null(end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend.Association);
        }

        [Fact]
        public void TestAssociationToEndReset()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEnd();
            var end2 = factory.AssociationEnd();
            assoc.First = end1;
            Assert.Equal(end1, assoc.First);
            Assert.Null(assoc.Second);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.Second = end2;
            Assert.Equal(end1, assoc.First);
            Assert.Equal(end2, assoc.Second);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.First = null;
            Assert.Null(assoc.First);
            Assert.Equal(end2, assoc.Second);
            Assert.Null(end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.First = end1;
            assoc.Second = null;
            Assert.Equal(end1, assoc.First);
            Assert.Null(assoc.Second);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.First = null;
            Assert.Null(assoc.First);
            Assert.Null(assoc.Second);
            Assert.Null(end1.Association);
            Assert.Null(end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend1.Association);
            Assert.Null(iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationSet2Set()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndSet();
            end.Association = assoc;
            Assert.Contains(end, assoc.FirstSet);
            Assert.Contains(end, assoc.SecondSet);
            Assert.Equal(assoc, end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Contains(iend, iassoc.FirstSet);
            Assert.Contains(iend, iassoc.SecondSet);
            Assert.Equal(iassoc, iend.Association);
        }

        [Fact]
        public void TestAssociationToEndSet2Set()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndSet();
            var end2 = factory.AssociationEndSet();
            assoc.FirstSet.Add(end1);
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 0);
            Assert.Contains(end1, assoc.FirstSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondSet.Add(end2);
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 1);
            Assert.Contains(end1, assoc.FirstSet);
            Assert.Contains(end2, assoc.SecondSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Contains(iend1, iassoc.FirstSet);
            Assert.Contains(iend2, iassoc.SecondSet);
            Assert.Equal(iassoc, iend1.Association);
            Assert.Equal(iassoc, iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationResetSet2Set()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndSet();
            end.Association = assoc;
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 1);
            Assert.Contains(end, assoc.FirstSet);
            Assert.Contains(end, assoc.SecondSet);
            Assert.Equal(assoc, end.Association);
            end.Association = null;
            Assert.True(assoc.FirstSet.Count == 0);
            Assert.True(assoc.SecondSet.Count == 0);
            Assert.Null(end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend.Association);
        }

        [Fact]
        public void TestAssociationToEndResetSet2Set()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndSet();
            var end2 = factory.AssociationEndSet();
            assoc.FirstSet.Add(end1);
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 0);
            Assert.Contains(end1, assoc.FirstSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondSet.Add(end2);
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 1);
            Assert.Contains(end1, assoc.FirstSet);
            Assert.Contains(end2, assoc.SecondSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstSet.Remove(end1);
            Assert.True(assoc.FirstSet.Count == 0);
            Assert.True(assoc.SecondSet.Count == 1);
            Assert.Contains(end2, assoc.SecondSet);
            Assert.Null(end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstSet.Add(end1);
            assoc.SecondSet.Remove(end2);
            Assert.True(assoc.FirstSet.Count == 1);
            Assert.True(assoc.SecondSet.Count == 0);
            Assert.Contains(end1, assoc.FirstSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.FirstSet.Remove(end1);
            Assert.True(assoc.FirstSet.Count == 0);
            Assert.True(assoc.SecondSet.Count == 0);
            Assert.Null(end1.Association);
            Assert.Null(end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.True(iassoc.FirstSet.Count == 0);
            Assert.True(iassoc.SecondSet.Count == 0);
            Assert.Null(iend1.Association);
            Assert.Null(iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationList2List()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndList();
            end.Association = assoc;
            Assert.Contains(end, assoc.FirstList);
            Assert.Contains(end, assoc.SecondList);
            Assert.Equal(assoc, end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Contains(iend, iassoc.FirstList);
            Assert.Contains(iend, iassoc.SecondList);
            Assert.Equal(iassoc, iend.Association);
        }

        [Fact]
        public void TestAssociationToEndList2List()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndList();
            var end2 = factory.AssociationEndList();
            assoc.FirstList.Add(end1);
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 0);
            Assert.Contains(end1, assoc.FirstList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondList.Add(end2);
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 1);
            Assert.Contains(end1, assoc.FirstList);
            Assert.Contains(end2, assoc.SecondList);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Contains(iend1, iassoc.FirstList);
            Assert.Contains(iend2, iassoc.SecondList);
            Assert.Equal(iassoc, iend1.Association);
            Assert.Equal(iassoc, iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationResetList2List()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndList();
            end.Association = assoc;
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 1);
            Assert.Contains(end, assoc.FirstList);
            Assert.Contains(end, assoc.SecondList);
            Assert.Equal(assoc, end.Association);
            end.Association = null;
            Assert.True(assoc.FirstList.Count == 0);
            Assert.True(assoc.SecondList.Count == 0);
            Assert.Null(end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend.Association);
        }

        [Fact]
        public void TestAssociationToEndResetList2List()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndList();
            var end2 = factory.AssociationEndList();
            assoc.FirstList.Add(end1);
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 0);
            Assert.Contains(end1, assoc.FirstList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondList.Add(end2);
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 1);
            Assert.Contains(end1, assoc.FirstList);
            Assert.Contains(end2, assoc.SecondList);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstList.Remove(end1);
            Assert.True(assoc.FirstList.Count == 0);
            Assert.True(assoc.SecondList.Count == 1);
            Assert.Contains(end2, assoc.SecondList);
            Assert.Null(end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstList.Add(end1);
            assoc.SecondList.Remove(end2);
            Assert.True(assoc.FirstList.Count == 1);
            Assert.True(assoc.SecondList.Count == 0);
            Assert.Contains(end1, assoc.FirstList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.FirstList.Remove(end1);
            Assert.True(assoc.FirstList.Count == 0);
            Assert.True(assoc.SecondList.Count == 0);
            Assert.Null(end1.Association);
            Assert.Null(end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.True(iassoc.FirstList.Count == 0);
            Assert.True(iassoc.SecondList.Count == 0);
            Assert.Null(iend1.Association);
            Assert.Null(iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationMultiSet2MultiSet()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndMultiSet();
            end.Association = assoc;
            Assert.Contains(end, assoc.FirstMultiSet);
            Assert.Contains(end, assoc.SecondMultiSet);
            Assert.Equal(assoc, end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Contains(iend, iassoc.FirstMultiSet);
            Assert.Contains(iend, iassoc.SecondMultiSet);
            Assert.Equal(iassoc, iend.Association);
        }

        [Fact]
        public void TestAssociationToEndMultiSet2MultiSet()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndMultiSet();
            var end2 = factory.AssociationEndMultiSet();
            assoc.FirstMultiSet.Add(end1);
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondMultiSet.Add(end2);
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 1);
            Assert.Contains(end1, assoc.FirstMultiSet);
            Assert.Contains(end2, assoc.SecondMultiSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Contains(iend1, iassoc.FirstMultiSet);
            Assert.Contains(iend2, iassoc.SecondMultiSet);
            Assert.Equal(iassoc, iend1.Association);
            Assert.Equal(iassoc, iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationResetMultiSet2MultiSet()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndMultiSet();
            end.Association = assoc;
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 1);
            Assert.Contains(end, assoc.FirstMultiSet);
            Assert.Contains(end, assoc.SecondMultiSet);
            Assert.Equal(assoc, end.Association);
            end.Association = null;
            Assert.True(assoc.FirstMultiSet.Count == 0);
            Assert.True(assoc.SecondMultiSet.Count == 0);
            Assert.Null(end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend.Association);
        }

        [Fact]
        public void TestAssociationToEndResetMultiSet2MultiSet()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndMultiSet();
            var end2 = factory.AssociationEndMultiSet();
            assoc.FirstMultiSet.Add(end1);
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondMultiSet.Add(end2);
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 1);
            Assert.Contains(end1, assoc.FirstMultiSet);
            Assert.Contains(end2, assoc.SecondMultiSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstMultiSet.Remove(end1);
            Assert.True(assoc.FirstMultiSet.Count == 0);
            Assert.True(assoc.SecondMultiSet.Count == 1);
            Assert.Contains(end2, assoc.SecondMultiSet);
            Assert.Null(end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstMultiSet.Add(end1);
            assoc.SecondMultiSet.Remove(end2);
            Assert.True(assoc.FirstMultiSet.Count == 1);
            Assert.True(assoc.SecondMultiSet.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiSet);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.FirstMultiSet.Remove(end1);
            Assert.True(assoc.FirstMultiSet.Count == 0);
            Assert.True(assoc.SecondMultiSet.Count == 0);
            Assert.Null(end1.Association);
            Assert.Null(end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.True(iassoc.FirstMultiSet.Count == 0);
            Assert.True(iassoc.SecondMultiSet.Count == 0);
            Assert.Null(iend1.Association);
            Assert.Null(iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationMultiList2MultiList()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndMultiList();
            end.Association = assoc;
            Assert.Contains(end, assoc.FirstMultiList);
            Assert.Contains(end, assoc.SecondMultiList);
            Assert.Equal(assoc, end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Contains(iend, iassoc.FirstMultiList);
            Assert.Contains(iend, iassoc.SecondMultiList);
            Assert.Equal(iassoc, iend.Association);
        }

        [Fact]
        public void TestAssociationToEndMultiList2MultiList()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndMultiList();
            var end2 = factory.AssociationEndMultiList();
            assoc.FirstMultiList.Add(end1);
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondMultiList.Add(end2);
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 1);
            Assert.Contains(end1, assoc.FirstMultiList);
            Assert.Contains(end2, assoc.SecondMultiList);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.Contains(iend1, iassoc.FirstMultiList);
            Assert.Contains(iend2, iassoc.SecondMultiList);
            Assert.Equal(iassoc, iend1.Association);
            Assert.Equal(iassoc, iend2.Association);
        }

        [Fact]
        public void TestEndToAssociationResetMultiList2MultiList()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end = factory.AssociationEndMultiList();
            end.Association = assoc;
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 1);
            Assert.Contains(end, assoc.FirstMultiList);
            Assert.Contains(end, assoc.SecondMultiList);
            Assert.Equal(assoc, end.Association);
            end.Association = null;
            Assert.True(assoc.FirstMultiList.Count == 0);
            Assert.True(assoc.SecondMultiList.Count == 0);
            Assert.Null(end.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend = end.ToImmutable(imodel);
            Assert.Null(iassoc.First);
            Assert.Null(iassoc.Second);
            Assert.Null(iend.Association);
        }

        [Fact]
        public void TestAssociationToEndResetMultiList2MultiList()
        {
            var model = new MutableModel();
            var factory = new PropertiesTestFactory(model);
            var assoc = factory.Association();
            var end1 = factory.AssociationEndMultiList();
            var end2 = factory.AssociationEndMultiList();
            assoc.FirstMultiList.Add(end1);
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.SecondMultiList.Add(end2);
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 1);
            Assert.Contains(end1, assoc.FirstMultiList);
            Assert.Contains(end2, assoc.SecondMultiList);
            Assert.Equal(assoc, end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstMultiList.Remove(end1);
            Assert.True(assoc.FirstMultiList.Count == 0);
            Assert.True(assoc.SecondMultiList.Count == 1);
            Assert.Contains(end2, assoc.SecondMultiList);
            Assert.Null(end1.Association);
            Assert.Equal(assoc, end2.Association);
            assoc.FirstMultiList.Add(end1);
            assoc.SecondMultiList.Remove(end2);
            Assert.True(assoc.FirstMultiList.Count == 1);
            Assert.True(assoc.SecondMultiList.Count == 0);
            Assert.Contains(end1, assoc.FirstMultiList);
            Assert.Equal(assoc, end1.Association);
            Assert.Null(end2.Association);
            assoc.FirstMultiList.Remove(end1);
            Assert.True(assoc.FirstMultiList.Count == 0);
            Assert.True(assoc.SecondMultiList.Count == 0);
            Assert.Null(end1.Association);
            Assert.Null(end2.Association);
            var imodel = model.ToImmutable();
            var iassoc = assoc.ToImmutable(imodel);
            var iend1 = end1.ToImmutable(imodel);
            var iend2 = end2.ToImmutable(imodel);
            Assert.True(iassoc.FirstMultiList.Count == 0);
            Assert.True(iassoc.SecondMultiList.Count == 0);
            Assert.Null(iend1.Association);
            Assert.Null(iend2.Association);
        }

    }
}


text:
<!DOCTYPE html>

		<title>OPC 8 Buyside (Procurement Mode) Main Menu</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<link rel="stylesheet" href="../../../css/jcatalog-bootstrap-bundle.css" type="text/css" media="screen" title="no title" charset="utf-8">
		<link rel="stylesheet" href="../../../css/jcatalog-bootstrap-extensions-bundle.css" type="text/css" media="screen" title="no title" charset="utf-8">

							Catalog

Search

Categories

External Shops

Suppliers

Contracts

							Requests

Requisitions

Requisition Status

Order Process Overview

Cart Import

Approval

Approve Requisition

Overview of Approved Requisitions

Show all Approvals

							Purchase Order

Purchase Orders

Purchase Order Status

Cancel Purchase Order

PO Confirmation

Deliveries

Goods Receipt

Delivery Note

Analysis

							Invoices

Invoice Administration

Create Invoice / Credit Note

Edit Invoice / Credit Note

Invoice Verification

Quick Quote

						<button type="button" class="btn btn-default visible-sm visible-xs" data-toggle="collapse" data-target="#main-menu">
							Menu
						</button>

							7

							7

							<button type="button" class="btn btn-primary btn-lg btn-block">Shopping Cart</button>

											2.00

												Asus X53SV-SO951V

												Supplier AG

												€1,198.00

											14.00

												TP-Link 300Mbps Wireless USB Adapter

												Supplier AG

												209.86

											3.00

												MacBook pro 13-inch: 2.4GHz with Retina display

												Apple

												3,897.00

											1.00

											more item(s)

											Total price: €5,344.42

							Martin Hallmann

Martin Hallmann

User Details

Change customer assignment

Language

DE Deutsch

EN English

FR Francais

Shopping Lists

Delegation

Support

Help

Logout

Auto Goods Receipt

System Administration

Customer Administration

Setup

				RfQ #ShortDesc#, Item 1/7

						Back to RfQ

						<button class="btn btn-default"> Item</button>
						<button class="btn btn-default"> Item</button>

Reliable Multitasking Performance

Powered by the 2nd generation Intel Core i5-2410M processor with Intel Turbo Boost 2.0 Technology, the A53E-XA2 easily handles multitasking and entertainment on its brilliant 15.6" LED-backlit HD display. HDMI ready, supersize your high-definition media to an HDTV for 1080p visuals and 8 channel surround sound support. The A53E-XA2 is also engineered with ASUS IceCool technology with hairline brushed aluminum to maintain a low temperature on the keyboard and palm rest area for comfortable computing even after the longest sessions.

Comfort and Control Included
The A53E-XA2 has an array of built-in features that are specialized for ease of use. It features a chiclet keyboard with numeric keypad and multi-touch trackpad to effortlessly type documents or navigate through your mobile world. The A53E-XA2 also has a spacious palm rest with ASUS Palm-Proof Technology where the trackpad intelligently distinguishes between your palm and finger to prevent errors for a worry-free typing experience.
With its sunken-hinge screen design, you will be able to enjoy wider and more ergonomic viewing angles, enabling greater clarity and comfort. Plus, the ASUS Power4Gear utility controls the fans noise level so you can relax with a virtually silent computing experience anywhere you go.

				ID00781234
				Open
				Response Required
				Information Only

					<input type="submit" class="btn btn-primary" value="Save & Next" name="submit" id="submit">

Product Info

Attributes

Supplier Response Attributes

Attachments

 			<form class="form-horizontal">

Product Info

							Product ID

								<input type="text" class="form-control" placeholder="" value="">

							Catalog ID

								<input type="text" class="form-control" placeholder="" value="">

							Manuf. ID

								<input type="text" class="form-control" placeholder="" value="">

							Manuf. name

								<input type="text" class="form-control" placeholder="" value="">

							Manuf. prod. ID

								<input type="text" class="form-control" placeholder="" value="">

							Short description

								<input type="text" class="form-control" placeholder="" value="">

							Long Description

								<textarea class="form-control textarea-resize-y"></textarea>

							Supplier Name

								<input type="text" class="form-control" placeholder="" value="">

							Ext. prod. ID

								<input type="text" class="form-control" placeholder="" value="">

										<input type="checkbox" autocomplete="off" checked> Response Required

										<input type="checkbox" autocomplete="off"> Information Only

							Comment

								<input type="text" class="form-control" placeholder="" value="">

							Selection group ID

								<input type="text" class="form-control" placeholder="DO WE NEED THIS?" value="">

Price

							Contract ID

								<input type="text" class="form-control" placeholder="" value="">

							Price Unit

								<input type="text" class="form-control" placeholder="" value="">

							Quantity

								<input type="text" class="form-control" placeholder="" value="">

							UOM

								<select class="form-control">
									<option>piece</option>
								</select>

							Net Price

								<input type="text" class="form-control" placeholder="">

							Currency

								<select class="form-control">
									<option>EUR</option>
								</select>

							Contracted net price

								<input type="text" class="form-control" placeholder="" value="22.89" disabled>

							Contracted Currency

								<input type="text" class="form-control" placeholder="" value="EUR" disabled>

Date

							Lead time (days)

								<input type="text" class="form-control" placeholder="" value="">

							Delivery Date

									<input type="text" class="form-control input-date" placeholder="DD/MM/YYYY">

							Valid from

									<input type="text" class="form-control input-date" placeholder="DD/MM/YYYY">

							Valid to

									<input type="text" class="form-control input-date" placeholder="DD/MM/YYYY">

			</form>

				<input type="submit" class="btn btn-primary" value="Save & Next" name="submit" id="submit">

© 2001 — 2015 jCatalog Software AG

redpajama_set_name: RedPajamaGithub


text:
package com.antonio.samir.wonderfulredtooth.proxyrecorder.proxies;

import com.antonio.samir.wonderfulredtooth.proxyrecorder.ProxyManager;
import com.antonio.samir.wonderfulredtooth.proxyrecorder.bean.BeanLink;

import java.io.IOException;

/**
 * Created by samir on 7/8/15.
 */
public class RecorderClientToServer extends LinkRecorder {

    public RecorderClientToServer(final BeanLink beanLink, final ProxyManager proxyManager) throws IOException {
        super(proxyManager);
        getStreams(beanLink.client, beanLink.server);
    }

    @Override
    protected void write(final byte[] buffer) {
        proxyManager.request(buffer);
    }

}


text:
EyeJS Trial and Evaluation
==========================

## Trial Format

Trial participants will be asked to participate in a series of experiments. Each experiment will be performed by each user three times; once using a standard mouse, once using EyeJS with keypress activation, and once using EyeJS blink activation. The order of the experiments and the order of the input modes they use to complete the task (mouse, keypress, blinking) will be randomized.

### Input Modes

There are three distinct input modes for this trial. The keyboard will be used for text entry in all three modes.

#### Mouse ($m$)

In this input mode, the trial participants will use a standard mouse to select elements. This will be considered the *baseline case* that EyeJS is compared to.

#### Keypress ($k$)

In this input mode, elements are selected using a keyboard keypress using EyeJS. Users gaze at a particular elements (which is essentially analogous to a mouse *hover*), then press a key on the keyboard to select it.

#### Blinks  ($b$)

Elements are selected using EyeJS blink-selection. In this mode, users gaze at a particular element and use a specially timed blink to select elements.

### Experiments Overview

Each participant will complete four experiments. The experiment procedure will be repeated three times with each participant, once for each input mode.

#### Sythetic User Interface ($s$)

This experiment will measure the user's accuracy and execution time when presented with a sequence of selection tasks.

#### Simple Navigation ($w$)

This experiment will measure the difference in task execution time between different modes of input on a simple website (Wikipedia.org).

#### Complex Navigation ($a$)

This experiment will measure the difference in task execution time between different modes of input on a complex and link-dense website (Amazon.com).

#### User Focus ($f$)

This experiment will measure the amount of information gathered and retained by the user with and without custom eye-aware UI enhancements using EyeJS.

### Participant Randomization

The order in-which participants complete experiments will be randomized, as well as the order of input modes they use. An example of participant experiment and input mode assignments are below. The experiment cells are tuples, the first element representing which experiment is being performed and the second the order of input modalities.

| Participant        | First Experiment  | Second Experiment | Third Experiment  | Fourth Experiment |
| ------------------ | :---------------: | :---------------: | :---------------: | :---------------: |
| John               | $(s, kmb)$        | $(w, kbm)$        | $(f, mkb)$        | $(a, bkm)$        |
| Jane               | $(w, mbk)$        | $(s, mkb)$        | $(a, mbk)$        | $(f, kbm)$        |
| Mike               | $(a, kbm)$        | $(w, kbm)$        | $(f, kmb)$        | $(s, kmb)$        |

## Things to Avoid

### Don't Evaluate the Webpage

We don't want to evaluate the design or usability of the webpages used during this trial. Only the amount of time taken to *select* navigation elements, and selection accuracy should be considered, not the amount of time taken to *locate* the navigation element.

## Questions to Answer

### Primary Questions

- How does user accuracy change when using EyeJS compared to a standard mouse?
- How does using EyeJS affect the speed of task completion?
- When using EyeJS, are keypress activations more accurate than blinks?
- When using EyeJS, how does activation time compare between using keypresses and blinks?
- How small can buttons and other interactive elements get before accuracy and selection ability start to degrade?
- How close can interactive elements get before accuracy and selection ability start to degrade?

### Secondary Question

- How large should the gaze area (gaze indicator) be?
- Does automatic page scrolling decrease the amount of time it takes for users to perform the tasks? **[Should we add an experiment for automatic page scrolling?]**

## Assumptions and Parameters

### Gaze Area

The gaze area is a circular area where DOM sample points are taken by EyeJS. The samples are taken in an outward, counter-clockwise radiating pattern.

![](images/gaze-area.svg)

### Fixation Time

We consider a *fixation* to have occurred after the longest possible saccade (in duration). So, if the user's gaze remains over a specific element for a greater period of time than the longest saccade, then we consider this a fixation of that element. Eye tracker samples which indicate the user's gaze is over a specific element, but do not sample that same element for longer than some fixation threshold are ignored.

![](images/saccade-ignore.svg)

We define the *fixation threshold*, $\delta$, as minimum amount of time the user's gaze must be continually over an element for a *fixation* to occur.

$$ \delta = Fixation\ Threshold > Longest\ Saccade\ Duration = 120 ms $$

We assume that after the user has *fixated* on the target element, the user is aware of it's presence. In situations where the user's only goal is to select the target element, further fixations indicate gazing away from the target for some reason, or trouble selecting the target. The interpretation of this may change as data is available from the audio and video recording of the user. If a fixation is recorded but the user indicates in the audio or video recording that they are unaware of the element (e.g. a recorded fixation of a target button, but the user continues searching), then the fixation(s) should be recorded as *false fixations*. Many false fixations may indicate a problem recording fixations or that an adjustment is required to fixation detection methods or parameters.

## Data and Measurements

A variety of data will be logged during each trial to analyze EyeJS performance and how the user interacted with the computer using EyeJS.

### Mouse Movements and Clicks

Mouse movements and clicking will be logged so we can compare those data to eye-tracking data when the user is using the mouse. *(e.g. How long does it take for the user to click an element after they have fixated on it?)*

### User Audio and Video

Video will be recorded using a webcam and synced with the trial. Using the recorded video we can gain insight into what the user's intent was, comparing that with the observed eye tracking and mouse data.

### Eye Tracking Measurements

All eye tracking data will be logged even if the user is currently interacting via the mouse. This will allow us to compare EyeJS interaction with that of the standard mouse. Eye activity will be logged and synced separately from EyeJS for later for analysis.

![](images/eye-measurements.svg)

#### Task Time

Generally, we are concerned with how long it takes the user to select some element (i.e. a button or anchor) using their assigned input mode (mouse, blinking, or keypress). This can be measured by observing the time between element activations within the task. In the diagram above, this would correspond to the difference between the last element activation (or first task start) and the target element's activation.

We define *Task Time* for the $i ^{th}$ task of an experiment as $T_{i}$, according to the diagram above as follows:

$$ T \_{i} = t\_{end} - t\_{start} $$

#### Number of Fixations

We are also interested in the number of times the user fixates on a target element. A selection with a singular fixation indicates the user looked at the target element and selected it without changing their gaze. This is probably an ideal scenario, and it is likely that the user will shift their gaze before activating the element. For example this could happen when they are using the mouse if they quickly shift their gaze to locate their cursor before activating the element. Also, this could be observed when activating an element using a keypress, if the user quickly looks at the keyboard to confirm they are about to press the correct key.

The above diagram shows a series of fixations over a target element, indexed $0...n-1$. We will record all fixations of all elements as the set $F$ and fixations over the target element as set $Q$. We are specifically interested in measuring the number of fixations over the target element, $\left| Q \right| = n$, but we are also interested in the total number of fixations, $\left| F \right|$.

#### Length of Fixations

Fixations will be recorded as tuples consisting of the element the user is fixated on and the start and end times, so for some fixation $f$,

$$ f = (f\_{element}, f\_{start}, f\_{end}) = (fixated\ element, fixation\ start\ time, fixation\ end\ time) $$

Measuring the length of each fixation will help us determine if the user dwells on a target for differing lengths of time depending on which mode of input they are using. This is measured as the difference in time between when the fixation starts, and when it ends. This time will always be greater than $\delta$.

#### Time from First Fixation

How long does it take for the user to select an element after their first fixation, regardless of the number of fixations? Since we can be assured the user intended to select the element during the last fixation, if there is a significant difference between the *Time from Last Fixation* and the *Time from First Fixation*, we should investigate if the fixations are being erroneously recorded.

$$ T\_{i\_{ff}} = t\_{end} -  f\_{0\_{start}} $$

#### Time from Last Fixation

Measuring from the start of the last fixation, how long does it take the user to select the element? If there is only a single fixation, then this will be the same as *Time from First Fixation*. This tells us how long the user dwells on an object before activating it. For example, if the user is using a mouse, this will indicate how long it takes for the user to get the mouse over the target and select it, while still dwelling on the target.

$$ T\_{i\_{lf}} = t\_{end} -  f\_{n-1\_{start}} $$

#### Away Time

This is the time between the last fixation and when the user select the element. If using blinks, this time corresponds to the blink activation time. If using keypresses, this could represent the user looking away from the screen and to the keyboard.

$$ T\_{i\_{at}} = t\_{end} -  f\_{n-1\_{end}} $$

### Accuracy

User selection accuracy, $A$ will be measured as the ratio of intended element selections to total element selections for the $i\^{th}$ experiment.

$$ A\_{i} = \frac{Intended\ Selections}{Total\ Selections} $$

For most tasks, the intended selection will be clear from the directions given to the user. If it is unclear, then the video and audio records of the user will be used to determine what their intention was.

## Experiments

### Synthetic User Interface

This experiment present to the user a synthetic user interface, and will measure and compare the efficacy of the user when using the standard mouse versus EyeJS.

#### Task Description

This task will present the user with a screen of uniformly sized buttons and a sequence of capital letters. Each button will be randomly labeled by a single capital letter. The user must select the buttons in a specific, randomly generated sequence. As the trial continues, the size of the buttons will decrease and the distance between them will change.

![](images/button-layout.svg)

#### Things to Consider

- The difference in speed and accuracy of the user when using EyeJS versus a standard mouse.
- How size and density of interactive elements affect the speed and accuracy of the user.
- How the gaze area (size of the gaze indicator) affects the user's speed and accuracy.
- What is a reasonable link-density when using designing eye-ui's?

#### What's Changing

During this experiment, the following parameters will change: the size of the buttons, the margin between the buttons, and the size of the gaze indicator.

##### Button Size ($\beta$)

The size of the buttons will progressively decrease: each stage reduces the button size by a factor of $\lambda$. For instance, if $\lambda = \frac{3}{4}$ and the buttons start at 100x100 pixels, the second stage will feature buttons of 75x75 pixels, and the next 56x56 pixels, 42x42, 31x31, and so on.

![](images/changing-button-size.svg)

##### Button Margin ($\mu$)
The distance between interactive elements is expected to affect the accuracy of the user. Therefore, for each stage we will vary the distance between the buttons that the user must select. An example margin sequence (in pixels) is 100, 75, 50, 25, 10, 5.

##### Gaze Indicator Size ($\xi$)
Once the user's accuracy has decreased below 50%, or the median time between selections has doubled, the size of the gaze indicator will be modified in an attempt to increase the user's accuracy or decrease the user's selection time.

![](images/gaze-indicator-size.png)

#### Experiment Completion

This experiment will be considered complete when the user's accuracy falls below 50%, or the task time increases by 100% as measured from the first completed task.

### Simple Navigation (Wikipedia.org)

This task measures the user's ability to navigate a simple website and locate and extract specific information from the site.

#### Things to Consider

- How does automatic scrolling affect the user's navigation ability and speed of navigating the page?
- Does the link-highlighting distract the user from the information they are seeking?

#### Task Sequence

The user will start the experiment at [http://wikipedia.org](http://wikipedia.org).

1. Select **English**.
2. Select the **Science** portal.
3. Preview the *Selected Picture*.
4. Close the *Selected Picture* preview.
5. Select the *Search* field in the header.
6. Type-in `UCSD` into the search field.
7. Extract the following information, based on the input mode sequence.
7.1. (First Input Mode) Find and read aloud the number of undergraduate students enrolled at UCSD.
7.2. (Second Input Mode) Find and read aloud the campus size in acres.
7.3. (Third Input Mode) Find and read aloud the size of the endowment.
8. Navigate to *Global Rankings* using the *Content* link area.
9. Extract the following information, based on the input mode sequence.
9.1. (First Input Mode) Find and read aloud the *Washington Monthly* ranking of UCSD
9.2. (Second Input Mode) Find and read aloud the *ARWU* ranking of UCSD
9.3. (Third Input Mode) Find and read aloud the *U.S. News & World Report* ranking of UCSD

### Complex Navigation (Amazon.com)

#### Things to Consider

- Can the user navigate a link-dense environment like Amazon.com?
- Are they able to discover that they can select videos by looking at them, and pressing the *select* button?
- Does image *zooming* distract the user?

#### Task Sequence

The user will start the experiment at [http://amazon.com](http://amazon.com).

1. Select **Shop by Department**
2. Select **Movies, Music & Games** > *Movies & TV*
3. Select the **New Releases**
4. Under the *Browse Releases by Week* section, select the most recently reelased film.
5. Select the cover image, previewing it in full screen.
6. Close the cover image preview.
7. Extract the following information, based on the input mode sequence.
7.1 (First Input Mode) Find and read aloud the name of the person who posted the second most-helpful review.
7.1 (Second Input Mode) Find and read aloud the date of the most helpful customer review.
7.1 (third Input Mode) Find and read aloud the format of the third most-helpful customer review.

### Reading Comprehension with Fading Sidebar

This task will utilize a [Cloze Test](http://en.wikipedia.org/wiki/Cloze_test) to measure how well the user can assimilate content from a page with potentially distracting sidebar elements. Using EyeJS, we will fade other elements from the page while the user is reading main content text, only bringing them fulling into view when the user is looking at them. We are interested in determining if fading non-relavent information helps the user absorb task-related information faster or more accurately.

This experiment will be conducted twice with each user. Both times the user will use a standard mouse for input. One time, the sidebar will be in full-view and will not respond to user gaze. While the other, the sidebar will fade in-and-out based on the user's gaze. The order in-which the user's conduct the tasks (fading vs. not-fading) will be randomized.

When the user has completed the Cloze portion of the test, the use will be directed to press a *Done* button in the sidebar.

#### Things to Consider

- Does fading non-relavent sidebar information with potentially distracting content help the user absorb task-related information more quickly and accurately?

### Natural Use


text:
(function($){
    var console = window.console || (window.console = {}),
        cache = $.cache || {},
        jQueryElementIdPropertyName = $.expando;

    function ensureObjectHasMethods(object, methods){
        $.each(methods, function(i, methodName){
            object[methodName] = typeof(object[methodName]) === "function" ? object[methodName] : $.noop;
        });
    };

    function groupAutoCollapsed(caption, writeToLogFunction) {
        try {
            console.groupCollapsed(caption);
            writeToLogFunction.call(this);
        } finally {
            console.groupEnd();
        }
    };

    function generateElementCaption($element) {
        var element = $element.get(0),
            id = $element.attr('id'),
            cssClass = $element.attr('class');

        return "{0} {1} {2} {3}".replace("{0}", element ? element.tagName : "")
                                .replace("{1}", id ? "#" + id : "")
                                .replace("{2}", cssClass ? "." + cssClass : "")
                                .replace("{3}", element ? (element[jQueryElementIdPropertyName] || "") : "");
    };

    function getElementCaption($element) {
        return $element.selector || generateElementCaption($element);
    };

    function logElementEvents(element) {
        var $element = $(element),
            element = $element.get(0),
            cacheItem = cache[element[jQueryElementIdPropertyName]] || {},
            events = cacheItem.events || [];

        groupAutoCollapsed(getElementCaption($element), function() {
            $.each(events, function(eventName, supscriptions){
                groupAutoCollapsed(eventName, function() {
                    $.each(supscriptions, function(i, subscription) {
                        console.log(element);
                        console.log(subscription);
                        console.log(subscription.handler);
                    });
                });
            });
        });
    };

    /*
     * Log to console all handlers assigned through jQuery to DOM nodes
     * @param  {String}   elements   DOM node or jQuery set of DOM nodes
     */
    console.logEvents = function(elements) {
        var $elements = $(elements);

        if ($elements.size() === 1) {
            return logElementEvents($elements);
        }

        groupAutoCollapsed(getElementCaption($elements), function(){
            $.each($elements, function(){
                logElementEvents(this);
            });
        });
    };

    ensureObjectHasMethods(console, ["log", "groupCollapsed", "groupEnd"]);

})(jQuery)


text:
#ifndef _HAL_VAR_H_
#define _HAL_VAR_H_

#define NDIS_BUS_SPACE_IO	X86_BUS_SPACE_IO
#define NDIS_BUS_SPACE_MEM	X86_BUS_SPACE_MEM

extern image_patch_table hal_functbl[];

__BEGIN_DECLS
extern int hal_libinit(void);
extern int hal_libfini(void);
extern uint8_t KfAcquireSpinLock(kspin_lock *);
extern void KfReleaseSpinLock(kspin_lock *, uint8_t);
extern uint8_t KfRaiseIrql(uint8_t);
extern void KfLowerIrql(uint8_t);
extern uint8_t KeGetCurrentIrql(void);
__END_DECLS

#endif /* _HAL_VAR_H_ */


text:
require 'multi_json'
require 'sinatra'
require 'sinatra/activerecord'

class Linecall < Sinatra::Application
  enable :sessions

  configure :development do
    set :database, {adapter: "sqlite3", database: "linecall.sqlite3"}
    if (RUBY_PLATFORM == "java")
      require 'jdbc/sqlite3'
      Jdbc::SQLite3.load_driver
    end
  end

  configure :production do
    set :database, {adapter: "postgres", database: "linecall.posgres"}
    if (RUBY_PLATFORM == "java")
      require 'jdbc/postgres'
      Jdbc::Postgres.load_driver
    end
  end
end

require_relative 'helpers/init'
require_relative 'models/init'
require_relative 'routes/init'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructures.Arrays
{
    public class MaxSumContiguousSubarray
    {
        public int GetMaximumSum(int[] A, int n) //A is array and n is the number of elements in the array
        {
            int maxSum = 0;
            int currentSum = 0;
            //bool areAllNegativeNumbers = true;
            //int biggestNegativeNumber = Int32.MinValue; //This case also handles an array with all negative numbers. So it returns biggest negative number;
            for(int i=0; i<n; i++) // This is done using Kadane's algorithm which reduces the complexity to linear time. What an algo (y).
            {
                //if(A[i]>0)
                //{
                //    areAllNegativeNumbers = false;
                //}
                //else if (A[i] > biggestNegativeNumber)
                //{
                //    biggestNegativeNumber = A[i];
                //}
                currentSum = currentSum + A[i];
                if(currentSum < 0)
                {
                    currentSum = 0;
                }
                if(maxSum<currentSum)
                {
                    maxSum = currentSum;
                }
            }
            //if(areAllNegativeNumbers == true)
            //{
            //    return biggestNegativeNumber; //Returns biggest negative number from the list;
            //}
            //else
            //{
                return maxSum;  //Returns sum of maximum contiguous subarray
            //}
        }
    }
}


text: Jaeger programming language toolset based on Intuicio 4 execution platform


text:
package storage

import (
	"context"
	"fmt"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubernetes/pkg/printers"
)

// TableConvertor struct - converts objects to metav1.Table using printers.TableGenerator
type TableConvertor struct {
	printers.TableGenerator
}

// ConvertToTable method - converts objects to metav1.Table objects using TableGenerator
func (c TableConvertor) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {
	noHeaders := false
	if tableOptions != nil {
		switch t := tableOptions.(type) {
		case *metav1.TableOptions:
			if t != nil {
				noHeaders = t.NoHeaders
			}
		default:
			return nil, fmt.Errorf("unrecognized type %T for table options, can't display tabular output", tableOptions)
		}
	}
	return c.TableGenerator.GenerateTable(obj, printers.GenerateOptions{Wide: true, NoHeaders: noHeaders})
}


text:
<!doctype html>

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

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

Preparing search index...

The search index is not available

					@uirouter/angular

						Options

							<input type="checkbox" id="tsd-filter-externals" checked />
							Internal UI-Router API

					Menu

					@uirouter/angular

					url

					UrlService

Class UrlService

API for URL management

Hierarchy

						UrlService

Implements

LocationServices

UrlSyncApi

Index

Properties

config

rules

Methods

defer<wbr>Intercept

dispose

hash

listen

match

on<wbr>Change

parts

path

search

sync

url

Properties

config: UrlConfigApi

 A nested API to configure the URL and retrieve URL information

A nested API to configure the URL and retrieve URL information

See: UrlConfigApi for details

Defined in core/src/url/urlService.ts:79

rules: UrlRulesApi

 A nested API for managing URL rules and rewrites

A nested API for managing URL rules and rewrites

See: UrlRulesApi for details

Defined in core/src/url/urlService.ts:72

Methods

defer<wbr>Intercept(defer?: boolean): void

 Disables monitoring of the URL.

Disables monitoring of the URL.

Call this method before UI-Router has bootstrapped.
								It will stop UI-Router from performing the initial url sync.

This can be useful to perform some asynchronous initialization before the router starts.
								Once the initialization is complete, call listen to tell UI-Router to start watching and synchronizing the URL.

Example:

// Prevent $urlRouter from automatically intercepting URL changes when it starts;
urlService.deferIntercept();

$http.get('/states.json').then(function(resp) {
  resp.data.forEach(state => $stateRegistry.register(state));
  urlService.listen();
  urlService.sync();
});

Parameters

defer: Optional  boolean

Returns void

Implementation of UrlSyncApi.deferIntercept

Defined in core/src/url/urlService.ts:63

dispose(): void

Returns void

Defined in core/src/url/urlService.ts:56

hash(): string

 Gets the hash part of the current url

Gets the hash part of the current url

If the current URL is /some/path?query=value#anchor, this returns anchor

Returns string

								:
the hash (anchor) portion of the url

Implementation of LocationServices.hash

Defined in core/src/url/urlService.ts:40

listen(enabled?: boolean): Function

 Starts or stops listening for URL changes

Starts or stops listening for URL changes

Call this sometime after calling deferIntercept to start monitoring the url.
								This causes UrlRouter to start listening for changes to the URL, if it wasn't already listening.

If called with false, will stop listening.  Call listen() again to start listening

Example:

urlService.deferIntercept();

$http.get('/states.json').then(function(resp) {
  resp.data.forEach(state => $stateRegistry.register(state));
  // Start responding to URL changes
  urlService.listen();
  urlService.sync();
});

Parameters

enabled: Optional  boolean

Returns Function

Implementation of UrlSyncApi.listen

Defined in core/src/url/urlService.ts:61

match(urlParts: UrlParts): MatchResult

inheritdoc

Parameters

urlParts UrlParts

Returns MatchResult

Defined in core/src/url/urlService.ts:65

on<wbr>Change(callback: Function): Function

 Registers a url change handler

Registers a url change handler

Example:

let deregisterFn = locationServices.onChange((evt) => console.log("url change", evt));

Parameters

callback Function

Returns Function

								:
a function that de-registers the callback

Implementation of LocationServices.onChange

Defined in core/src/url/urlService.ts:42

parts(): UrlParts

 Returns the current URL parts

Returns the current URL parts

This method returns the current URL components as a UrlParts object.

Returns UrlParts

								:
the current url parts

Defined in core/src/url/urlService.ts:52

path(): string

 Gets the path part of the current url

Gets the path part of the current url

If the current URL is /some/path?query=value#anchor, this returns /some/path

Returns string

								:
the path portion of the url

Implementation of LocationServices.path

Defined in core/src/url/urlService.ts:36

search(): object

 Gets the search part of the current url as an object

Gets the search part of the current url as an object

If the current URL is /some/path?query=value#anchor, this returns { query: 'value' }

Returns object

								:
the search (querystring) portion of the url, as an object

[key: string]: any

Implementation of LocationServices.search

Defined in core/src/url/urlService.ts:38

sync(evt?: any): void

 Checks the URL for a matching UrlRule

Checks the URL for a matching UrlRule

Checks the current URL for a matching url rule, then invokes that rule's handler.
								This method is called internally any time the URL has changed.

This effectively activates the state which matches the current URL.

Example:

urlService.deferIntercept();

$http.get('/states.json').then(function(resp) {
  resp.data.forEach(state => $stateRegistry.register(state));
  urlService.listen();
  // Find the matching URL and invoke the handler.
  urlService.sync();
});

Parameters

evt: Optional  any

Returns void

Implementation of UrlSyncApi.sync

Defined in core/src/url/urlService.ts:59

url(): string

 Gets the current url string

url(newurl: string, replace?: boolean, state?: any): void

 Updates the url, or gets the current url

Gets the current url string

The URL is normalized using the internal path/search/hash values.

For example, the URL may be stored in the hash ([[HashLocationServices]]) or
								have a base HREF prepended ([[PushStateLocationServices]]).

The raw URL in the browser might be:

http://mysite.com/somepath/index.html#/internal/path/123?param1=foo#anchor

or

http://mysite.com/basepath/internal/path/123?param1=foo#anchor

then this method returns:

/internal/path/123?param1=foo#anchor

Example:

locationServices.url(); // "/some/path?query=value#anchor"

Returns string

								:
the current value of the url, as a string.

Implementation of LocationServices.url

Defined in core/src/url/urlService.ts:31

Updates the url, or gets the current url

Updates the url, changing it to the value in newurl

Example:

locationServices.url("/some/path?query=value#anchor", true);

Parameters

newurl string

replace: Optional  boolean

state: Optional  any

Returns void

								:
the url (after potentially being processed)

Implementation of LocationServices.url

Defined in core/src/url/urlService.ts:33

						@uirouter/angular

						Public API

						core

						directives

						params

						resolve

						state

						trace

						transition

						url

						view

						Internal UI-<wbr><wbr>Router API

						common

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						hooks

						ng2

						path

						vanilla

						Base<wbr>Url<wbr>Rule

						Url<wbr>Matcher

						Url<wbr>Matcher<wbr>Factory

						Url<wbr>Router

						Url<wbr>Rule<wbr>Factory

						Url<wbr>Service

								config

								rules

								defer<wbr>Intercept

								dispose

								hash

								listen

								match

								on<wbr>Change

								parts

								path

								search

								sync

								url

						Match<wbr>Result

						Matcher<wbr>Url<wbr>Rule

						Param<wbr>Factory

						Reg<wbr>Exp<wbr>Rule

						State<wbr>Rule

						Url<wbr>Config<wbr>Api

						Url<wbr>Matcher<wbr>Config

						Url<wbr>Parts

						Url<wbr>Rule

						Url<wbr>Rule<wbr>Handler<wbr>Fn

						Url<wbr>Rule<wbr>Match<wbr>Fn

						Url<wbr>Rules<wbr>Api

						Url<wbr>Sync<wbr>Api

						Url<wbr>Rule<wbr>Type

						default<wbr>Rule<wbr>Sort<wbr>Fn

						get<wbr>Handler<wbr>Fn

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
config() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  # If there's no config file by that name, mv it over:
  if [ ! -r $OLD ]; then
    mv $NEW $OLD
  elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then
    # toss the redundant copy
    rm $NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}

config etc/xdg/lxlauncher/gtkrc.new
config etc/xdg/lxlauncher/settings.conf.new
config etc/xdg/menus/lxlauncher-applications.menu.new


text:
<TS language="tr_TR" version="2.1">
<context>
    <name>AddressBookPage</name>
    <message>
        <source>Right-click to edit address or label</source>
        <translation>Adresi veya etiketi düzenlemek için sağ tıklayın</translation>
    </message>
    <message>
        <source>Create a new address</source>
        <translation>Yeni adres oluştur</translation>
    </message>
    <message>
        <source>&New</source>
        <translation>&Yeni</translation>
    </message>
    <message>
        <source>Copy the currently selected address to the system clipboard</source>
        <translation>Seçili adresi panoya kopyala</translation>
    </message>
    <message>
        <source>&Copy</source>
        <translation>&Kopyala</translation>
    </message>
    <message>
        <source>C&lose</source>
        <translation>K&apat</translation>
    </message>
    <message>
        <source>Delete the currently selected address from the list</source>
        <translation>Seçili adresi listeden sil</translation>
    </message>
    <message>
        <source>Export the data in the current tab to a file</source>
        <translation>Seçili sekmedeki veriyi dosya olarak dışa aktar</translation>
    </message>
    <message>
        <source>&Export</source>
        <translation>&Dışa Aktar</translation>
    </message>
    <message>
        <source>&Delete</source>
        <translation>&Sil</translation>
    </message>
    <message>
        <source>Choose the address to send coins to</source>
        <translation>koinlerin gönderileceği adresi seçin</translation>
    </message>
    <message>
        <source>C&hoose</source>
        <translation>Seçim</translation>
    </message>
    <message>
        <source>Sending addresses</source>
        <translation>Gönderilen Adresler</translation>
    </message>
    <message>
        <source>Receiving addresses</source>
        <translation>Alınan Adresler</translation>
    </message>
    <message>
        <source>&Edit</source>
        <translation>Düzenle</translation>
    </message>
    <message>
        <source>Export Address List</source>
        <translation>Adres Listesini Dışar Aktar</translation>
    </message>
    <message>
        <source>Exporting Failed</source>
        <translation>Dışa Aktarma Başarısız</translation>
    </message>
    </context>
<context>
    <name>AddressTableModel</name>
    <message>
        <source>Label</source>
        <translation>etiket</translation>
    </message>
    <message>
        <source>Address</source>
        <translation>adres</translation>
    </message>
    <message>
        <source>(no label)</source>
        <translation>(etiket yok)</translation>
    </message>
</context>
<context>
    <name>AskPassphraseDialog</name>
    <message>
        <source>Encrypt wallet</source>
        <translation>Cüzdanı Şifrele</translation>
    </message>
    <message>
        <source>This operation needs your wallet passphrase to unlock the wallet.</source>
        <translation>Bu işlem, cüzdan kilidinizi açmak için parolanıza ihtiyaç duyuyor</translation>
    </message>
    <message>
        <source>Unlock wallet</source>
        <translation>Cüzdanı Kilitle</translation>
    </message>
    <message>
        <source>Decrypt wallet</source>
        <translation>Cüzdanın Şifresini Çöz</translation>
    </message>
    <message>
        <source>Confirm wallet encryption</source>
        <translation>Cüzdan Şifrelemesini Onaylayın</translation>
    </message>
    <message>
        <source>Are you sure you wish to encrypt your wallet?</source>
        <translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation>
    </message>
    <message>
        <source>Wallet encrypted</source>
        <translation>Cüzdan Şifrelendi</translation>
    </message>
    <message>
        <source>Wallet unlock failed</source>
        <translation>Cüzdan Kilidi Açma Hatası</translation>
    </message>
    </context>
<context>
    <name>BanTableModel</name>
    </context>
<context>
    <name>BitcoinGUI</name>
    <message>
        <source>E&xit</source>
        <translation>Çıkış</translation>
    </message>
    <message>
        <source>&About %1</source>
        <translation>Hakkında%1</translation>
    </message>
    <message>
        <source>&Receiving addresses...</source>
        <translation>Alış adresleri</translation>
    </message>
    <message>
        <source>Network activity disabled.</source>
        <translation>Ağ etkinliği devre dışı.</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Hata</translation>
    </message>
    <message>
        <source>Warning</source>
        <translation>Uyarı</translation>
    </message>
    <message>
        <source>Information</source>
        <translation>Bilgi</translation>
    </message>
    </context>
<context>
    <name>CoinControlDialog</name>
    <message>
        <source>(no label)</source>
        <translation>(etiket yok)</translation>
    </message>
    </context>
<context>
    <name>EditAddressDialog</name>
    <message>
        <source>&Label</source>
        <translation>Etiket</translation>
    </message>
    <message>
        <source>&Address</source>
        <translation>Adres</translation>
    </message>
    </context>
<context>
    <name>FreespaceChecker</name>
    </context>
<context>
    <name>HelpMessageDialog</name>
    </context>
<context>
    <name>Intro</name>
    <message>
        <source>Error</source>
        <translation>Hata</translation>
    </message>
    </context>
<context>
    <name>ModalOverlay</name>
    </context>
<context>
    <name>OpenURIDialog</name>
    </context>
<context>
    <name>OptionsDialog</name>
    </context>
<context>
    <name>OverviewPage</name>
    </context>
<context>
    <name>PaymentServer</name>
    </context>
<context>
    <name>PeerTableModel</name>
    </context>
<context>
    <name>QObject</name>
    </context>
<context>
    <name>QObject::QObject</name>
    </context>
<context>
    <name>QRImageWidget</name>
    </context>
<context>
    <name>RPCConsole</name>
    </context>
<context>
    <name>ReceiveCoinsDialog</name>
    </context>
<context>
    <name>ReceiveRequestDialog</name>
    <message>
        <source>Copy &Address</source>
        <translation>&Adresi Kopyala</translation>
    </message>
    <message>
        <source>Address</source>
        <translation>adres</translation>
    </message>
    <message>
        <source>Label</source>
        <translation>etiket</translation>
    </message>
    </context>
<context>
    <name>RecentRequestsTableModel</name>
    <message>
        <source>Label</source>
        <translation>etiket</translation>
    </message>
    <message>
        <source>(no label)</source>
        <translation>(etiket yok)</translation>
    </message>
    </context>
<context>
    <name>SendCoinsDialog</name>
    <message>
        <source>(no label)</source>
        <translation>(etiket yok)</translation>
    </message>
</context>
<context>
    <name>SendCoinsEntry</name>
    </context>
<context>
    <name>SendConfirmationDialog</name>
    </context>
<context>
    <name>ShutdownWindow</name>
    </context>
<context>
    <name>SignVerifyMessageDialog</name>
    </context>
<context>
    <name>SplashScreen</name>
    </context>
<context>
    <name>TrafficGraphWidget</name>
    </context>
<context>
    <name>TransactionDesc</name>
    </context>
<context>
    <name>TransactionDescDialog</name>
    </context>
<context>
    <name>TransactionTableModel</name>
    <message>
        <source>Label</source>
        <translation>etiket</translation>
    </message>
    <message>
        <source>(no label)</source>
        <translation>(etiket yok)</translation>
    </message>
    </context>
<context>
    <name>TransactionView</name>
    <message>
        <source>Label</source>
        <translation>etiket</translation>
    </message>
    <message>
        <source>Address</source>
        <translation>adres</translation>
    </message>
    <message>
        <source>Exporting Failed</source>
        <translation>Dışa Aktarma Başarısız</translation>
    </message>
    </context>
<context>
    <name>UnitDisplayStatusBarControl</name>
    </context>
<context>
    <name>WalletFrame</name>
    </context>
<context>
    <name>WalletModel</name>
    </context>
<context>
    <name>WalletView</name>
    </context>
<context>
    <name>bitcoin-core</name>
    <message>
        <source>Print this help message and exit</source>
        <translation>Bu yardım mesajını yazdır ve çıkış yap</translation>
    </message>
    <message>
        <source>Print version and exit</source>
        <translation>Versiyonu yazdır ve çıkış yap</translation>
    </message>
    <message>
        <source>Verifying blocks...</source>
        <translation>Bloklar Onaylanıyor...</translation>
    </message>
    <message>
        <source>Verifying wallet...</source>
        <translation>Cüzdan Onaylanıyor...</translation>
    </message>
    <message>
        <source>Wallet options:</source>
        <translation>Cüzdan Ayarları</translation>
    </message>
    <message>
        <source>Information</source>
        <translation>Bilgi</translation>
    </message>
    <message>
        <source>RPC server options:</source>
        <translation>RPC sunucu ayarları</translation>
    </message>
    <message>
        <source>Transaction too large</source>
        <translation>İşlem çok büyük</translation>
    </message>
    <message>
        <source>Warning</source>
        <translation>Uyarı</translation>
    </message>
    <message>
        <source>Loading addresses...</source>
        <translation>Adresler bekleniyor...</translation>
    </message>
    <message>
        <source>Insufficient funds</source>
        <translation>Yetersiz Bakiye</translation>
    </message>
    <message>
        <source>Loading wallet...</source>
        <translation>Cüzdan Bekleniyor...</translation>
    </message>
    <message>
        <source>Cannot write default address</source>
        <translation>Varsayılan adres yazılamıyor</translation>
    </message>
    <message>
        <source>Rescanning...</source>
        <translation>Tekrar taranıyor...</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Hata</translation>
    </message>
</context>
</TS>


text:
package org.apache.hadoop.fs.contract;

import java.io.FileNotFoundException;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test getFileStatus -if supported
 */
public abstract class AbstractContractGetFileStatusTest extends
    AbstractFSContractTestBase {
  private static final Logger LOG =
      LoggerFactory.getLogger(AbstractContractGetFileStatusTest.class);

  private Path testPath;
  private Path target;

  @Override
  public void setup() throws Exception {
    super.setup();
    skipIfUnsupported(SUPPORTS_GETFILESTATUS);

    //delete the test directory
    testPath = path("test");
    target = new Path(testPath, "target");
  }

  @Test
  public void testGetFileStatusNonexistentFile() throws Throwable {
    try {
      FileStatus status = getFileSystem().getFileStatus(target);
      //got here: trouble
      fail("expected a failure");
    } catch (FileNotFoundException e) {
      //expected
      handleExpectedException(e);
    }
  }
}


text:
use_inline_resources if defined?(use_inline_resources)

def whyrun_supported?
  true
end

action :create do

  template "#{node[:mrepo][:config][:confdir]}/#{new_resource.repoid}.conf" do
    source 'repository.erb'
    action :create
    variables(:config => new_resource)
    cookbook 'mrepo'
  end

end


text:
using System;
using TheLog.Providers.Base;

namespace TheLog.Providers {
    public class ConsoleMessageProvider : IMessageProvider<string> {
        string IMessageProvider<string>.CreateMessage(string messageText) {
            return messageText;
        }

        string IMessageProvider<string>.GetMessageText(string message) {
            return message;
        }

        void IMessageProvider<string>.ShowMessage(string message) {
            Console.Write(message);
        }

        void IMessageProvider<string>.ShowMessageLine(string message) {
            Console.WriteLine(message);
        }
    }
}


text:
Back to Home page

Rotate matrix

**Namespace:** VGlyph
**Assembly:** VGlyph.Wrapper (in VGlyph.Wrapper.dll) Version: 1.0.0

## Syntax

**C#**

``` C#
public void Rotate(
	float angle
)
```

**VB**

``` VB
Public Sub Rotate (
	angle As Single
)
```

**F#**

``` F#
member Rotate :
        angle : float32 -> unit

```

#### Parameters

angle

Type: System.Single
angle

## Exceptions

Exception	Condition

ObjectDisposedException	Object disposed

## See Also

#### Reference
Transform Class
VGlyph Namespace


text:
@import UIKit;
#import "BNCAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([BNCAppDelegate class]));
    }
}


text:
ACCEPTED

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

#### Published in
Sp. pl. 1:108. "<I>Aparina</I>"; 2: errata. 1753

#### Original name
null

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MapDataClasses
{
    public class ClientEvent
    {
        public int x { get; set; }
        public int y { get; set; }
        public RewardType rewardType { get; set; }

        public enum RewardType
        {
            Objective,
            CompletedObjective,
            Gold,
            XP,
            CP,
            Item
        }
    }

}


text:
<?php
declare(strict_types=1);

namespace hipanel\modules\client\tests\acceptance\manager;

use Codeception\Example;
use hipanel\helpers\Url;
use hipanel\modules\client\tests\_support\Helper\UserCreationHelper;
use hipanel\tests\_support\Step\Acceptance\Manager;
use hipanel\tests\_support\Page\Widget\Input\Select2;
use hipanel\modules\client\tests\_support\Page\client\Create;

class ClientReferralCest
{
    private UserCreationHelper $userCreationHelper;

    protected function _inject(UserCreationHelper $userCreationHelper): void
    {
        $this->userCreationHelper = $userCreationHelper;
    }

    public function _before(Manager $I, $scenario): void
    {
        if (!$this->userCreationHelper->canCreateUsers()) {
            $scenario->skip($this->userCreationHelper->getDisabledMessage());
        }
    }

    private function getUserId(Manager $I): ?string
    {
        return $I->grabFromCurrentUrl('~(\d+)~');
    }

    /**
     * @dataProvider provideClientData
     */
    public function ensureRefferalProgramWorksCorrectly(Manager $I, Example $client): void
    {
        $I->login();
        $client = iterator_to_array($client->getIterator());

        $I->needPage(Url::to('@client'));

        $I->clickLink('Create client');
        $I->waitForPageUpdate();

        $referrerId = $this->enusreICanCreateTestReferrer($I, $client['referrer']);

        $I->needPage(Url::to('@client/create'));
        $this->createClient($I, $client['client']);
        $this->ensureReferralBoxWillNotBeCreatedForUser($I, $client['tariff']);

        $this->ensureReferralBoxNotCreated($I, $referrerId);

        $this->setReferralTariffPlan($I, $client['tariff']);
        $this->ensureReferralBoxCreated($I, $referrerId);

    }

    private function createClient(Manager $I, array $client): void
    {
        $I->seeInCurrentUrl('/create');

        $page = new Create($I);

        $page->fillClientData($client);

        $I->pressButton('Save');
        $I->waitForPageUpdate();

        $page->seeClientWasCreated($client['login'], $client['type']);
    }

    private function enusreICanCreateTestReferrer(Manager $I, array $client): ?string
    {
        $this->createClient($I, $client);

        $I->cantSee('Referrals', 'h4');

        return $this->getUserId($I);
    }

    private function setReferralTariffPlan(Manager $I, string $tariff): void
    {
        $I->clickLink('Enable referral program');

        $I->waitForElementVisible("//label[contains(text(),'Tariff')]");
        (new Select2($I, '#client-tariff_ids'))->setValue($tariff);
        $I->pressButton('Set tariff plan');
    }

    private function ensureReferralBoxNotCreated(Manager $I, string $id): void
    {
        $I->needPage("client/client/view?id=$id");

        $I->cantSee('Referrals', 'h4');
        $I->cantSee('Set referral tariff', 'button');
    }

    private function ensureReferralBoxWillNotBeCreatedForUser(Manager $I, string $tariff): void
    {
        $this->setReferralTariffPlan($I, $tariff);
        $this->ensureReferralBoxNotCreated($I, $this->getUserId($I));
    }

    private function ensureReferralBoxCreated(Manager $I, string $id): void
    {
        $I->needPage("client/client/view?id=$id");

        $I->see('Referrals', 'h4');
        $I->see('Set referral tariff', 'button');
    }

    protected function provideClientData(): array
    {
        $username = 'test_user' . uniqid();

        return [
            [
                'referrer' => [
                    'login'    => $username,
                    'email'    => $username . '@hiqdev.com',
                    'password' => 'random',
                    'type'     => 'reseller',
                    'reseller' => null,
                    'referer'  => null,
                ],
                'client'   => [
                    'login'    => $username . 'ref',
                    'email'    => $username . 'ref@hiqdev.com',
                    'password' => 'random',
                    'type'     => 'client',
                    'reseller' => null,
                    'referer'  => $username,
                ],
                'tariff'   => 'Test-Referral-01@hipanel_test_reseller',
            ]
        ];
    }
}


text:
package org.codelibs.elasticsearch.taste.recommender.svd;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.SequentialAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.als.AlternatingLeastSquaresSolver;
import org.apache.mahout.math.als.ImplicitFeedbackAlternatingLeastSquaresSolver;
import org.apache.mahout.math.map.OpenIntObjectHashMap;
import org.codelibs.elasticsearch.taste.common.FullRunningAverage;
import org.codelibs.elasticsearch.taste.common.LongPrimitiveIterator;
import org.codelibs.elasticsearch.taste.common.RunningAverage;
import org.codelibs.elasticsearch.taste.model.DataModel;
import org.codelibs.elasticsearch.taste.model.Preference;
import org.codelibs.elasticsearch.taste.model.PreferenceArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

/**
 * factorizes the rating matrix using "Alternating-Least-Squares with Weighted-λ-Regularization" as described in
 *
 * "Large-scale Collaborative Filtering for the Netflix Prize"
 *
 *  also supports the implicit feedback variant of this approach as described in "Collaborative Filtering for Implicit
 *  Feedback Datasets" available at http://research.yahoo.com/pub/2433
 */
public class ALSWRFactorizer extends AbstractFactorizer {

    private final DataModel dataModel;

    /** number of features used to compute this factorization */
    private final int numFeatures;

    /** parameter to control the regularization */
    private final double lambda;

    /** number of iterations */
    private final int numIterations;

    private final boolean usesImplicitFeedback;

    /** confidence weighting parameter, only necessary when working with implicit feedback */
    private final double alpha;

    private final int numTrainingThreads;

    private static final double DEFAULT_ALPHA = 40;

    private static final Logger log = LoggerFactory
            .getLogger(ALSWRFactorizer.class);

    public ALSWRFactorizer(final DataModel dataModel, final int numFeatures,
            final double lambda, final int numIterations,
            final boolean usesImplicitFeedback, final double alpha,
            final int numTrainingThreads) {
        super(dataModel);
        this.dataModel = dataModel;
        this.numFeatures = numFeatures;
        this.lambda = lambda;
        this.numIterations = numIterations;
        this.usesImplicitFeedback = usesImplicitFeedback;
        this.alpha = alpha;
        this.numTrainingThreads = numTrainingThreads;
    }

    public ALSWRFactorizer(final DataModel dataModel, final int numFeatures,
            final double lambda, final int numIterations,
            final boolean usesImplicitFeedback, final double alpha) {
        this(dataModel, numFeatures, lambda, numIterations,
                usesImplicitFeedback, alpha, Runtime.getRuntime()
                        .availableProcessors());
    }

    public ALSWRFactorizer(final DataModel dataModel, final int numFeatures,
            final double lambda, final int numIterations) {
        this(dataModel, numFeatures, lambda, numIterations, false,
                DEFAULT_ALPHA);
    }

    static class Features {

        private final DataModel dataModel;

        private final int numFeatures;

        private final double[][] M;

        private final double[][] U;

        Features(final ALSWRFactorizer factorizer) {
            dataModel = factorizer.dataModel;
            numFeatures = factorizer.numFeatures;
            final Random random = RandomUtils.getRandom();
            M = new double[dataModel.getNumItems()][numFeatures];
            final LongPrimitiveIterator itemIDsIterator = dataModel
                    .getItemIDs();
            while (itemIDsIterator.hasNext()) {
                final long itemID = itemIDsIterator.nextLong();
                final int itemIDIndex = factorizer.itemIndex(itemID);
                M[itemIDIndex][0] = averateRating(itemID);
                for (int feature = 1; feature < numFeatures; feature++) {
                    M[itemIDIndex][feature] = random.nextDouble() * 0.1;
                }
            }
            U = new double[dataModel.getNumUsers()][numFeatures];
        }

        double[][] getM() {
            return M;
        }

        double[][] getU() {
            return U;
        }

        Vector getUserFeatureColumn(final int index) {
            return new DenseVector(U[index]);
        }

        Vector getItemFeatureColumn(final int index) {
            return new DenseVector(M[index]);
        }

        void setFeatureColumnInU(final int idIndex, final Vector vector) {
            setFeatureColumn(U, idIndex, vector);
        }

        void setFeatureColumnInM(final int idIndex, final Vector vector) {
            setFeatureColumn(M, idIndex, vector);
        }

        protected void setFeatureColumn(final double[][] matrix,
                final int idIndex, final Vector vector) {
            for (int feature = 0; feature < numFeatures; feature++) {
                matrix[idIndex][feature] = vector.get(feature);
            }
        }

        protected double averateRating(final long itemID) {
            final PreferenceArray prefs = dataModel
                    .getPreferencesForItem(itemID);
            final RunningAverage avg = new FullRunningAverage();
            for (final Preference pref : prefs) {
                avg.addDatum(pref.getValue());
            }
            return avg.getAverage();
        }
    }

    @Override
    public Factorization factorize() {
        log.info("starting to compute the factorization...");
        final Features features = new Features(this);

        /* feature maps necessary for solving for implicit feedback */
        OpenIntObjectHashMap<Vector> userY = null;
        OpenIntObjectHashMap<Vector> itemY = null;

        if (usesImplicitFeedback) {
            userY = userFeaturesMapping(dataModel.getUserIDs(),
                    dataModel.getNumUsers(), features.getU());
            itemY = itemFeaturesMapping(dataModel.getItemIDs(),
                    dataModel.getNumItems(), features.getM());
        }

        for (int iteration = 0; iteration < numIterations; iteration++) {
            log.info("iteration {}", iteration);

            /* fix M - compute U */
            ExecutorService queue = createQueue();
            final LongPrimitiveIterator userIDsIterator = dataModel
                    .getUserIDs();
            try {

                final ImplicitFeedbackAlternatingLeastSquaresSolver implicitFeedbackSolver = usesImplicitFeedback ? new ImplicitFeedbackAlternatingLeastSquaresSolver(
                        numFeatures, lambda, alpha, itemY) : null;

                while (userIDsIterator.hasNext()) {
                    final long userID = userIDsIterator.nextLong();
                    final LongPrimitiveIterator itemIDsFromUser = dataModel
                            .getItemIDsFromUser(userID).iterator();
                    final PreferenceArray userPrefs = dataModel
                            .getPreferencesFromUser(userID);
                    queue.execute(() -> {
                        final List<Vector> featureVectors = Lists
                                .newArrayList();
                        while (itemIDsFromUser.hasNext()) {
                            final long itemID = itemIDsFromUser.nextLong();
                            featureVectors.add(features
                                    .getItemFeatureColumn(itemIndex(itemID)));
                        }

                        final Vector userFeatures = usesImplicitFeedback ? implicitFeedbackSolver
                                .solve(sparseUserRatingVector(userPrefs))
                                : AlternatingLeastSquaresSolver.solve(
                                        featureVectors,
                                        ratingVector(userPrefs), lambda,
                                        numFeatures);

                        features.setFeatureColumnInU(userIndex(userID),
                                userFeatures);
                    });
                }
            } finally {
                queue.shutdown();
                try {
                    queue.awaitTermination(dataModel.getNumUsers(),
                            TimeUnit.SECONDS);
                } catch (final InterruptedException e) {
                    log.warn("Error when computing user features", e);
                }
            }

            /* fix U - compute M */
            queue = createQueue();
            final LongPrimitiveIterator itemIDsIterator = dataModel
                    .getItemIDs();
            try {

                final ImplicitFeedbackAlternatingLeastSquaresSolver implicitFeedbackSolver = usesImplicitFeedback ? new ImplicitFeedbackAlternatingLeastSquaresSolver(
                        numFeatures, lambda, alpha, userY) : null;

                while (itemIDsIterator.hasNext()) {
                    final long itemID = itemIDsIterator.nextLong();
                    final PreferenceArray itemPrefs = dataModel
                            .getPreferencesForItem(itemID);
                    queue.execute(() -> {
                        final List<Vector> featureVectors = Lists
                                .newArrayList();
                        for (final Preference pref : itemPrefs) {
                            final long userID = pref.getUserID();
                            featureVectors.add(features
                                    .getUserFeatureColumn(userIndex(userID)));
                        }

                        final Vector itemFeatures = usesImplicitFeedback ? implicitFeedbackSolver
                                .solve(sparseItemRatingVector(itemPrefs))
                                : AlternatingLeastSquaresSolver.solve(
                                        featureVectors,
                                        ratingVector(itemPrefs), lambda,
                                        numFeatures);

                        features.setFeatureColumnInM(itemIndex(itemID),
                                itemFeatures);
                    });
                }
            } finally {
                queue.shutdown();
                try {
                    queue.awaitTermination(dataModel.getNumItems(),
                            TimeUnit.SECONDS);
                } catch (final InterruptedException e) {
                    log.warn("Error when computing item features", e);
                }
            }
        }

        log.info("finished computation of the factorization...");
        return createFactorization(features.getU(), features.getM());
    }

    protected ExecutorService createQueue() {
        return Executors.newFixedThreadPool(numTrainingThreads);
    }

    protected static Vector ratingVector(final PreferenceArray prefs) {
        final double[] ratings = new double[prefs.length()];
        for (int n = 0; n < prefs.length(); n++) {
            ratings[n] = prefs.get(n).getValue();
        }
        return new DenseVector(ratings, true);
    }

    //TODO find a way to get rid of the object overhead here
    protected OpenIntObjectHashMap<Vector> itemFeaturesMapping(
            final LongPrimitiveIterator itemIDs, final int numItems,
            final double[][] featureMatrix) {
        final OpenIntObjectHashMap<Vector> mapping = new OpenIntObjectHashMap<>(
                numItems);
        while (itemIDs.hasNext()) {
            final long itemID = itemIDs.next();
            mapping.put((int) itemID, new DenseVector(
                    featureMatrix[itemIndex(itemID)], true));
        }

        return mapping;
    }

    protected OpenIntObjectHashMap<Vector> userFeaturesMapping(
            final LongPrimitiveIterator userIDs, final int numUsers,
            final double[][] featureMatrix) {
        final OpenIntObjectHashMap<Vector> mapping = new OpenIntObjectHashMap<>(
                numUsers);

        while (userIDs.hasNext()) {
            final long userID = userIDs.next();
            mapping.put((int) userID, new DenseVector(
                    featureMatrix[userIndex(userID)], true));
        }

        return mapping;
    }

    protected Vector sparseItemRatingVector(final PreferenceArray prefs) {
        final SequentialAccessSparseVector ratings = new SequentialAccessSparseVector(
                Integer.MAX_VALUE, prefs.length());
        for (final Preference preference : prefs) {
            ratings.set((int) preference.getUserID(), preference.getValue());
        }
        return ratings;
    }

    protected Vector sparseUserRatingVector(final PreferenceArray prefs) {
        final SequentialAccessSparseVector ratings = new SequentialAccessSparseVector(
                Integer.MAX_VALUE, prefs.length());
        for (final Preference preference : prefs) {
            ratings.set((int) preference.getItemID(), preference.getValue());
        }
        return ratings;
    }
}