public void FailedCallbackFires()
        {
            List<int> order = new List<int> { 1, 2, 3, 4, 5 };
            List<int> errors = new List<int>();

            ThrottledProcessor<int> queue = new ThrottledProcessor<int>(
                100,
                (int value) => { throw new InvalidOperationException("This is the message"); },
                (int value) => Assert.Fail("The success path should never be called"),
                (int value, Exception ex) =>
                    {
                        Assert.AreEqual("This is the message", ex.Message);
                        errors.Add(value);
                    });

            foreach (int i in order)
            {
                queue.Add(i);
            }

            while (queue.Length > 0)
            {
                Thread.Sleep(100);
            }

            foreach (int expected in order)
            {
                int actual = errors.First();
                errors.RemoveAt(0);

                Assert.AreEqual(expected, actual, "The items were failed in the wrong order");
            }
        }
		public void TestBinarySearch()
		{
			List<string> animalsUnordered = new List<string>(
				new[] { "Cat", "Dog", "Elephant", "Eagle", "Eel", "Zebra", "Yak", "Monkey", "Meerkat" });

			WordList words;

			while (animalsUnordered.Count > 0)
			{	
				words = new WordList(animalsUnordered);
				
				Assert.AreEqual(-1, words.BinarySearch("Unicorn", false, false), "Wrong index for: Unicorn");

				string[] animalsOrdered = animalsUnordered.OrderBy(a => a).ToArray();

				Assert.AreEqual(-1, words.BinarySearch("Dragon", false, false), "Wrong index for: Dragon");

				for (int expectedIndex = 0; expectedIndex < animalsOrdered.Length; expectedIndex++)
				{
					string word = animalsOrdered[expectedIndex];
					Assert.AreEqual(expectedIndex, words.BinarySearch(word, false, false), "Wrong index for: " + word);
				}

				animalsUnordered.RemoveAt(0);
			}

			words = new WordList(new[] { "Heaven", "Hell", "Hello", "Zebra", "ZOO" });

			Assert.AreEqual(0, words.BinarySearch("H", false, true), "Wrong index for: H");
			Assert.AreEqual(1, words.BinarySearch("HELL", false, true), "Wrong index for: H");
			Assert.AreEqual(3, words.BinarySearch("M", true, false), "Wrong index for: M");
			Assert.AreEqual(-1, words.BinarySearch("M", false, false), "Wrong index for: M");
		}
Example #3
0
        private static int[] ToArray(int[] x, int[] y)
        {
            if(x.Length == 0 || y.Length == 0)
                return new int[] { };

            bool negative = (x[0] > 0) ^ (y[0] > 0);
            x[0] = Math.Abs(x[0]);
            y[0] = Math.Abs(y[0]);

            List<int> result = new List<int>(new int[x.Length + y.Length]);

            for(int i = x.Length - 1; i >= 0; i--)
            {
                for(int j = y.Length - 1; j >= 0; j--)
                {
                    result[i + j + 1] += x[i] * y[j];
                    result[i + j] += result[i + j + 1] / 10;
                    result[i + j + 1] %= 10;
                }
            }

            while (result.Count > 0 && result[0] == 0)
                result.RemoveAt(0);

            if (negative && result.Count > 0)
                result[0] *= -1;

            return result.ToArray();
        }
Example #4
0
        public void TestHeap_PriorityQueue()
        {
            Random random = new Random();

            // build a random list
            var list = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist());

            // make a heap
            list.ToSublist().MakeHeap().InPlace();
            Assert.IsTrue(list.ToSublist().IsHeap(), "The list is not a heap."); // confirm we have a heap

            // let's push a value onto the heap and make it the highest priority
            list.Add(100);
            list.ToSublist().HeapAdd();
            Assert.AreEqual(100, list[0], "The value was not moved to the top of the heap.");
            Assert.IsTrue(list.ToSublist().IsHeap(), "The list is not a heap.");

            // now let's remove it
            list.ToSublist().HeapRemove();
            Assert.AreEqual(100, list[list.Count - 1], "The value not moved to the bottom of the heap.");
            Assert.AreEqual(list.Count - 1, list.ToSublist().IsHeap(), "Could not find the end of the heap.");
            list.RemoveAt(list.Count - 1);
            Assert.IsTrue(list.ToSublist().IsHeap(), "The list is not a heap.");

            // we can sort a heap
            list.ToSublist().HeapSort();
            Assert.IsTrue(list.ToSublist().IsSorted(), "The list was not sorted.");
        }
Example #5
0
        public void TestAdd()
        {
            const int SampleSize = 1000000;

            Random Generator = new Random();

            SortedList<int> Tested = new SortedList<int>();
            List<int> Original = new List<int>();

            for (int x = 0; x < SampleSize; x++)
            {
                Original.Add(x);
            }
            List<int> OriginalClone = new List<int>(Original.ToArray());
            while (OriginalClone.Count > 0)
            {
                int Position = Generator.Next(0, OriginalClone.Count);
                Tested.Add(OriginalClone[Position]);
                OriginalClone.RemoveAt(Position);
            }

            if (Tested.Count != Original.Count)
            {
                throw new Exception("Count mismatch.");
            }

            for (int x = 0; x < Tested.Count; x++)
            {
                if (Tested[x] != Original[x])
                {
                    throw new Exception("Order mismatch.");
                }
            }
        }
        public void TestAdjacent()
        {
            IMatrix<string> matrix = new Matrix<string>(3, 3);
            List<string> items = new List<string>(9);
            for (int i = 0; i < items.Capacity; i++)
            {
                items.Add(string.Format("{0}", i));
            }

            var index = 0;
            for (int y = 0; y < matrix.Rows; y++)
            {
                int x;
                for (x = 0; x < matrix.Columns; x++)
                {
                    matrix[x, y] = items[index++];
                }
            }

            var middleCell = matrix[1, 1];
            int middleIndex = matrix.IndexOf(middleCell);
            items.RemoveAt(middleIndex);

            var adjacentCells = matrix.GetAdjacentCells(middleCell);
            Assert.IsTrue(items.SequenceEqual(adjacentCells));
        }
        public void CompareTo_ValidateSortingForAllPerms_Passes()
        {
            List<StartingHandCombo> copy = new List<StartingHandCombo>();
            List<StartingHandCombo> sorted = new List<StartingHandCombo>();
            List<StartingHandCombo> shuffled = new List<StartingHandCombo>();

            foreach (StartingHandCombo h in _startingHandPermutations.Values)
            {
                copy.Add(h);
                sorted.Add(h);
            }

            Random iRand = new Random();
            do{
                int i = iRand.Next(copy.Count - 1);
                shuffled.Add(copy[i]);
                copy.RemoveAt(i);
            }while(copy.Count > 0);

            Assert.IsFalse(EqualLists(sorted, shuffled));

            shuffled.Sort();
            sorted.Sort();

            Assert.IsTrue(EqualLists(sorted, shuffled));
        }
        public void TestPartialSortAdd_GrabTopValues()
        {
            Random random = new Random();

            // build a list
            var list = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist());

            // create a list to hold the top three
            const int numberOfItems = 10;
            var destination = new List<int>(numberOfItems);

            // store the top three results
            Func<int, int, int> comparison = (x, y) => Comparer<int>.Default.Compare(y, x);
            list.ToSublist().PartialSort(numberOfItems, comparison).AddTo(destination.ToSublist());

            // grab the three largest values from largest to smallest
            var expected = new List<int>(numberOfItems);
            for (int round = 0; round != numberOfItems; ++round)
            {
                int maxIndex = list.ToSublist().Maximum();
                expected.Add(list[maxIndex]);
                list.RemoveAt(maxIndex);
            }

            Assert.IsTrue(expected.ToSublist().IsEqualTo(destination.ToSublist()), "The top values weren't grabbed.");
        }
        public void PokerHandsChecker_HandWithLessThanFiveCardsShouldBeInvalid_False()
        {
            IList<ICard> currentCards = new List<ICard>(this.cards);
            currentCards.RemoveAt(0);
            var currentHand = new Hand(currentCards);

            Assert.IsFalse(this.checker.IsValidHand(currentHand));
        }
        public void PokerHandsChecker_HandWithRepeatCardShouldBeInvalid_False()
        {
            IList<ICard> currentCards = new List<ICard>(this.cards);
            currentCards.RemoveAt(0);
            currentCards.Add(new Card(currentCards[0].Face, currentCards[0].Suit));
            var currentHand = new Hand(currentCards);

            Assert.IsFalse(this.checker.IsValidHand(currentHand));
        }
        public void SetMazeConfigurationsTest()
        {
            // Setup constant parameters
            const int maxTimesteps = 300;
            const int minSuccessDistance = 5;

            // Create some dummy structures/walls
            IList<MazeStructure> mazeStructures = new List<MazeStructure>
            {
                new MazeStructure(300, 300, 1)
                {
                    Walls = {new MazeStructureWall(5, 5, 10, 10), new MazeStructureWall(6, 6, 11, 11)}
                },
                new MazeStructure(300, 300, 1)
                {
                    Walls = {new MazeStructureWall(7, 7, 12, 12), new MazeStructureWall(8, 8, 13, 13)}
                },
                new MazeStructure(300, 300, 1)
                {
                    Walls = {new MazeStructureWall(9, 9, 14, 14), new MazeStructureWall(10, 10, 15, 15)}
                },
                new MazeStructure(300, 300, 1)
                {
                    Walls = {new MazeStructureWall(11, 11, 16, 16), new MazeStructureWall(12, 12, 17, 17)}
                },
                new MazeStructure(300, 300, 1)
                {
                    Walls = {new MazeStructureWall(13, 13, 18, 18), new MazeStructureWall(14, 14, 19, 19)}
                }
            };

            // Create the factory
            MultiMazeNavigationWorldFactory<BehaviorInfo> factory =
                new MultiMazeNavigationWorldFactory<BehaviorInfo>(maxTimesteps, minSuccessDistance);

            // Attempt setting the configurations
            factory.SetMazeConfigurations(mazeStructures);

            // Ensure number of mazes is 2
            Debug.Assert(factory.NumMazes == 5);

            // Remove one of the dummy structures
            mazeStructures.RemoveAt(0);

            // Call again with one of the mazes removed
            factory.SetMazeConfigurations(mazeStructures);

            // Ensure that no longer extant maze was removed
            Debug.Assert(factory.NumMazes == 4);
        }
Example #12
0
        //        private int[] Get6Clock(int i)
        //      {
        //        return Permutation(i).
        //  }
        private int[] Get6Clock(int n)
        {
            int[] dividors = { 720, 120, 24, 6, 2, 1, 1 };
            List<int> numbers = new List<int>(new int[] {1,2,3,4,5,6});
            int[] result = new int[5];
            int index;

            for (int i = 0; i < 5; i++)
            {
                index = (n%dividors[i])/dividors[i+1];
                result[i] = numbers[index];
                numbers.RemoveAt(index);
            }
            return result;
        }
Example #13
0
        public string getTask(string[] list, int n)
        {
            List<string> tasks = new List<string>();
            foreach (string task in list)
                tasks.Add(task);

            int index = 0;

            while(tasks.Count > 1)
            {
                index = (index + n - 1) % (tasks.Count);
                tasks.RemoveAt(index);
            }

            return tasks[0];
        }
Example #14
0
 public static IEnumerable<int> MakeRandomInsertList(int count)
 {
     List<int> ret = new List<int>(count);
     List<int> sorted = new List<int>(count);
     var rng = new Random();
     for (int i = 0; i < count; i++)
     {
         sorted.Add(i);
     }
     while (sorted.Count > 0)
     {
         var sampleIx = rng.Next(sorted.Count);
         ret.Add(sorted[sampleIx]);
         sorted.RemoveAt(sampleIx);
     }
     return ret;
 }
 private void GenerateAnswer(bool[,] dp, List<string[]> result, int start, List<string> cur, string input)
 {
     for (int end = start; end < input.Length; end++)
     {
         if (dp[start, end])
         {
             cur.Add(input.Substring(start, end - start + 1));
             if (end == input.Length - 1)
             {
                 result.Add(cur.ToArray());
             }
             else
             {
                 GenerateAnswer(dp, result, end + 1, cur, input);
             }
             cur.RemoveAt(cur.Count - 1);
         }
     }
 }
Example #16
0
        private void PathSum(BinaryTree node, ref int sum, List<int[]> results, List<int> data)
        {
            if (node == null)
            {
                return;
            }

            sum -= node.Value;
            data.Add(node.Value);
            if (node.Left == null && node.Right == null && sum == 0)
            {
                results.Add(data.ToArray());
            }

            PathSum(node.Left, ref sum, results, data);
            PathSum(node.Right, ref sum, results, data);

            sum += node.Value;
            data.RemoveAt(data.Count - 1);
        }
        public void PrepareData_Split1800ProvidedAndMiniTradingMade_ShouldMakeProfit()
        {
            var data = _service.PrepareData(1800);
            var forexTreeData = data[0].ForexData;

            const double spending = 10000.0;
            const double margin = 0.02;
            const double leverage = 1.0 / margin;
            var eurosSpent = 0.0;
            var profit = 0.0;
            List<double> dollarsList = new List<double>();
            foreach (var record in forexTreeData)
            {
                double dollars;
                switch (record.Action)
                {
                    case MarketAction.Hold:
                        continue;
                    case MarketAction.Buy:
                        eurosSpent += spending;
                        dollars = spending * leverage * record.Bid;
                        dollarsList.Add(MathHelpers.PreservePrecision(dollars));
                        continue;
                }

                dollars = dollarsList.First();
                dollarsList.RemoveAt(0);
                profit += dollars / record.Ask - spending * leverage;
                profit = MathHelpers.CurrencyPrecision(profit);
            }

            if (profit < 0)
            {
                Assert.Fail();
            }

            var eurosNow = eurosSpent + profit;

            Assert.AreEqual(460000.0, eurosSpent);
            Assert.AreEqual(462671.64, eurosNow);
        }
        public bool SetOfSetsCheckEqual(HashSet<HashSet<int>> set, List<HashSet<int>> tocompare)
        {
            foreach (var subset in set)
            {
                int i;
                for (i = tocompare.Count - 1; i >= 0; i--)
                {
                    if (tocompare[i].SetEquals(subset))
                    {
                        tocompare.RemoveAt(i);
                        break;
                    }
                }
                if (i == -1) // subset not found
                {
                    return false;
                }
            }

            return tocompare.Count == 0;
        }
        public Int32 Q1TripleStep(Int32 steps) // assumption that steps fists in n
        {
            List<Int32> ways = new List<Int32> { 1, 1, 2 };

            if (steps <= 1)
                return ways[steps]; // here we assume that 0 steps can be chosen in one way.

            // Hangs. Bug?
            // Contract.Assert(steps > 2);

            int stepsRemaining = steps - 2;
            while (stepsRemaining > 0)
            {
                stepsRemaining--;
                ways.Add(ways.Sum());
                ways.RemoveAt(0);
            }

            Contract.Ensures(ways.Count == 3);
            return ways.Last();
        }
        public void BinarySearchTreeDeleteTest()
        {
            for (int i = 0; i < 10; i++)
            {
                for (int j = 1; j < 100; j++)
                {
                    int[] data = Utilities.ArrayUtilities.CreateRandomArray(j, 0, BinarySearchTreeTests.MaxValue);

                    BinaryTreeNode<int> root = new BinaryTreeNode<int>(data[0]);

                    for (int k = 1; k < data.Length; k++)
                        BinarySearchTree.Insert(root, data[k]);

                    BinarySearchTreeTests.ValidateTree(root, data, data.Length);

                    List<int> list = new List<int>(data);
                    Random random = new Random();

                    while(list.Count > 0)
                    {
                        int index = random.Next(0, list.Count);
                        int x = list[index];

                        BinaryTreeNode<int> toRemove = BinarySearchTree.Find(root, x);
                        BinaryTreeNode<int> successor = BinaryTree.Delete(toRemove);

                        if (toRemove == root)
                            root = successor;

                        list.RemoveAt(index);
                        int[] remaining = list.ToArray();
                        ValidateTree(root, remaining, remaining.Length);
                    }
                }
            }
        }
        public void ChecksumDiffTest4()
        {
            List<TimeSeriesValue> duplicateList = new List<TimeSeriesValue>();

            // Create an identical array by deep copy
            foreach (TimeSeriesValue tsv in IrregList1)
            {
                duplicateList.Add(new TimeSeriesValue { Date = tsv.Date, Value = tsv.Value });
            }
            // remove a value from the middle of the list
            duplicateList.RemoveAt(150);

            TSTrace trace1 = new TSTrace { TraceNumber = 1 };
            TSTrace trace2 = new TSTrace { TraceNumber = 1 };

            Boolean ret = ComputeTestChecksums(
                    TSDateCalculator.TimeStepUnitCode.Irregular, 0, IrregList1, trace1,
                    TSDateCalculator.TimeStepUnitCode.Irregular, 0, duplicateList, trace2);

            Assert.IsFalse(ret);
        }
Example #22
0
        private void ChildTest(string filename, int lineNo, string text, int frame, params ChildInfo[] children) {
            var debugger = new PythonDebugger();
            PythonThread thread = null;
            var process = DebugProcess(debugger, DebuggerTestPath + filename, (newproc, newthread) => {
                var breakPoint = newproc.AddBreakPoint(filename, lineNo);
                breakPoint.Add();
                thread = newthread;
            });

            AutoResetEvent brkHit = new AutoResetEvent(false);
            process.BreakpointHit += (sender, args) => {
                brkHit.Set();
            };

            try {
                process.Start();

                AssertWaited(brkHit);

                var frames = thread.Frames;

                AutoResetEvent evalComplete = new AutoResetEvent(false);
                PythonEvaluationResult evalRes = null;
                Console.WriteLine("Executing {0}", text);
                frames[frame].ExecuteText(text, (completion) => {
                    evalRes = completion;
                    evalComplete.Set();
                });

                AssertWaited(evalComplete);
                Assert.IsNotNull(evalRes, "didn't get evaluation result");

                if (children == null) {
                    Assert.IsFalse(evalRes.IsExpandable, "result should not be expandable");
                    Assert.IsNull(evalRes.GetChildren(Int32.MaxValue), "result should not have children");
                } else {
                    Assert.IsNull(evalRes.ExceptionText, "exception while evaluating: " + evalRes.ExceptionText);
                    Assert.IsTrue(evalRes.IsExpandable, "result is not expandable");
                    var childrenReceived = new List<PythonEvaluationResult>(evalRes.GetChildren(Int32.MaxValue));

                    Console.WriteLine("{0} children received:", childrenReceived.Count);
                    foreach (var childReceived in childrenReceived) {
                        Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", childReceived.ChildName, childReceived.Expression, childReceived.StringRepr, childReceived.HexRepr);
                    }

                    Assert.AreEqual(children.Length, childrenReceived.Count, "received incorrect number of children");

                    for (int i = 0; i < children.Length; i++) {
                        var curChild = children[i];
                        Console.WriteLine("Finding: <{0}> (Repr: <{1}>)", curChild.ChildText, curChild.Repr ?? "(null)");

                        bool foundChild = false;
                        for (int j = 0; j < childrenReceived.Count; j++) {
                            var curReceived = childrenReceived[j];
                            Console.WriteLine("Candidate: <{0}> (Repr: <{1}>)", curReceived.ChildName, curReceived.StringRepr ?? "(null)");
                            if (ChildrenMatch(curChild, curReceived)) {
                                foundChild = true;

                                string expr = curChild.Expression;
                                if (expr == null) {
                                    if (curChild.ChildText.StartsWith("[")) {
                                        expr = text + curChild.ChildText;
                                    } else {
                                        expr = text + "." + curChild.ChildText;
                                    }
                                }

                                Assert.AreEqual(expr, curReceived.Expression);
                                Assert.AreEqual(frames[frame], curReceived.Frame);
                                childrenReceived.RemoveAt(j);
                                break;
                            }
                        }

                        Assert.IsTrue(foundChild, "failed to find " + curChild.ChildText + " found " + String.Join(", ", childrenReceived.Select(x => x.ChildName)));
                    }

                    Assert.AreEqual(0, childrenReceived.Count, "there's still some children left over which we didn't find");
                }
            } finally {
                process.Continue();
                WaitForExit(process);
            }
        }
Example #23
0
        private void TestException(
            PythonDebugger debugger,
            string filename,
            bool resumeProcess,
            ExceptionMode defaultExceptionMode,
            ICollection<KeyValuePair<string, ExceptionMode>> exceptionModes,
            PythonDebugOptions debugOptions,
            params ExceptionInfo[] exceptions
        ) {
            Console.WriteLine();
            Console.WriteLine("Testing {0}", filename);

            bool loaded = false;
            var process = DebugProcess(debugger, filename, (processObj, threadObj) => {
                loaded = true;
                processObj.SetExceptionInfo(
                    (int)defaultExceptionMode,
                    exceptionModes == null ?
                        Enumerable.Empty<KeyValuePair<string, int>>() :
                        exceptionModes.Select(m => new KeyValuePair<string, int>(m.Key, (int)m.Value))
                );
            }, debugOptions: debugOptions);

            var raised = new List<Tuple<string, string>>();
            process.ExceptionRaised += (sender, args) => {
                if (loaded) {
                    raised.Add(Tuple.Create(args.Exception.TypeName, TryGetStack(args.Thread)));
                }
                if (resumeProcess) {
                    process.Resume();
                } else {
                    args.Thread.Resume();
                }
            };

            StartAndWaitForExit(process);

            if (Version.Version == PythonLanguageVersion.V30 && raised.Count > exceptions.Length) {
                // Python 3.0 raises an exception as the process shuts down.
                raised.RemoveAt(raised.Count - 1);
            }

            if (GetType() == typeof(DebuggerTestsIpy) && raised.Count == exceptions.Length + 1) {
                // IronPython over-reports exceptions
                raised.RemoveAt(raised.Count - 1);
            }

            foreach (var t in raised) {
                Console.WriteLine("Received {0} at{1}{2}", t.Item1, Environment.NewLine, t.Item2);
            }
            AssertUtil.AreEqual(
                raised.Select(t => t.Item1),
                exceptions.Select(e => e.TypeName).ToArray()
            );
        }
Example #24
0
        public void RunMozillaTests(string folder) {
            var assembly = Assembly.GetExecutingAssembly();
            var shell = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.shell.js")).ReadToEnd();
            var extensions = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.extensions.js")).ReadToEnd();

            var resources = new List<string>();
            foreach (var resx in assembly.GetManifestResourceNames()) {
                // Ignore scripts not in /Scripts
                if (!resx.Contains(".ecma_3.") || !resx.Contains(folder)) {
                    continue;
                }

                resources.Add(resx);
            }

            resources.Sort();

            //Run the shell first if defined
            string additionalShell = null;
            if (resources[resources.Count - 1].EndsWith("shell.js")) {
                additionalShell = resources[resources.Count - 1];
                resources.RemoveAt(resources.Count - 1);
                additionalShell = new StreamReader(assembly.GetManifestResourceStream(additionalShell)).ReadToEnd();
            }

            foreach (var resx in resources) {
                var program = new StreamReader(assembly.GetManifestResourceStream(resx)).ReadToEnd();
                Console.WriteLine(Path.GetFileNameWithoutExtension(resx));

                StringBuilder output = new StringBuilder();
                StringWriter sw = new StringWriter(output);

                var jint = new JintEngine(Options.Ecmascript5) // These tests doesn't work with strict mode
                .SetDebugMode(true)
                .SetFunction("print", new Action<string>(sw.WriteLine));

                jint.Run(extensions);
                jint.Run(shell);
                jint.Run("test = _test;");
                if (additionalShell != null) {
                    jint.Run(additionalShell);
                }

                try {
                    jint.Run(program);
                    string result = sw.ToString();
                    if (result.Contains("FAILED")) {
                        Assert.Fail(result);
                    }
                }
                catch (Exception e) {
                    jint.Run("print('Error in : ' + gTestfile)");
                    Assert.Fail(e.Message);
                }
            }
        }
Example #25
0
        public void ShouldExecuteEcmascript5TestsScripts() {
            var assembly = Assembly.GetExecutingAssembly();
            var extensions = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.extensions.js")).ReadToEnd();

            var resources = new List<string>();
            foreach (var resx in assembly.GetManifestResourceNames()) {
                // Ignore scripts not in /Scripts
                if (!resx.Contains(".ecma_5.") || resx.Contains(".Scripts.")) {
                    continue;
                }

                resources.Add(resx);
            }

            resources.Sort();

            //Run the shell first if defined
            string additionalShell = null;
            if (resources[resources.Count - 1].EndsWith("shell.js")) {
                additionalShell = resources[resources.Count - 1];
                resources.RemoveAt(resources.Count - 1);
                additionalShell = new StreamReader(assembly.GetManifestResourceStream(additionalShell)).ReadToEnd();
            }

            foreach (var resx in resources) {
                var program = new StreamReader(assembly.GetManifestResourceStream(resx)).ReadToEnd();
                Console.WriteLine(Path.GetFileNameWithoutExtension(resx));

                var jint = new JintEngine()
                .SetDebugMode(true)
                .SetFunction("print", new Action<string>(System.Console.WriteLine));

                jint.Run(extensions);
                //jint.Run(shell);
                jint.Run("test = _test;");
                if (additionalShell != null) {
                    jint.Run(additionalShell);
                }

                try {
                    jint.Run(program);
                }
                catch (Exception e) {
                    jint.Run("print('Error in : ' + gTestfile)");
                    Console.WriteLine(e.Message);
                }
            }
        }
        public void Delete_StudentWithValidId_ShouldReturnDeletedResponseMsg()
        {
           
            var mockRepository = Mock.Create<DbStudentsRepository>();

            var models = new List<Student>();
            models.Add( new Student()
            {
                StudentId = 1,
                FirstName = "Peter",
                LastName = "Petrov",
                Grade = 5,
                Age = 18,
               
            });
            int idForRemoving = 1;
            Mock.Arrange(() => mockRepository.Delete(Arg.IsAny<int>()))
                .DoInstead(() => models.RemoveAt(models.FindIndex(s=>s.StudentId== idForRemoving)));

            var server = new InMemoryHttpServer<Student>("http://localhost/", mockRepository);

            var responce = server.CreateDeleteRequest("api/students/1");

            Assert.AreEqual(responce.StatusCode, HttpStatusCode.NoContent);
            Assert.IsTrue(models.Count == 0);
        }
        public void CloudBlockBlobBlockReordering()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();
                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");

                List<string> originalBlockIds = GetBlockIdList(10);
                List<string> blockIds = new List<string>(originalBlockIds);
                List<byte[]> blocks = new List<byte[]>();
                for (int i = 0; i < blockIds.Count; i++)
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(i.ToString());
                    using (MemoryStream stream = new MemoryStream(buffer))
                    {
                        blob.PutBlock(blockIds[i], stream, null);
                    }
                    blocks.Add(buffer);
                }
                blob.PutBlockList(blockIds);
                Assert.AreEqual("0123456789", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(0);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("123456789", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(8);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("12345678", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(3);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("1235678", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[9]))
                {
                    blob.PutBlock(originalBlockIds[9], stream, null);
                }
                blockIds.Insert(0, originalBlockIds[9]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("91235678", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[0]))
                {
                    blob.PutBlock(originalBlockIds[0], stream, null);
                }
                blockIds.Add(originalBlockIds[0]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("912356780", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[4]))
                {
                    blob.PutBlock(originalBlockIds[4], stream, null);
                }
                blockIds.Insert(2, originalBlockIds[4]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("9142356780", DownloadText(blob, Encoding.UTF8));

                blockIds.Insert(0, originalBlockIds[0]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("09142356780", DownloadText(blob, Encoding.UTF8));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Example #28
0
        public void TimedTest_AccessQuery()
        {
            var times = new List<long>();
            var profiler = new Stopwatch();

            using (var db = CreateAccessDB())
            {
                for (int i = 1; i <= 4; i++)
                {
                    profiler.Restart();

                    var products = db.Query<Product>().FromView("V_Product").Graph().ToList();

                    profiler.Stop();

                    if (products.Count == 0)
                        throw new Exception("Result set was empty");

                    Trace.WriteLine(string.Format("iteration {0} : {1}ms", i, profiler.ElapsedMilliseconds));
                    times.Add(profiler.ElapsedMilliseconds);
                }
            }

            Trace.WriteLine("---------------");
            times.RemoveAt(0);
            Trace.WriteLine(string.Format("Average time after inital load: {0}", times.Average()));
        }
Example #29
0
        public void TimedTest_PassingInQueryText()
        {
            var times = new List<long>();
            var profiler = new Stopwatch();

            using (var db = CreateAccessDB())
            {
                db.SqlMode = SqlModes.Text;

                for (int i = 1; i <= 4; i++)
                {
                    profiler.Restart();

                    string sql = @"SELECT Product.ID, Product.Name, Product.Description, Product.Price, Product.CategoryID, Product.ImageFileName, Product.NewItem, Product.IsSplash, Category.Name AS CategoryName, Option.OptionTypeID, OptionType.Type, OptionType.MultiPick, Option.ID AS OptionID, Option.Description AS OptionDescription, Option.Price AS OptionPrice
                                   FROM ((Category LEFT JOIN OptionType ON Category.ID = OptionType.CategoryID) RIGHT JOIN Product ON Category.ID = Product.CategoryID) LEFT JOIN [Option] ON OptionType.ID = Option.OptionTypeID;";
                    var products = db.Query<Product>().QueryText(sql).Graph().ToList();

                    profiler.Stop();

                    if (products.Count == 0)
                        throw new Exception("Result set was empty");

                    Trace.WriteLine(string.Format("iteration {0} : {1}ms", i, profiler.ElapsedMilliseconds));
                    times.Add(profiler.ElapsedMilliseconds);
                }
            }

            Trace.WriteLine("---------------");
            times.RemoveAt(0);
            Trace.WriteLine(string.Format("Average time after inital load: {0}", times.Average()));
        }
		public void MustGenereteDiffrentHashForDiffierentString()
		{
			var messageService = new MessageService();
			var hashes = new List<long>();
			for (int i = 0; i < 10000; i++)
			{
				hashes.Add(messageService.CreateMessageHash(new MessageDefinition
				{
					MessageId = Guid.NewGuid().ToString() + i
				}));
			}
			int c = 0;
			while (hashes.Count > 0)
			{
				c++;
				var l = hashes[0];
				hashes.RemoveAt(0);
				Assert.IsFalse(hashes.Contains(l), string.Format("Count: {0} for {1}", c, l));
			}
		}