/// <summary> /// Verifies that the expected collection events are raised from the <see cref="ValidationResultCollection"/> /// for validation results with the specified member names. /// </summary> /// <param name="validationResultMemberNames"> /// The array of member names to create validation results for that will be /// added and removed from the collection. /// </param> /// <param name="errorsChangedMemberNames">The array of member names to expect errors changed events for.</param> private static void VerifyAddRemoveCollectionEvents(string[] validationResultMemberNames, string[] errorsChangedMemberNames) { int collectionChangedCount = 0; int hasErrorsChangedCount = 0; List<string> propertyErrorsChangedList = new List<string>(); Action collectionChanged = () => ++collectionChangedCount; Action hasErrorsChanged = () => ++hasErrorsChangedCount; Action<string> propertyErrorsChanged = propertyName => propertyErrorsChangedList.Add(propertyName); ValidationResultCollection collection = new TestValidationResultCollection(collectionChanged, hasErrorsChanged, propertyErrorsChanged); ValidationResult vr1 = new ValidationResult("Error 1", validationResultMemberNames); collection.Add(vr1); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first add"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for first add"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for first add"); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); ValidationResult vr2 = new ValidationResult("Error 2", validationResultMemberNames); collection.Add(vr2); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second add"); Assert.AreEqual<int>(0, hasErrorsChangedCount, "HasErrorsChanged count for second add"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for second add"); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); collection.Remove(vr1); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first remove"); Assert.AreEqual<int>(0, hasErrorsChangedCount, "HasErrorsChanged count for first remove"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for first remove"); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); collection.Remove(vr2); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second remove"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for second remove"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList for second remove"); }
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"); }
public void PartitionEvenlyWorks() { var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15 }; var partitions = list.PartitionEvenly(i => i * 2, 3).ToList(); Assert.AreEqual(3, partitions.Count); // Partition size are well-defined if the # of elements is not exactly a factor of the partition count. Assert.AreEqual(4, partitions[0].Count); Assert.AreEqual(4, partitions[1].Count); Assert.AreEqual(3, partitions[2].Count); // We don't care about what particular elements are inside the partitions, // but we do care that they are all the same weight Assert.AreEqual(26, partitions[0].Aggregate((x, y) => x + y)); Assert.AreEqual(26, partitions[1].Aggregate((x, y) => x + y)); Assert.AreEqual(26, partitions[2].Aggregate((x, y) => x + y)); // All the elements of the initial list must be present in the union of the partitions. Assert.IsTrue(list.OrderBy(x => x).SequenceEqual(partitions.SelectMany(x => x).OrderBy(x => x))); }
private static void PrintSchedule(List<Employee> employees, List<Duty> duties) { var maxNameLength = employees.Max(x => x.Name.Length); duties = duties.OrderBy(x => x.Timeslot).ToList(); Debug.Write(new string(' ', maxNameLength + Padding)); Debug.Write(String.Join(" ", duties.Select(x => x.Timeslot))); Debug.WriteLine(""); foreach (var employee in employees) { Debug.Write(employee.Name.PadRight(maxNameLength + Padding)); foreach (var duty in duties) { if (duty.Employee.Equals(employee)) { Debug.Write("X"); } else { Debug.Write(" "); } Debug.Write(" "); } Debug.Write(" "); PrintStatistics(employee, duties.Where(x => Equals(x.Employee, employee)).ToList()); Debug.WriteLine(""); } }
public void GetExecutionPlan_WhereTaskHasDependencyNotSpecifiedForHost_AddsDependencyToPlan() { // Arrange var taskblock = typeof(InheritDependencies); var host = new Host { Hostname = SomeHostname }; var config = new DeploymentConfig { Hosts = new[] { host } }; var expected = new List<ExecutionPlan> { new ExecutionPlan(host, taskblock.GetObjMethods("Task1", "Task2")) }; // Act var manager = new DeploymentManager<InheritDependencies>(config); var actual = manager.GetExecutionPlans(); // Assert CollectionAssert.AreEqual( expected.OrderBy(p => p.Host.Hostname).ToList(), actual.OrderBy(p => p.Host.Hostname).ToList()); }
public void FindByTitleAndPriceRange_AddMultipleProducts_ShouldReturnCorrectOnes() { var products = new ProductsCollection(); var expectedProducts = new List<Product>(); decimal price = 1.0m; for (int i = 99; i >= 0; i--) { string title = string.Empty; if (i % 5 == 0 && price <= 15) { title = "magnit"; var product = new Product(i, title, "Bai Tosho" + i, price); expectedProducts.Add(product); products.Add(i, title, "Bai Tosho" + i, price); price++; } else { title = "magnit" + i; products.Add(i, title, "Bai Tosho" + i, 0.5m); } } expectedProducts = expectedProducts.OrderBy(p => p.Id).ToList(); var actualProducts = products .FindProductsTitleAndPriceRange("magnit", 1.0m, 15.0m) .ToList(); CollectionAssert.AreEqual(expectedProducts, actualProducts); }
protected Diagnostic[] GetDiagnostics(IEnumerable<string> sourceCodes) { DiagnosticAnalyzer analyzer = GetDiagnosticAnalyzer(); Project project = CreateProject(sourceCodes); CompilationWithAnalyzers compilationWithAnalyzers = project.GetCompilationAsync().Result .WithAnalyzers(ImmutableArray.Create(analyzer)); ImmutableArray<Diagnostic> analyzerDiagnostics = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; List<Diagnostic> diagnostics = new List<Diagnostic>(analyzerDiagnostics.Length); foreach (Diagnostic diagnostic in analyzerDiagnostics) { if (diagnostic.Location == Location.None || diagnostic.Location.IsInMetadata) diagnostics.Add(diagnostic); else { SyntaxTree tree; foreach (Document doc in project.Documents) { tree = doc.GetSyntaxTreeAsync().Result; if (tree == diagnostic.Location.SourceTree) diagnostics.Add(diagnostic); } } } return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); }
public void SortDependenciesTest() { // Columns indicate direct dependencies // 0 1 2 3 4 //0 • • //1 • • • • //2 • • //3 • • //4 • var schemas = new List<TableSchema>(); schemas.Add(new TableSchema("0")); schemas.Add(new TableSchema("1")); schemas.Add(new TableSchema("2")); schemas.Add(new TableSchema("3")); schemas.Add(new TableSchema("4")); schemas[4].Columns.AddForeignKey("4 -> 3", schemas[3], "4 -> 3"); schemas[4].Columns.AddForeignKey("4 -> 1", schemas[1], "4 -> 1"); schemas[3].Columns.AddForeignKey("3 -> 2", schemas[2], "3 -> 2"); schemas[2].Columns.AddForeignKey("2 -> 1", schemas[1], "2 -> 1"); schemas[3].Columns.AddForeignKey("3 -> 1", schemas[1], "3 -> 1"); schemas[1].Columns.AddForeignKey("1 -> 0", schemas[0], "1 -> 0"); var rand = new Random(); for (int i = 0; i < 10; i++) //Test different orderings Assert.IsTrue(schemas.OrderBy(j => rand.Next()).SortDependencies().ToArray().SequenceEqual(schemas)); }
public void GetEnumerator_IfItemsToRemovePresentAtStart_ThenTheyAreNeverYielded() { using (var cts = new CancellationTokenSource()) { var input = new string[] { "a", "bad one", "b" }; var results = new List<string>(new ReadyItemCollection<string>(input, cts.Token, item => { if (item == "bad one") return null; else return true; }, item => DateTime.UtcNow.AddMilliseconds(10))); Assert.IsTrue(results.OrderBy(i => i).SequenceEqual(new string[] { "a", "b" })); } }
public void what_is_comparer() { var now = DateTime.Now; var v1 = new DataHolder(now); var v2 = new DataHolder(now); var list = new List<DataHolder>() { v1, v2 }; list.OrderBy(x => x); //var comparer = Comparer<DataHolder>.Default; //Assert.IsFalse(comparer.Compare(v1, v2) == 0); }
private static IEnumerable<Event> GetFakeHistory(int nrOfVisitors) { var history = new List<Event>(); for (var i = 0; i < nrOfVisitors; i++) { history.AddRange(GetVisitorEvents(Guid.NewGuid())); } return history.OrderBy(e => e.Version); }
public void TestSorting() { var doc1 = new TestDocument(); var doc2 = new TestDocument(); var docList = new List<TestDocument>() { doc1, doc2 }; var sorting = docList[0].OrderBy(); var result = docList.OrderBy(sorting).ToList(); Assert.IsTrue(result[0] == doc1); }
public void GetEnumerator_IfAvailableItemsExistAtStart_ThenTheyAreAllYieldedQuickly() { using (var cts = new CancellationTokenSource()) { var input = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; var sw = new Stopwatch(); sw.Start(); var results = new List<string>(new ReadyItemCollection<string>(input, cts.Token, item => true, item => DateTime.UtcNow.AddMinutes(1))); sw.Stop(); Assert.IsTrue(results.OrderBy(f => f).SequenceEqual(input)); Assert.IsTrue(sw.ElapsedMilliseconds < 1000, String.Format("That took too long ({0} milliseconds)!", sw.ElapsedMilliseconds)); } }
private static void RegroupWorkersTestHelper(List<int> faultDomains, List<int> expectedBuddyGroups) { ServerRole_Accessor target = new ServerRole_Accessor(); IEnumerable<Worker> workers = faultDomains.Select(fd => new Worker(Guid.NewGuid().ToString(), null, fd)); int currentBuddyGroup = 1; List<string> actualBuddyGroups = target.RegroupWorkers(workers, () => currentBuddyGroup++.ToString()) .Select(worker => worker.BuddyGroupID).OrderBy(bg => bg).ToList(); CollectionAssert.AreEqual( expectedBuddyGroups.OrderBy(bg => bg).Select(buddyGroup => buddyGroup.ToString()).ToList(), actualBuddyGroups); }
public void GivenFilterLimitsResults_WhenBind_ThenResultTotalDisplayRecordsMatchesFilteredCount() { IQueryable<Program> originalItems = new List<Program> { new Program(), new Program(), new Program() }.AsQueryable(); IQueryable<Program> filteredItems = new List<Program> { new Program() }.AsQueryable(); IQueryable<Program> sortedItems = filteredItems.OrderBy(p => p); DataTable.Expect(m => m.ApplyFilters(originalItems)).Return(filteredItems); DataTable.Expect(m => m.ApplySort(filteredItems)).Return(sortedItems); DataTable.Expect(m => m.CreateResultSet(sortedItems, RequestModel)).Return(sortedItems.Cast<object>().ToList()); DataTableResultModel actual = Target.Bind<Program>(originalItems, DataTable, RequestModel); Assert.AreEqual(filteredItems.Count(), actual.iTotalDisplayRecords); }
public void ConvertThreeParametersReference() { // This is a reference for how a path is parsed and the various components extracted. var result = RouteParser.ConvertPatternToRegularExpression("/{prop}/Toy/{name}/{price}/Cost/{currency}/{value}", true); Assert.AreEqual("^(/)(?<resourceIdentifier>.*?)()(?<resourceName>/Toy/)(?<resourceIdentifier>.*?)()(/)(?<resourceIdentifier>.*?)()(?<resourceName>/Cost/)(?<resourceIdentifier>.*?)()(/)(?<resourceIdentifier>.*?)()$", result); var candidate = "/candidate/Toy/Bone/50/Cost/dollar/85"; var matches = Regex.Matches(candidate, result, RegexOptions.ExplicitCapture); // We now need to extract the resourceNames and resourceIdentifiers. By sorting their start index, we can work out the order in which // they occurred and then walk an in-memory database. var resourceNames = matches[0].Groups["resourceName"]; var resourceIdentifiers = matches[0].Groups["resourceIdentifier"]; List<Placeholder> parsed = new List<Placeholder>(); foreach (Capture n in resourceNames.Captures) { parsed.Add(new Placeholder() { Type = "resourceName", Value = n.Value.Replace("/", ""), Index = n.Index }); } foreach(Capture n in resourceIdentifiers.Captures) { parsed.Add(new Placeholder() { Type = "resourceIdentifier", Value = n.Value, Index = n.Index }); } parsed = parsed.OrderBy(f => f.Index).ToList(); Assert.AreEqual("resourceIdentifier", parsed[0].Type); Assert.AreEqual("candidate", parsed[0].Value); Assert.AreEqual("resourceName", parsed[1].Type); Assert.AreEqual("Toy", parsed[1].Value); Assert.AreEqual("resourceIdentifier", parsed[2].Type); Assert.AreEqual("Bone", parsed[2].Value); Assert.AreEqual("resourceIdentifier", parsed[3].Type); Assert.AreEqual("50", parsed[3].Value); Assert.AreEqual("resourceName", parsed[4].Type); Assert.AreEqual("Cost", parsed[4].Value); Assert.AreEqual("resourceIdentifier", parsed[5].Type); Assert.AreEqual("dollar", parsed[5].Value); Assert.AreEqual("resourceIdentifier", parsed[6].Type); Assert.AreEqual("85", parsed[6].Value); }
public void IndividualTest() { List<Individual> list = new List<Individual>(); Individual i = null; for(int j = 0; j < 5; j++) { i = new Individual(); i.Distance = j; list.Add(i); } var expectedList = list.OrderBy(x => x.Distance); list.Sort(); Assert.IsTrue(expectedList.SequenceEqual(list)); }
public void GetEnumerator_IfNonReadyItemsExistAtStart_ThenYieldsThemQuicklyWhenReady() { using (var cts = new CancellationTokenSource()) { var input = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; TimeSpan delay = TimeSpan.FromSeconds(3); DateTime timeAvailable = DateTime.UtcNow.Add(delay); var sw = new Stopwatch(); sw.Start(); var results = new List<string>(new ReadyItemCollection<string>(input, cts.Token, item => DateTime.UtcNow >= timeAvailable, item => DateTime.UtcNow.AddMilliseconds(200))); sw.Stop(); Assert.IsTrue(results.OrderBy(f => f).SequenceEqual(input)); var minimumMilliseconds = delay.Milliseconds - 200; // Subtract a margin of error because timings are not always exact. Assert.IsTrue(sw.Elapsed.Milliseconds >= minimumMilliseconds, String.Format("Didn't wait for the items to become ready. The items were obtained in {0} milliseconds.", sw.ElapsedMilliseconds)); Assert.IsTrue(sw.Elapsed.Milliseconds <= delay.Milliseconds + 1000, String.Format("That took too long ({0} milliseconds)!", sw.ElapsedMilliseconds)); } }
public void FindFiles() { string processFileListPath = @"TestData\ProcessedMeasureFilesList.txt"; List<String> fileList = new List<String>(); using (StreamReader sr = new StreamReader(processFileListPath)) { while (!sr.EndOfStream) { string file = sr.ReadLine(); fileList.Add(file); } fileList.OrderBy(x => x).ToList(); } if (fileList != null || fileList.Count != 0) { Console.WriteLine("vdd"); } }
public void Cards() { var testCases = new List<Tuple<Card, int>> { Tuple.Create(new Card(Rank.King), 4), Tuple.Create(new Card(Rank.Five), 1), Tuple.Create(new Card(Rank.Ace), 0), Tuple.Create(new Card(Rank.Nine), 2), Tuple.Create(new Card(Rank.Jack), 3), }; var orderStrategy = new StandardOrder(); foreach (var testcase in testCases) { var sortedByOrderStrategy = testCases.OrderBy(c => orderStrategy.Order(c.Item1)).ToList(); Assert.AreEqual(testcase.Item2, sortedByOrderStrategy.IndexOf(testcase)); } }
public void DeckInitialisedWithCorrectCardsFromItemList() { List<Item> items = new List<Item>() { new Item() { Name = "TestItem1", Cards = new List<Card>() { new Card() {Name = "TestCard1"} } }, new Item() { Name = "TestItem2", Cards = new List<Card>() { new Card() {Name = "TestCard2"} } }, new Item() { Name = "TestItem3", Cards = new List<Card>() { new Card() {Name = "TestCard2"} } } }; List<Card> cards = new List<Card>(); cards.Add(new Card() { Name = "TestCard2" }); cards.Add(new Card() { Name = "TestCard2" }); cards.Add(new Card() { Name = "TestCard1" }); Deck deck = Deck.CreateFromItemList(items); CollectionAssert.AreEqual( deck.Cards.OrderBy(x => x.Name).ToList(), cards.OrderBy(x => x.Name).ToList(), Comparer<Card>.Create((x, y) => (string.Compare(x.Name, y.Name))), "Deck contains correct list of cards."); }
public void QueryableFromRepository() { using (var container = new RhetosTestContainer()) { var createdConcepts = new List<string>(); var serializedInfo = new StringBuilder(); var createQuery = new StringBuilder(); container.Resolve<ISqlExecuter>().ExecuteReader( "SELECT DISTINCT InfoType, SerializedInfo, CreateQuery FROM Rhetos.AppliedConcept WHERE SerializedInfo LIKE '%>TestAllPropertiesCopyAllFeatures<%'", reader => { createdConcepts.Add(reader.GetString(0).Split(',')[0]); serializedInfo.AppendLine(reader.GetString(1)); createQuery.AppendLine(reader.GetString(2)); }); Console.WriteLine("Copied concepts:"); foreach (var createdConcept in createdConcepts.OrderBy(x => x)) Console.WriteLine(" - " + createdConcept); foreach (var expected in _expectedConcepts) Assert.IsTrue(createdConcepts.Contains(expected.FullName), "'" + expected.FullName + "' was not copied."); Console.WriteLine("Create query:"); Console.WriteLine(createQuery); Assert.IsTrue(new Regex(@"TestAllPropertiesCopyAllFeatures.*TheParentID.*ON DELETE CASCADE", RegexOptions.Singleline) .IsMatch(createQuery.ToString()), "Property 'TheParentID' should have cascade delete copied from the source data structure."); TestUtility.AssertContains( serializedInfo.ToString(), new [] { "<PropertyNames>Name</PropertyNames>", "<PropertyNames>Name Start</PropertyNames>", "<PropertyNames>Name Start TheParent</PropertyNames>" }, "These 3 indexes expected"); } }
public void TestPropTesterBasic() { var matched = new List<string>(); var not_matched = new List<string>(); var should_matched = new List<string> { "steve", "jeff" }; var should_not_matched = new List<string> { "jimbo", "george" }; var tester = new TreeBuilder<DataClass>(); tester.Push("name", "steve", comparison.Equals) .Push("name", "jeff", comparison.Equals) .Or(); var lambda = tester.Build(); foreach (var item in MakeSomeDataObjs()) { if (lambda(item)) matched.Add(item.name); else not_matched.Add(item.name); } Assert.IsTrue(Enumerable.SequenceEqual(matched.OrderBy(p => p), should_matched.OrderBy(p => p))); Assert.IsTrue(Enumerable.SequenceEqual(not_matched.OrderBy(p => p), should_not_matched.OrderBy(p => p))); }
public void TestAddingDuplicatedElements() { SortedDeque<int> sortedDeque = new SortedDeque<int>(); List<int> valuesToAdd = new List<int> { 2, 1, 9, 1, 5, 2, 9 }; for (int i = 0; i < valuesToAdd.Count; ++i) sortedDeque.Insert(valuesToAdd[i]); valuesToAdd = valuesToAdd.OrderBy(x => x).ToList(); List<int> uniqueValues = new List<int>(valuesToAdd).Distinct().ToList(); for (int i = 0; i < uniqueValues.Count; ++i) { Assert.AreEqual(uniqueValues.ElementAt(i), sortedDeque.At(i)); } Assert.IsFalse(sortedDeque.Empty()); Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeTotal); Assert.AreEqual(uniqueValues.Count, sortedDeque.SizeUnique); Assert.AreEqual(1, sortedDeque.NumberOfBuckets); }
public void TestAddingGreaterValueWhenFirstBucketIsFull() { int SIZE_OF_BUCKET = 3; SortedDeque<int> sortedDeque = new SortedDeque<int>(SIZE_OF_BUCKET); List<int> valuesToAdd = new List<int> { 2, 1, 9 }; for (int i = 0; i < valuesToAdd.Count; ++i) sortedDeque.Insert(valuesToAdd[i]); valuesToAdd = valuesToAdd.OrderBy(x => x).ToList(); for (int i = 0; i < valuesToAdd.Count; ++i) { Assert.AreEqual(valuesToAdd.ElementAt(i), sortedDeque.ElementAt(i)); } Assert.IsFalse(sortedDeque.Empty()); Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeTotal); Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeUnique); Assert.AreEqual(SIZE_OF_BUCKET, sortedDeque.Capacity); Assert.AreEqual(1, sortedDeque.NumberOfBuckets); ///////////////////////////////////////////////////////// const int valueGreaterThanPreviousValuesToAdd = 100; sortedDeque.Insert(valueGreaterThanPreviousValuesToAdd); Assert.IsTrue(sortedDeque.Back == valueGreaterThanPreviousValuesToAdd); Assert.IsFalse(sortedDeque.Empty()); Assert.AreEqual(valuesToAdd.Count + 1, sortedDeque.SizeTotal); Assert.AreEqual(valuesToAdd.Count + 1, sortedDeque.SizeUnique); Assert.AreEqual(2 * SIZE_OF_BUCKET, sortedDeque.Capacity); Assert.AreEqual(2, sortedDeque.NumberOfBuckets); }
// permute L then compare works, but would generate too many string[], and out of memory // note: in L, all the words have same length! // so for every detetion, string can be split into l.Lenght parts public int[] FindSubstring(string s, string[] l) { // build word count from L first, dup words can be handled like this Dictionary<string, int> wordCount = new Dictionary<string, int>(); l.ToList().ForEach(w => wordCount[w] = wordCount.ContainsKey(w) ? wordCount[w] + 1 : 1); int slotLength = l[0].Length; int totalpartLenght = l.Sum(p => p.Length); var answer = new List<int>(); for (int i = 0; i <= slotLength - 1; i++) { Dictionary<string, int> currentRemaing = new Dictionary<string, int>(wordCount); for (int j = i + slotLength; j <= s.Length; j += slotLength) { int remainingCount = l.Length; string newInSlot = s.Substring(j - slotLength, slotLength); if (currentRemaing.ContainsKey(newInSlot)) { currentRemaing[newInSlot] -= 1; } if (j - i > totalpartLenght) // offset previous slot before current detection area { string preSlot = s.Substring(j - totalpartLenght - slotLength, slotLength); if (currentRemaing.ContainsKey(preSlot)) { currentRemaing[preSlot] += 1; } } if (currentRemaing.Values.All(n => n == 0)) // all the word captured, must hit answer { answer.Add(j - totalpartLenght); } } } return answer.OrderBy(a => a).ToArray(); }
/// <summary> /// Verifies that the expected collection events are raised from the <see cref="ValidationResultCollection"/> /// when <see cref="ValidationResultCollection.ReplaceErrors"/> is called for a property. /// </summary> /// <param name="member">The property that errors are being replaced for</param> /// <param name="replacementResults">The results to use as the replacement errors for the property for the replacement.</param> /// <param name="errorsChangedMembers">The array of member names to expect errors changed events for.</param> private static void VerifyPropertyReplacementEvents(string member, IEnumerable<ValidationResult> replacementResults, string[] errorsChangedMembers) { int collectionChangedCount = 0; int hasErrorsChangedCount = 0; List<string> propertyErrorsChangedList = new List<string>(); Action collectionChanged = () => ++collectionChangedCount; Action hasErrorsChanged = () => ++hasErrorsChangedCount; Action<string> propertyErrorsChanged = propertyName => propertyErrorsChangedList.Add(propertyName); ValidationResultCollection collection = new TestValidationResultCollection(collectionChanged, hasErrorsChanged, propertyErrorsChanged); collection.ReplaceErrors(member, replacementResults); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first replacement"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for first replacement"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMembers.OrderBy(s => s)), "propertyErrorsChangedList for first replacement"); collection.Add(new ValidationResult("Error", new string[] { member })); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); collection.ReplaceErrors(member, replacementResults); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second replacement"); Assert.AreEqual<int>(0, hasErrorsChangedCount, "HasErrorsChanged count for second replacement"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMembers.OrderBy(s => s)), "propertyErrorsChangedList for second replacement"); }
public void ClearRaisesEvents() { int collectionChangedCount = 0; int hasErrorsChangedCount = 0; List<string> propertyErrorsChangedList = new List<string>(); Action collectionChanged = () => ++collectionChangedCount; Action hasErrorsChanged = () => ++hasErrorsChangedCount; Action<string> propertyErrorsChanged = propertyName => propertyErrorsChangedList.Add(propertyName); ValidationResultCollection collection = new TestValidationResultCollection(collectionChanged, hasErrorsChanged, propertyErrorsChanged); collection.Add(new ValidationResult("Property Error", new string[] { "Member" })); collection.Add(new ValidationResult("Entity Error", null)); string[] errorsChangedMemberNames = new string[] { "Member", null }; Assert.AreEqual<int>(2, collectionChangedCount, "collectionChangedCount after adding"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "hasErrorsChangedCount after adding"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList after adding"); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); collection.Clear(); // We only get one collection changed event because it's an atomic action Assert.AreEqual<int>(1, collectionChangedCount, "collectionChangedCount after clearing"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "hasErrorsChangedCount after clearing"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(errorsChangedMemberNames.OrderBy(s => s)), "propertyErrorsChangedList after clearing"); }
public void ReplaceAllResultsWithNothing() { // This test differs from the other replacement tests enough that it doesn't use the same helper method string member = "Member"; string[] memberNames = new string[] { member }; string[] replacementNames = new string[] { member }; IEnumerable<ValidationResult> initialResults = new ValidationResult[] { new ValidationResult("Error", memberNames) }; IEnumerable<ValidationResult> replacementResults = Enumerable.Empty<ValidationResult>(); int collectionChangedCount = 0; int hasErrorsChangedCount = 0; List<string> propertyErrorsChangedList = new List<string>(); Action collectionChanged = () => ++collectionChangedCount; Action hasErrorsChanged = () => ++hasErrorsChangedCount; Action<string> propertyErrorsChanged = propertyName => propertyErrorsChangedList.Add(propertyName); ValidationResultCollection collection = new TestValidationResultCollection(collectionChanged, hasErrorsChanged, propertyErrorsChanged); collection.ReplaceErrors(initialResults); Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for first replacement"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for first replacement"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(replacementNames.OrderBy(s => s)), "propertyErrorsChangedList for first replacement"); collection.Add(new ValidationResult("Error", new string[] { member })); collectionChangedCount = 0; hasErrorsChangedCount = 0; propertyErrorsChangedList.Clear(); collection.ReplaceErrors(replacementResults); // Notice that HasErrors changes again because we no longer have any errors Assert.AreEqual<int>(1, collectionChangedCount, "CollectionChanged count for second replacement"); Assert.AreEqual<int>(1, hasErrorsChangedCount, "HasErrorsChanged count for second replacement"); Assert.IsTrue(propertyErrorsChangedList.OrderBy(s => s).SequenceEqual(replacementNames.OrderBy(s => s)), "propertyErrorsChangedList for second replacement"); }
public void GetDataPageableTest() { PagedResult<AssertType> expectedResult; _repository .Setup(it => it.GetDataPageable(It.IsAny<String>(), It.IsAny<Int32>(), It.IsAny<Int32>())) .Returns<String, Int32, Int32>((sortExpression, page, pageSize) => { var query = _repositoryList; switch (sortExpression) { case "Id": query = new List<AssertType>(query.OrderBy(q => q.Id)); break; case "Name": query = new List<AssertType>(query.OrderBy(q => q.Name)); break; } return query.Take(pageSize).Skip((page-1)*pageSize).ToList(); }); _repository .Setup(it => it.GetRowCount()) .Returns(_repositoryList.Count); var result = _target.GetDataPageable("Id", 1, 2); Assert.IsTrue(result.TryGetContentValue(out expectedResult)); Assert.AreEqual(_repositoryList.Take(2).ToList().Count, expectedResult.Results.Count); Assert.AreEqual(_repositoryList.OrderBy(q => q.Id).FirstOrDefault().Id, expectedResult.Results.FirstOrDefault().Id); }