Ejemplo n.º 1
0
 public void DoubleTest()
 {
     List<int> myList = new List<int>();
     myList.Insert(0, 1);
     myList.Insert(1, 2);
     myList.Insert(2, 3);
     List<int> changedList = Map.MapFunction(myList, x => x * 2);
     Assert.AreEqual(2, changedList[0]);
     Assert.AreEqual(4, changedList[1]);
     Assert.AreEqual(6, changedList[2]);
 }
Ejemplo n.º 2
0
 public void OriginalListDoesntChangeTest()
 {
     List<int> myList = new List<int>();
     myList.Insert(0, 5);
     Map.MapFunction(myList, x => x * x);
     Assert.AreEqual(5, (myList[0]));
 }
Ejemplo n.º 3
0
 public void SquareTest()
 {
     List<int> myList = new List<int>();
     myList.Insert(0, 5);
     List<int> changedList = Map.MapFunction(myList, x => x * x);
     Assert.AreEqual(25, (changedList[0]));
 }
 public static async Task<String> EvaluateScriptWithJqueryAsync(params String[] sources)
 {
     var list = new List<String>(sources);
     list.Insert(0, Sources.Jquery);
     var cfg = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true).WithJavaScript();
     var scripts = "<script>" + String.Join("</script><script>", list) + "</script>";
     var html = "<!doctype html><div id=result></div>" + scripts;
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     return document.GetElementById("result").InnerHtml;
 }
Ejemplo n.º 5
0
 public IEnumerable<Report> ReportListGenerator()
 {
     int iCount = 5;
     var x = new List<Report>();
     while (iCount > 0)
     {
         x.Insert(0, new Report() { ID = iCount, Name = "Report #" + iCount });
         iCount--;
     }
     return x.AsEnumerable();
 }
Ejemplo n.º 6
0
        public void UnionQueryReuse()
        {
            List<int> first = new List<int> { 1, 2 };
            List<int> second = new List<int> { 2, 3 };
            IEnumerable<int> enumerable = first.Union(second);

            enumerable.AssertEqual(1, 2, 3);

            first.Insert(0, 0);
            second.Add(4);
            enumerable.AssertEqual(0, 1, 2, 3, 4);
        }
Ejemplo n.º 7
0
        public void TestExecute()
        {
            var list = new List<int> ();
            Action<int,int> exeAction = (i, v) => list.Insert (i, v);
            Action<int,int> undoAction = (i, v) => list.RemoveAt (i);

            var command = new Command<int,int>(0,4,exeAction, undoAction);
            command.Execute ();
            Assert.AreEqual (1, list.Count);
            Assert.AreEqual (list[0],4);

            command.Undo ();
            Assert.AreEqual (0, list.Count);
        }
        public void ListCollectgionInitialization()
        {
            var people = new List<Person>
            {
                new Person { Name = "Matteo", Age = 12 }, //equivalent to people.Add(new Person { Name = "Matteo", Age = 12 }); add the object to the end of the list
                new Person { Name = "Valerio", Age = 13 }
            };

            people.Insert(1, new Person { Name = "Antonio", Age = 23 });

            foreach (var person in people)
            {
                Console.WriteLine(person.Name);
            }
        }
        public void AddReplicaTest()
        {
            Assert.IsTrue(this.repTable.Exists(), "RTable does not exist");

            View v = this.configurationWrapper.GetWriteView();
            int index = v.Chain.Count - 1;
            string accountName = v.GetReplicaInfo(index).StorageAccountName;

            List<ReplicaInfo> replicas = new List<ReplicaInfo>();
            for (int i = 0; i <= index; i++)
            {
                replicas.Add(v.Chain[i].Item1);
            }

            //Just add the last replica again at the head to simulate a new replica addition
            ReplicaInfo newReplica = new ReplicaInfo()
            {
                StorageAccountName = accountName,
            };

            //Add the new replica at the head
            replicas.Insert(0, newReplica);

            int readViewHeadIndex = 1;
            this.UpdateConfiguration(replicas, readViewHeadIndex);

            // validate all state
            Assert.IsFalse(this.configurationWrapper.IsViewStable(), "View = {0}", this.configurationWrapper.GetWriteView().IsStable);
            View readView = this.configurationWrapper.GetReadView();
            View writeView = this.configurationWrapper.GetWriteView();
            long viewIdAfterFirstUpdate = writeView.ViewId;

            // Actually, both read and write views point to the same view
            Assert.IsTrue(readView == writeView);

            int headIndex = 0;
            long readViewHeadViewId = readView.GetReplicaInfo(readViewHeadIndex).ViewInWhichAddedToChain;
            Assert.IsTrue(writeView.GetReplicaInfo(headIndex).ViewInWhichAddedToChain == readViewHeadViewId + 1);

            //Now, make the read and write views the same
            this.UpdateConfiguration(replicas, 0);
            // validate all state
            Assert.IsTrue(this.configurationWrapper.IsViewStable());
            readView = this.configurationWrapper.GetReadView();
            writeView = this.configurationWrapper.GetWriteView();
            Assert.IsTrue(readView == writeView);
            Assert.IsTrue(readView.ViewId == viewIdAfterFirstUpdate + 1);
        }
		public void Insert()
		{
			List<string> applied = new List<string> { "foo", "bar", "baz" };

			Action reset = () => Assert.Fail ("Reset should not be called");
			Action<object, int, bool> insert = (o, i, create) => {
				Assert.That (create, Is.True);
				applied.Insert (i, (string) o);
			};
			Action<object, int> removeAt = (o, i) => applied.RemoveAt (i);

			var items = new ObservableCollection<string> (applied);
			items.CollectionChanged += (s, e) => e.Apply (insert, removeAt, reset);

			items.Insert (1, "monkey");

			CollectionAssert.AreEqual (items, applied);
		}
Ejemplo n.º 11
0
        public void TestStack()
        {
            Stack<string> stack = new Stack<string>();

            stack.Push("1");
            stack.Push("2");
            stack.Push("3");
            stack.Push("4");
            List<string> list = new List<string>();

            while (stack.Count >0)
            {
                list.Insert(0,stack.Pop());
            }
            foreach (string s in list)
            {
                Console.WriteLine(s);
            }
        }
        public void diff_charsToLinesTest()
        {
            diff_match_patchTest dmp = new diff_match_patchTest();

              Assert.AreEqual(new Diff(Operation.EQUAL, "a"),
              new Diff(Operation.EQUAL, "a"));

              // Convert chars up to lines.
              List<Diff> diffs = new List<Diff> {
              new Diff(Operation.EQUAL, "\u0001\u0002\u0001"),
              new Diff(Operation.INSERT, "\u0002\u0001\u0002")};
              List<string> tmpVector = new List<string>();
              tmpVector.Add("");
              tmpVector.Add("alpha\n");
              tmpVector.Add("beta\n");
              dmp.diff_charsToLines(diffs, tmpVector);
              CollectionAssert.AreEqual(new List<Diff> {
              new Diff(Operation.EQUAL, "alpha\nbeta\nalpha\n"),
              new Diff(Operation.INSERT, "beta\nalpha\nbeta\n")}, diffs);

              // More than 256 to reveal any 8-bit limitations.
              int n = 300;
              tmpVector.Clear();
              StringBuilder lineList = new StringBuilder();
              StringBuilder charList = new StringBuilder();
              for (int x = 1; x < n + 1; x++) {
            tmpVector.Add(x + "\n");
            lineList.Append(x + "\n");
            charList.Append(Convert.ToChar (x));
              }
              Assert.AreEqual(n, tmpVector.Count);
              string lines = lineList.ToString();
              string chars = charList.ToString();
              Assert.AreEqual(n, chars.Length);
              tmpVector.Insert(0, "");
              diffs = new List<Diff> {new Diff(Operation.DELETE, chars)};
              dmp.diff_charsToLines(diffs, tmpVector);
              CollectionAssert.AreEqual(new List<Diff>
              {new Diff(Operation.DELETE, lines)}, diffs);
        }
Ejemplo n.º 13
0
		public void TestAddGetRemove ()
		{
			var foos = new List<string> (){ "1", "2", "3" };
			Assert.AreEqual (3, foos.Count);

			foos [2] = "MooFoey!";
			Assert.IsTrue (foos.Contains ("MooFoey!"));
			Assert.AreEqual ("MooFoey!", foos [2]);

			foos.Add ("Hello!");
			Assert.AreEqual (4, foos.Count);

			foos.Remove ("Hello!");
			Assert.AreEqual (3, foos.Count);

			foos.Insert (1, "foomoey!");
			Assert.AreEqual (4, foos.Count);

			foos.InsertRange (1, new List<string>{ "1", "2", "3" }); 
			Assert.AreEqual (7, foos.Count);

			foos.Clear ();
			Assert.IsEmpty (foos);
		}
Ejemplo n.º 14
0
        public void diff_linesToCharsTest()
        {
            var dmp = new diff_match_patchTest();
            // Convert lines down to characters.
            var tmpVector = new List<string>{"", "alpha\n", "beta\n"};
            Object[] result = dmp.diff_linesToChars("alpha\nbeta\nalpha\n", "beta\nalpha\nbeta\n");
            Assert.AreEqual("\u0001\u0002\u0001", result[0]);
            Assert.AreEqual("\u0002\u0001\u0002", result[1]);
            CollectionAssert.AreEqual(tmpVector, (List<string>)result[2]);

            tmpVector.Clear();
            tmpVector.Add("");
            tmpVector.Add("alpha\r\n");
            tmpVector.Add("beta\r\n");
            tmpVector.Add("\r\n");
            result = dmp.diff_linesToChars("", "alpha\r\nbeta\r\n\r\n\r\n");
            Assert.AreEqual("", result[0]);
            Assert.AreEqual("\u0001\u0002\u0003\u0003", result[1]);
            CollectionAssert.AreEqual(tmpVector, (List<string>)result[2]);

            tmpVector.Clear();
            tmpVector.Add("");
            tmpVector.Add("a");
            tmpVector.Add("b");
            result = dmp.diff_linesToChars("a", "b");
            Assert.AreEqual("\u0001", result[0]);
            Assert.AreEqual("\u0002", result[1]);
            CollectionAssert.AreEqual(tmpVector, (List<string>)result[2]);

            // More than 256 to reveal any 8-bit limitations.
            const int n = 300;
            tmpVector.Clear();
            var lineList = new StringBuilder();
            var charList = new StringBuilder();
            for (int x = 1; x < n + 1; x++) {
                tmpVector.Add(x + "\n");
                lineList.Append(x + "\n");
                charList.Append(Convert.ToChar(x));
            }
            Assert.AreEqual(n, tmpVector.Count);
            string lines = lineList.ToString();
            string chars = charList.ToString();
            Assert.AreEqual(n, chars.Length);
            tmpVector.Insert(0, "");
            result = dmp.diff_linesToChars(lines, "");
            Assert.AreEqual(chars, result[0]);
            Assert.AreEqual("", result[1]);
            CollectionAssert.AreEqual(tmpVector, (List<string>)result[2]);
        }
Ejemplo n.º 15
0
		public void MakeContextMenu_CheckedStates_SelCoversMultiSideBySideAnn()
		{
			// Provide hvoTagPoss and SelectedWfics, create a markup tag and examine it.
			// Setup the SelectedWfics property to include 2 words
			List<int> tempList = new List<int>();
			tempList.Add(m_hvoWfics[0]);
			tempList.Add(m_hvoWfics[1]);
			m_tagChild.SelectedWfics = tempList;

			// Make a tag for 1st selection
			int itestItem1 = 0; // first tag in list
			m_tagChild.CallMakeTextTagAnnotation(m_possTagHvos[itestItem1]);

			// Setup the SelectedWfics property to include one more word
			tempList.Clear();
			tempList.Add(m_hvoWfics[2]);
			tempList.Add(m_hvoWfics[3]);
			m_tagChild.SelectedWfics = tempList;

			// Make a tag for 2nd selection
			int itestItem2 = 1; // 2nd tag in list
			m_tagChild.CallMakeTextTagAnnotation(m_possTagHvos[itestItem2]);

			// Setup selection to cover part of first tag, and all of second
			tempList.Insert(0, m_hvoWfics[1]);
			m_tagChild.SelectedWfics = tempList;

			// SUT; make menu while selected phrase has 2 side-by-side tags
			ContextMenuStrip menu = new ContextMenuStrip();
			m_tagChild.CallMakeContextMenuForTags(menu, m_textMarkupTags);

			// Verification of SUT; Two should be checked and that in a submenu
			ToolStripMenuItem subList = AssertHasMenuWithText(menu.Items, kFTO_RRG_Semantics, 3);
			Assert.IsNotNull(subList, "No " + kFTO_RRG_Semantics + " menu!?");
			ToolStripItemCollection subMenu = subList.DropDownItems;
			bool[] expectedStates = new bool[subMenu.Count];
			expectedStates[itestItem1] = true;
			expectedStates[itestItem2] = true;
			AssertMenuCheckState(expectedStates, subMenu);
		}
Ejemplo n.º 16
0
		public void MakeContextMenu_CheckedStates_MultiAnnSelExtra()
		{
			// This test will need changing when we allow multiple lines of tagging.

			// Provide hvoTagPoss and SelectedWfics, create a markup tag and examine it.
			// Setup the SelectedWfics property to include 2 words
			List<int> tempList = new List<int>();
			tempList.Add(m_hvoWfics[1]);
			tempList.Add(m_hvoWfics[2]);
			m_tagChild.SelectedWfics = tempList;

			// Make a tag for 1st selection
			int itestItem1 = 0; // first tag in list
			m_tagChild.CallMakeTextTagAnnotation(m_possTagHvos[itestItem1]);

			// Setup the SelectedWfics property to include one more word
			tempList.Add(m_hvoWfics[3]);
			m_tagChild.SelectedWfics = tempList;

			// Make a tag for 2nd selection
			// TODO GordonM: For the time being, this deletes the first tag. When multiple layers
			// of tags are allowed, change the expected results.
			int itestItem2 = 1; // 2nd tag in list
			m_tagChild.CallMakeTextTagAnnotation(m_possTagHvos[itestItem2]);

			// Setup selection to contain previous tags, plus another word
			tempList.Insert(0, m_hvoWfics[0]);
			m_tagChild.SelectedWfics = tempList;

			// SUT; make menu while selected phrase has 2 tags, but the initial
			// wfic has no tags.
			ContextMenuStrip menu = new ContextMenuStrip();
			m_tagChild.CallMakeContextMenuForTags(menu, m_textMarkupTags);

			// Verification of SUT; Two should be checked and that in a submenu
			ToolStripMenuItem subList = AssertHasMenuWithText(menu.Items, kFTO_RRG_Semantics, 3);
			Assert.IsNotNull(subList, "No " + kFTO_RRG_Semantics + " menu!?");
			ToolStripItemCollection subMenu = subList.DropDownItems;
			bool[] expectedStates = new bool[subMenu.Count];
			expectedStates[itestItem1] = false;
			expectedStates[itestItem2] = true;
			AssertMenuCheckState(expectedStates, subMenu);
		}
Ejemplo n.º 17
0
        public static object TransformString2(string str)
        {
            char[] charArr = str.ToCharArray();
            if (charArr.Length == 1) return new Var(str);
            bool isNeg = charArr[0].Equals('-');

            var lst = new List<object>();
            int j = - 1;
            for (int i = charArr.Count() - 1; i >= 0; i--)
            {
                if (Char.IsLetter(charArr[i]))
                {
                    lst.Insert(0, new Var(charArr[i]));
                }
                else
                {
                    j = i;
                    break;
                }
            }
            if (isNeg)
            {
                if (j == 0)
                {
                    var term1 = new Term(Expression.Multiply, new List<object>() {-1, lst[0]});
                    lst[0] = term1;

                    if (lst.Count == 1)
                    {
                        return lst[0];
                    }
                    return new Term(Expression.Multiply, lst);
                }
                var subStr = str.Substring(1, j);
                bool result = LogicSharp.IsNumeric(subStr);
                if (!result) return null;

                int iNum;
                bool result000 = LogicSharp.IsInt(subStr, out iNum);
                if (result000)
                {
                    lst.Insert(0,-1*iNum);
                }
                else
                {
                    double dNum;
                    LogicSharp.IsDouble(subStr, out dNum);
                    lst.Insert(0,-1*dNum);
                }
            }
            else
            {
                if (j == -1)
                {
                    if (lst.Count == 1)
                    {
                        return lst[0];
                    }
                    return new Term(Expression.Multiply, lst);
                }
                var subStr = str.Substring(0, j+1);

                bool result = LogicSharp.IsNumeric(subStr);
                if (!result) return null;

                int iNum;
                bool result000 = LogicSharp.IsInt(subStr, out iNum);
                if (result000)
                {
                    lst.Insert(0,iNum);
                }
                else
                {
                    double dNum;
                    LogicSharp.IsDouble(subStr, out dNum);
                    lst.Insert(0,dNum);
                }
            }
            return new Term(Expression.Multiply, lst);
        }
Ejemplo n.º 18
0
        public void FailoverTest()
        {
            var parallelOptions = new ParallelOptions();
            parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
            parallelOptions.MaxDegreeOfParallelism = 100;

            var policy = new ConstantReconnectionPolicy(int.MaxValue);
            var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false);
            using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build())
            {
                var session = cluster.Connect();
                // Check query to host distribution before killing nodes
                var queriedHosts = new List<string>();
                DateTime futureDateTime = DateTime.Now.AddSeconds(120);
                while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime)
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    queriedHosts.Add(rs.Info.QueriedHost.ToString());
                    Thread.Sleep(50);
                }
                Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!");

                // Create List of actions
                Action selectAction = () =>
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    Assert.Greater(rs.Count(), 0);
                };
                var actions = new List<Action>();
                for (var i = 0; i < 100; i++)
                {
                    actions.Add(selectAction);
                }

                //kill some nodes.
                actions.Insert(20, () => nonShareableTestCluster.StopForce(1));
                actions.Insert(20, () => nonShareableTestCluster.StopForce(2));
                actions.Insert(80, () => nonShareableTestCluster.StopForce(3));

                //Execute in parallel more than 100 actions
                Parallel.Invoke(parallelOptions, actions.ToArray());

                // Wait for the nodes to be killed
                TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20);
                TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20);
                TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20);

                // Execute some more SELECTs
                for (var i = 0; i < 250; i++)
                {
                    var rowSet2 = session.Execute("SELECT * FROM system.local");
                    Assert.Greater(rowSet2.Count(), 0);
                    StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", rowSet2.Info.QueriedHost.ToString());
                }
            }
        }
Ejemplo n.º 19
0
        public void FailoverThenReconnect()
        {
            var parallelOptions = new ParallelOptions
            {
                TaskScheduler = new ThreadPerTaskScheduler(),
                MaxDegreeOfParallelism = 100
            };

            var policy = new ConstantReconnectionPolicy(500);
            var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false);
            using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build())
            {
                var session = cluster.Connect();
                // Check query to host distribution before killing nodes
                var queriedHosts = new List<string>();
                DateTime futureDateTime = DateTime.Now.AddSeconds(120);
                while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime)
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    queriedHosts.Add(rs.Info.QueriedHost.ToString());
                    Thread.Sleep(50);
                }
                Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!");

                // Create list of actions
                Action selectAction = () =>
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    Assert.Greater(rs.Count(), 0);
                };
                var actions = new List<Action>();
                for (var i = 0; i < 100; i++)
                {
                    actions.Add(selectAction);
                    //Check that the control connection is using first host
                    StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString());

                    //Kill some nodes
                    //Including the one used by the control connection
                    actions.Insert(20, () => nonShareableTestCluster.Stop(1));
                    actions.Insert(20, () => nonShareableTestCluster.Stop(2));
                    actions.Insert(80, () => nonShareableTestCluster.Stop(3));

                    //Execute in parallel more than 100 actions
                    Parallel.Invoke(parallelOptions, actions.ToArray());

                    //Wait for the nodes to be killed
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20);
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20);
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20);

                    actions = new List<Action>();
                    for (var j = 0; j < 100; j++)
                    {
                        actions.Add(selectAction);
                    }

                    //Check that the control connection is using first host
                    //bring back some nodes
                    actions.Insert(3, () => nonShareableTestCluster.Start(3));
                    actions.Insert(50, () => nonShareableTestCluster.Start(2));
                    actions.Insert(50, () => nonShareableTestCluster.Start(1));

                    //Execute in parallel more than 100 actions
                    Trace.TraceInformation("Start invoking with restart nodes");
                    Parallel.Invoke(parallelOptions, actions.ToArray());

                    //Wait for the nodes to be restarted
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30);

                    queriedHosts.Clear();
                    // keep querying hosts until they are all queried, or time runs out
                    futureDateTime = DateTime.Now.AddSeconds(120);
                    while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime)
                    {
                        var rs = session.Execute("SELECT * FROM system.local");
                        queriedHosts.Add(rs.Info.QueriedHost.ToString());
                        Thread.Sleep(50);
                    }
                    //Check that one of the restarted nodes were queried
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, queriedHosts);
                    //Check that the control connection is still using last host
                    StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString());
                }
            }
        }
		public void PackageSources_TwoPackageSourcesInOptions_ReturnsTwoPackageSourcesPlusAggregatePackageSource ()
		{
			CreateRegisteredPackageRepositories ();
			AddTwoPackageSourcesToRegisteredSources ();
			CreateViewModel (registeredPackageRepositories);

			var expectedPackageSources = new List<PackageSource> (registeredPackageRepositories.PackageSources);
			expectedPackageSources.Insert (0, RegisteredPackageSourceSettings.AggregatePackageSource);

			PackageSourceCollectionAssert.AreEqual (expectedPackageSources, viewModel.PackageSources);
		}
Ejemplo n.º 21
0
        public void performance()
        {
            var stopwatch = new Stopwatch();

            var count = 2 << 16;

            Console.WriteLine($"Count: {count}");
            

            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Add(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Insert(blist.Count / 2, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Insert(0, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");
            

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Add(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Insert(list.Count / 2, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Insert(0, _random.Next());
                }
            }
            
            stopwatch.Stop();
            Console.WriteLine($"List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new LinkedList<int>();

                for (int i = 0; i < count; i++)
                {
                    list.AddFirst(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var linkedlist = new LinkedList<int>();

                var last = linkedlist.AddFirst(_random.Next());

                for (int i = 0; i < count; i++)
                {
                    last = ((i & 1) == 1
                        ? linkedlist.AddAfter(last, _random.Next())
                        : linkedlist.AddBefore(last, _random.Next()));
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new LinkedList<int>();

                for (int i = 0; i < count; i++)
                {
                    list.AddLast(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

        }
Ejemplo n.º 22
0
        public void ParallelInsertAndSelectSyncWithNodesFailing()
        {
            var originalTraceLevel = Diagnostics.CassandraTraceSwitch.Level;
            Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Warning;
            var builder = Cluster.Builder()
                .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance);
            var clusterInfo = TestUtils.CcmSetup(3, builder);
            try
            {
                var session = clusterInfo.Session;
                session.WaitForSchemaAgreement(session.Execute(@"
                    CREATE KEYSPACE tester
                    WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
                "));
                session.ChangeKeyspace("tester");

                string tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
                session.WaitForSchemaAgreement(session.Execute(String.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName)));

                var insertQuery = String.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
                var insertQueryPrepared = session.Prepare(insertQuery);
                var selectQuery = String.Format("SELECT * FROM {0} LIMIT 10000", tableName);

                var rowsPerId = 100;
                var actionInsert = GetInsertAction(session, new SimpleStatement(insertQuery), ConsistencyLevel.Quorum, rowsPerId);
                var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
                var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);

                //Execute insert sync to have some records
                actionInsert();
                //Execute select sync to assert that everything is going OK
                actionSelect();

                var actions = new List<Action>();
                for (var i = 0; i < 10; i++)
                {
                    //Add 10 actions to execute
                    actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared });
                    actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert });
                    actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect });
                }

                actions.Insert(8, () =>
                {
                    Thread.Sleep(300);
                    TestUtils.CcmStopForce(clusterInfo, 2);
                });

                //Execute in parallel more than 100 actions
                var parallelOptions = new ParallelOptions();
                parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
                parallelOptions.MaxDegreeOfParallelism = 1000;
                Parallel.Invoke(parallelOptions, actions.ToArray());
            }
            finally
            {
                TestUtils.CcmRemove(clusterInfo);
            }
            Diagnostics.CassandraTraceSwitch.Level = originalTraceLevel;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// A simpler version of the algorithm that works with any IEnumerable. 
        /// </summary>
        private IEnumerable<int> InsertionSortIEnumerable(IEnumerable<int> unsorted)
        {
            var sorted = new List<int>();
            foreach (var item in unsorted)
            {
                var newIndex = sorted.Count;
                while (newIndex > 0 && sorted[newIndex-1] > item)
                    newIndex--;
                sorted.Insert(newIndex, item);
            }

            return sorted;
        }
		public void RaiseChangedTest()
		{
			ModifiedMonitoredList<MockParagraph> modifiedList = new ModifiedMonitoredList<MockParagraph>();
			List<MockParagraph> list = new List<MockParagraph>();
			modifiedList.Changed += RaiseParagraphsChanged;

			MockParagraph para1 = new MockParagraph("Para One");
			MockParagraph para2 = new MockParagraph("Para Two");
			MockParagraph para3 = new MockParagraph("Para Three");
			MockParagraph para4 = new MockParagraph("Para Four");
			MockParagraph para5 = new MockParagraph("Para Five");

			list.Add(para1);
			modifiedList.Add(para1);
			Assert.That(paragraphChangedEvent.FirstChange == 0);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 0);
			Assert.That(CompareLists(list, modifiedList));

			list.Add(para3);
			modifiedList.Add(para3);
			Assert.That(paragraphChangedEvent.FirstChange == 1);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 0);
			Assert.That(CompareLists(list, modifiedList));

			list.Add(para5);
			modifiedList.Add(para5);
			Assert.That(paragraphChangedEvent.FirstChange == 2);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 0);
			Assert.That(CompareLists(list, modifiedList));

			list.Insert(1, para2);
			modifiedList.Insert(1, para2);
			Assert.That(paragraphChangedEvent.FirstChange == 1);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 0);
			Assert.That(CompareLists(list, modifiedList));

			list.Insert(3, para4);
			modifiedList.Insert(3, para4);
			Assert.That(paragraphChangedEvent.FirstChange == 3);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 0);
			Assert.That(CompareLists(list, modifiedList));

			list[2] = para2;
			modifiedList[2] = para2;
			Assert.That(paragraphChangedEvent.FirstChange == 2);
			Assert.That(paragraphChangedEvent.NumberAdded == 1);
			Assert.That(paragraphChangedEvent.NumberDeleted == 1);
			Assert.That(CompareLists(list, modifiedList));

			list.Remove(para4);
			modifiedList.Remove(para4);
			Assert.That(paragraphChangedEvent.FirstChange == 3);
			Assert.That(paragraphChangedEvent.NumberAdded == 0);
			Assert.That(paragraphChangedEvent.NumberDeleted == 1);
			Assert.That(CompareLists(list, modifiedList));

			list.RemoveAt(1);
			modifiedList.RemoveAt(1);
			Assert.That(paragraphChangedEvent.FirstChange == 1);
			Assert.That(paragraphChangedEvent.NumberAdded == 0);
			Assert.That(paragraphChangedEvent.NumberDeleted == 1);
			Assert.That(CompareLists(list, modifiedList));

			modifiedList.SimulateChange(0, 2);
			Assert.That(paragraphChangedEvent.FirstChange == 0);
			Assert.That(paragraphChangedEvent.NumberAdded == 2);
			Assert.That(paragraphChangedEvent.NumberDeleted == 2);
			Assert.That(CompareLists(list, modifiedList));

			list.Clear();
			modifiedList.Clear();
			Assert.That(paragraphChangedEvent.FirstChange == 0);
			Assert.That(paragraphChangedEvent.NumberAdded == 0);
			Assert.That(paragraphChangedEvent.NumberDeleted == 3);
			Assert.That(CompareLists(list, modifiedList));

		}
Ejemplo n.º 25
0
		public void MakeContextMenu_CheckedStates_MultiAnnSelExtra()
		{
			// This test will need changing when we allow multiple lines of tagging.

			// Provide hvoTagPoss and SelectedWordforms, create a markup tag and examine it.
			// Setup the SelectedWordforms property to include 2 words
			var tempList = new List<AnalysisOccurrence> { m_occurrences[1], m_occurrences[2] };
			m_tagChild.SelectedWordforms = tempList;

			// Make a tag for 1st selection
			const int itestItem1 = 0;
			UndoableUnitOfWorkHelper.Do("UndoTagTest", "RedoTagTest", Cache.ActionHandlerAccessor,
				() => m_tagChild.CallMakeTextTagInstance(m_possTags[itestItem1]));

			// Setup the SelectedWordforms property to include one more word
			tempList.Add(m_occurrences[3]);
			m_tagChild.SelectedWordforms = tempList;

			// Make a tag for 2nd selection
			// Enhance GordonM: For the time being, this deletes the first tag. When multiple layers
			// of tags are allowed, change the expected results.
			const int itestItem2 = 1;
			UndoableUnitOfWorkHelper.Do("UndoTagTest", "RedoTagTest", Cache.ActionHandlerAccessor,
				() => m_tagChild.CallMakeTextTagInstance(m_possTags[itestItem2]));

			// Setup selection to contain previous tags, plus another word
			tempList.Insert(0, m_occurrences[0]);
			m_tagChild.SelectedWordforms = tempList;

			// SUT; make menu while selected phrase has 2 tags, but the initial
			// occurrence has no tags.
			using (var menu = new ContextMenuStrip())
			{
				m_tagChild.CallMakeContextMenuForTags(menu, m_textMarkupTags);

				// Verification of SUT; Two should be checked and that in a submenu
				var subList = AssertHasMenuWithText(menu.Items, kFTO_RRG_Semantics, 3);
				Assert.IsNotNull(subList, "No " + kFTO_RRG_Semantics + " menu!?");
				var subMenu = subList.DropDownItems;
				var expectedStates = new bool[subMenu.Count];
				expectedStates[itestItem1] = false;
				// Enhance GordonM: When multiple layers allowed, change this.
				expectedStates[itestItem2] = true;
				AssertMenuCheckState(expectedStates, subMenu);
			}
		}
Ejemplo n.º 26
0
		public void MakeContextMenu_CheckedStates_SelCoversMultiSideBySideAnn()
		{
			// Provide hvoTagPoss and SelectedWordforms, create a markup tag and examine it.
			// Setup the SelectedWordforms property to include 2 words
			var tempList = new List<AnalysisOccurrence> { m_occurrences[0], m_occurrences[1] };
			m_tagChild.SelectedWordforms = tempList;

			// Make a tag for 1st selection
			const int itestItem1 = 0;
			UndoableUnitOfWorkHelper.Do("UndoTagTest", "RedoTagTest", Cache.ActionHandlerAccessor,
				() => m_tagChild.CallMakeTextTagInstance(m_possTags[itestItem1]));

			// Setup the SelectedWordforms property to include one more word
			tempList.Clear();
			tempList.Add(m_occurrences[2]);
			tempList.Add(m_occurrences[3]);
			m_tagChild.SelectedWordforms = tempList;

			// Make a tag for 2nd selection
			const int itestItem2 = 1;
			UndoableUnitOfWorkHelper.Do("UndoTagTest", "RedoTagTest", Cache.ActionHandlerAccessor,
				() => m_tagChild.CallMakeTextTagInstance(m_possTags[itestItem2]));

			// Setup selection to cover part of first tag, and all of second
			tempList.Insert(0, m_occurrences[1]);
			m_tagChild.SelectedWordforms = tempList;

			// SUT; make menu while selected phrase has 2 side-by-side tags
			using (var menu = new ContextMenuStrip())
			{
				m_tagChild.CallMakeContextMenuForTags(menu, m_textMarkupTags);

				// Verification of SUT; Two should be checked and that in a submenu
				var subList = AssertHasMenuWithText(menu.Items, kFTO_RRG_Semantics, 3);
				Assert.IsNotNull(subList, "No " + kFTO_RRG_Semantics + " menu!?");
				var subMenu = subList.DropDownItems;
				var expectedStates = new bool[subMenu.Count];
				expectedStates[itestItem1] = true;
				expectedStates[itestItem2] = true;
				AssertMenuCheckState(expectedStates, subMenu);
			}
		}
Ejemplo n.º 27
0
    public void FindCertificateTest() {
      CertificateHandler ch = new CertificateHandler();

      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512);
      byte[] blob = rsa.ExportCspBlob(false);
      RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();
      rsa_pub.ImportCspBlob(blob);

      List<MemBlock> supported = new List<MemBlock>();
      List<MemBlock> unsupported = new List<MemBlock>();

      for(int i = 0; i < 20; i++) {
        CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky",
            "*****@*****.**" + i, rsa_pub, i.ToString());
        Certificate cert = cm.Sign(cm, rsa);
        if(i % 2 == 0) {
          ch.AddCACertificate(cert.X509);
          ch.AddSignedCertificate(cert.X509);
          supported.Add(cert.SerialNumber);
        } else {
          unsupported.Add(cert.SerialNumber);
        }
      }

      Assert.IsNotNull(ch.FindCertificate(supported), "Should find a certificate");

      bool success = false;
      try {
        success = ch.FindCertificate(unsupported) != null;
      } catch { }

      Assert.IsTrue(!success, "Should not find a certificate");

      List<MemBlock> mixed = new List<MemBlock>(unsupported);
      mixed.Insert(4 ,supported[1]);
      Assert.AreEqual(supported[1],
          MemBlock.Reference(ch.FindCertificate(mixed).SerialNumber),
          "Only one supported");
    }
Ejemplo n.º 28
0
        public void SignSome()
        {
            Association assoc = HmacShaAssociation.Create(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.HMAC_SHA1,
                "h1", sha1Secret, TimeSpan.FromMinutes(2));
            const string prefix = "q.";

            var dict = new Dictionary<string, string>();
            dict.Add("q.a", "b");
            dict.Add("q.c", "d");
            dict.Add("q.e", "f");

            var signKeys = new List<string> { "a", "c" }; // don't sign e

            byte[] sig1 = assoc.Sign(dict, signKeys, prefix);

            // change the unsigned value and verify that the sig doesn't change
            dict["q.e"] = "g";
            Assert.IsTrue(Util.ArrayEquals(sig1, assoc.Sign(dict, signKeys, prefix)));
            // change a signed value and verify that the sig does change.
            dict["q.c"] = "D";
            Assert.IsFalse(Util.ArrayEquals(sig1, assoc.Sign(dict, signKeys, prefix)));

            // change the ordering of signed fields and verify that the signature changes.
            dict["q.c"] = "d"; // put this back first.
            Assert.IsTrue(Util.ArrayEquals(sig1, assoc.Sign(dict, signKeys, prefix)));
            signKeys.Insert(0, signKeys[1]);
            signKeys.RemoveAt(2);
            Assert.IsFalse(Util.ArrayEquals(sig1, assoc.Sign(dict, signKeys, prefix)));
        }
		public void Can_MoveBetweenLists()
		{
			var list1Members = new List<string> { "one", "two", "three", "four" };
			var list2Members = new List<string> { "five", "six", "seven" };
			const string item4 = "four";

			list1Members.ForEach(x => Redis.AddItemToList(ListId, x));
			list2Members.ForEach(x => Redis.AddItemToList(ListId2, x));

			list1Members.Remove(item4);
			list2Members.Insert(0, item4);
			Redis.PopAndPushItemBetweenLists(ListId, ListId2);

			var readList1 = Redis.GetAllItemsFromList(ListId);
			var readList2 = Redis.GetAllItemsFromList(ListId2);

			AssertAreEqual(readList1, list1Members);
			AssertAreEqual(readList2, list2Members);
		}
Ejemplo n.º 30
0
        public static void Conversation()
        {
            //OAuthTokens tokens = Configuration.GetTokens();

            var statusResponse = TwitterStatus.Show(7183041864671232);

            List<TwitterStatus> conversation = new List<TwitterStatus>();
            conversation.Add(statusResponse.ResponseObject);

            while (statusResponse.ResponseObject.InReplyToStatusId.HasValue)
            {
                statusResponse = TwitterStatus.Show(statusResponse.ResponseObject.InReplyToStatusId.Value);

                conversation.Insert(0, statusResponse.ResponseObject);
            }
        }