private static void CreateMetadata(List <Ui5Complex> results) { var fullclasslist = results.Flatten(x => x.Content).OfType <Ui5Class>().ToList(); foreach (Ui5Class c in fullclasslist) { c.CreateMetadata(); } var fullinterfacelist = results.Flatten(x => x.Content).OfType <Ui5Interface>(); foreach (Ui5Class c in fullclasslist) { c.ConnectMetadata(fullinterfacelist); } }
public void Utilities_DistinctBy() { var list1 = new List <Example> { new Example("e1") { Children = new List <Example> { new Example("some"), new Example("e4") } }, new Example("e2") { Children = new List <Example> { new Example("e2"), new Example("some") } }, }; var list = list1.Flatten((item) => item.Children); var result = Utilities.DistinctBy <Example, string>(list, (item) => { return(item.Name); }); var resultArray = result.ToArray(); Assert.AreEqual(4, resultArray.Length); Assert.AreEqual(list1[0].Children[0], resultArray[0]); Assert.AreEqual(list1[0].Children[1], resultArray[1]); Assert.AreEqual(list1[1].Children[0], resultArray[2]); Assert.AreEqual(list1[0], resultArray[3]); }
public void FlattenTest() { var numbers = new List <List <int> > { new List <int> { 0, 1, 2, 3 }, new List <int> { 4, 5 }, new List <int>(0), new List <int> { 6 }, new List <int> { 7, 8 }, new List <int> { 9, 10, 11, 12 }, }; var flattened = numbers.Flatten().ToArray(); var flattenedSelectMany = numbers.SelectMany(a => a).ToArray(); Assert.AreEqual(flattenedSelectMany, flattened); }
/// <summary> /// Drills down into succesive column combinations, combining the results. /// <para> /// For example: We have columns {A, B, C, D} /// First, this will get counts for {A}, {B}, {C}, {D}. /// then: {A, B}, {A, C}, {A, D} - ONLY if {A} returned no suppressed columns /// then: {B, A}, {B, C}, {B, D} - ONLY if {B} returned no suppressed columns /// etc... /// then: {A, B, C, D} - ONLY if {A, B, C} returned no suppressed columns /// then: {A, B, D, C} - ONLY if {A, B, D} returned no suppressed columns /// etc. /// </para> /// <para> /// Thus, it 'searches' the data sets, grouping by ever increasing column combinations, until it reaches a /// 'dead-end' where the combination is suppressed. /// </para> /// </summary> /// <param name="context">An <see cref"ExplorerContext" /> containing the query execution method.</param> /// <param name="projections"> /// A list of <see cref="ColumnProjection" />s defining how to segment the columns into buckets. /// </param> /// <param name="maxLevel"> /// The maximum number of columns to include in a subgrouping, or null for all columns. /// </param> /// <returns>A Task that resolves to a list of query result rows.</returns> public static async Task <IEnumerable <MultiColumnCounts.Result> > DrillDown( ExplorerContext context, IEnumerable <ColumnProjection> projections, int?maxLevel = null) { maxLevel ??= projections.Count(); var numLevels = Math.Min(maxLevel.Value, projections.Count()); var allLevels = new List <IEnumerable <MultiColumnCounts.Result> >(numLevels); var rootLevel = await context.Exec(new MultiColumnCountsPartial(projections)); allLevels.Add(rootLevel.Rows); foreach (var depth in Enumerable.Range(1, numLevels - 1)) { var currentLevel = allLevels[depth - 1]; var nextLevel = await DrillDownNextLevel(context, projections, currentLevel, depth); if (!nextLevel.Any()) { break; } allLevels.Add(nextLevel.ToList()); } return(allLevels.Flatten()); }
public void Append_WhenSubCollectionIsNull_SkipsSubCollection() { var expected = new List <int> { 167, 36, 21, 12, 372165, 234733, 14, 247 }; var items = new List <List <int> > { new List <int> { 167, 36 }, new List <int> { 21 }, null, new List <int> { }, new List <int> { 12, 372165, 234733, 14, 247 }, }; var result = items.Flatten(); CollectionAssert.AreEqual(expected, result); }
public void TestFlatten() { var area = new AreaInstance { Name = "root" }; var child1 = new AreaInstance { Name = "child1" }; var child2 = new AreaInstance { Name = "child2" }; area.InverseThis2ParentNavigation.Add(child1); child1.InverseThis2ParentNavigation.Add(child2); var list = new List <AreaInstance>(); list.Add(area); var flatten = list.Flatten(a => a.InverseThis2ParentNavigation).ToList(); Assert.NotNull(flatten); Assert.Equal(3, flatten.Count); }
/// <summary> /// Create multiple items /// </summary> /// <remarks> /// All other forms of create should call this one. Provides an event /// (OnItemCreate) to be used by attribute repos to perform their own /// actions after an item is created (such as create and persist /// attribute data) /// </remarks> /// <param name="items">List of items to create</param> /// <returns>List of items created</returns> override public List <Item> Create(List <Item> items) { if (items == null) { throw new BotDatabaseException("Can not create null items"); } // Base create may modify the original parameter and copy // siblings into children if their parentId is set. This // may cause a single item to appear multiple times in the // constructed object tree. base.Create(items); // Flatten then normalize the tree of items var flattenedItems = items.Flatten(); if (OnItemCreate != null) { void InvokeOnItemCreate(List <Item> invokeItems) { invokeItems.ForEach(item => { OnItemCreate(item); if (item.Children != null && item.Children.Count > 0) { InvokeOnItemCreate(item.Children); } }); }; InvokeOnItemCreate(flattenedItems); } return(items); }
public static Maybe <List <DPosThckRflt> > GetIPSDatas(string ipsPath, string klaPah) { ipsPath = Path.GetDirectoryName(ipsPath); FileNames filenames = Just(ipsPath) .Bind(GetAllDirs) .Map(GetAllFileNames); if (!CheckFiles(filenames)) { return(None); } var numOfClass = filenames.Select(GetNumOfClass).ToList(); var wave = GetDataWith(ReadWaveLen, RfltFilter, filenames).First().Datas.First().Value; var thckness = GetDataWith(ReadPos, ThckFilter, filenames); var rflts = GetDataWith(ReadReflectivity, RfltFilter, filenames); var Total = thckness.Zip(rflts, (f, s) => f.ToTuple(s)).ToList(); //var Total = ToClsNumWihtThckRflt(numOfClass , thckness , rflts ); List <List <DPosThckRflt> > totallist = new List <List <NumPosThckRflt <double> > >(); //for ( int i = 0 ; i < Total.Count ; i++ ) // loop for each files //{ foreach (var item in Total) { //var item = Total[i]; var thmiss = item.Item1.MissingIndex; var rfmiss = item.Item2.MissingIndex; var missing = thmiss.Concat(rfmiss).Distinct().OrderBy(x => x).Reverse(); foreach (var idx in missing) // remove { //item.Item1.RemoveAt( idx ); item.Item1.Datas.RemoveAt(idx); item.Item2.Datas.RemoveAt(idx); } var newthck = item.Item1.Datas.Select(x => x.Value).ToList(); var newrflt = item.Item2.Datas.Select(x => x.Value).ToList(); if (newthck.Count != newrflt.Count) { return(None); } List <DPosThckRflt> output = new List <DPosThckRflt>(); for (int j = 0; j < newrflt.Count; j++) { var ptrw = ToPosThckRflt(newthck[j][0], newthck[j][1], newthck[j][2], newrflt[j], wave); output.Add(ptrw); } totallist.Add(output); } return(Just(totallist.Flatten().ToList())); }
private void GenSchemaTypes(List <ExplorerItem> schema, StringWriter writer, DirectoryInfo root) { const string ForceRefresh = "Overby.LINQPad.FileDriver.Configuration.RuntimeConfiguration.ForceRefresh = true;"; var flatSchema = schema.Flatten().ToArray(); // alias all file/folder namespaces // this avoids conflicts in folder schema types // when referencing reader/record types // in namespaces that are named same as members using (writer.Region("File Namespace Aliases")) foreach (var tag in flatSchema.GetTags <IRefFileSystemInfo>()) { var nsFile = tag.FileSystemInfo.GetNameSpace(root); var alias = tag.FileSystemInfo.FullName.UniqueIdentifier(); writer.WriteLine($"using {alias} = {nsFile};"); } Write(root, schema); foreach (var(item, tag) in flatSchema.WithTag <FolderTag>()) { Write(tag.Folder, item.Children); } void Write(DirectoryInfo folder, IList <ExplorerItem> items) { if (items.Count == 0) { return; } var fileItems = items.WithTag <FileTag>().ToArray(); using var _1 = writer.Region(folder); using var _2 = writer.NameSpace(folder.GetNameSpace(root)); // write file records/readers foreach (var(item, fileTag) in fileItems) { var fileConfig = fileTag.FileConfig; var(WriteRecordMembers, WriteEnumeratorImplementation) = fileTag.CodeGenerator.GetCodeGenerators(fileConfig); using (writer.Region(fileTag.File)) using (writer.NameSpace(fileTag.File.GetNameIdentifier())) { // record class writer.MemberComment("Record type for " + fileTag.File.FullName); using (writer.Brackets("public class " + RecordClassName)) WriteRecordMembers(writer); // reader class writer.MemberComment("Reader for " + fileTag.File.FullName); using (writer.Brackets($"public class {ReaderClassName} : {IEnumerable(RecordClassName)}")) { // file path property writer.MemberComment("Path to " + fileTag.File.FullName); writer.WriteLine(@$ " public string {ReaderFilePathPropertyName} => {fileTag.File.FullName.ToLiteral()};
private void CreateOverloads(List <Ui5Complex> results) { var alltypes = results.Flatten(x => x.Content); foreach (Ui5Complex c in alltypes) { c.CheckOverloads(alltypes); } }
public void Flatten_list_of_list_of_ints() { var listToFlatten = new List <IEnumerable <int> >() { Enumerable.Range(0, 3), Enumerable.Range(3, 3) }; var result = listToFlatten.Flatten(); Equal(6, result.Count()); }
private static IEnumerable <int> GetIdsForNodeType(INodeType nodeType, List <ILink> linksForNode) { var requiredIds = linksForNode .Flatten() .Where(n => n.NodeType.Equals(nodeType)) .Distinct(equalityComparer) .Select(n => n.Id); return(requiredIds); }
public void FlattenReturnsEmptyListWhenSourceIsNull() { //Arrange List <Item> data = null; //Act var result = data.Flatten(item => item.Children); //Assert result.Should().BeEmpty(); }
public void SupportEmptyList() { //arrange var nestedArray = new List <object>(); //act var result = nestedArray.Flatten(); //assert Assert.IsNotNull(result); Assert.AreEqual(0, result.Count); }
public void TryBroadcastEvent(List <string> ev) { if (!ev.IsEmpty()) { Object.Observable.Next(new SenderEv(Id, ev)); if (Object.DebugMode) { Print.Log(string.Format("{0}|SENDS|{1}", Info, ev.Flatten()), "orange"); } } }
private static void Normalize(VectorImageData vectorImageData) { var sequencesUnflattened = new List <IEnumerable <PointsSequence> >(); sequencesUnflattened.Add(vectorImageData.Polygons ?? System.Linq.Enumerable.Empty <PointsSequence>()); sequencesUnflattened.Add(vectorImageData.PolyLines ?? System.Linq.Enumerable.Empty <PointsSequence>()); var sequences = sequencesUnflattened.Flatten(); var points = sequences.SelectMany(sequence => sequence.Points).ToList(); var xs = points.Select(pnt => pnt.X).ToArray(); var ys = points.Select(pnt => pnt.Y).ToArray(); var minX = xs.Min(); var maxX = xs.Max(); var minY = ys.Min(); var maxY = ys.Max(); var tx = (maxX + minX) / 2; var sx = (maxX - minX) / 2; var ty = (maxY + minY) / 2; var sy = (maxY - minY) / 2; var scale = Math.Max(sx, sy); foreach (var seq in sequences) { foreach (var idx in System.Linq.Enumerable.Range(0, seq.Points.Length)) { // get the point var point = seq.Points[idx]; // modify the point point.X = point.X - tx; point.Y = point.Y - ty; if (sx > 0) { point.X = point.X / scale; } if (sy > 0) { point.Y = point.Y / scale; } // put the modified point seq.Points[idx] = point; } } }
public void Flatten_GivenEmptyCollection_ShouldReturnEmptyCollection() { //---------------Set up test pack------------------- var input = new List <List <int> >(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = input.Flatten(); //---------------Test Result ----------------------- Assert.IsNotNull(result); CollectionAssert.IsEmpty(result); }
public void NotThrowExceptionUntilIterateIt3() { IEnumerable <IEnumerable <int> > source = new List <IEnumerable <int> > { new[] { 0, 1, 2 }, new[] { 3, 4, 5, 6 }, new ThrowExceptionEnumerable <int>(7, 8, 9) }; foreach (int e in source.Flatten().Take(10)) { } }
public void TestFlattenNodes() { var ns1 = new List <Node> { Helper.GenerateTestNode(0, ("Raing", "1")) }; var ns2 = new List <Node> { Helper.GenerateTestNode(0, ("Raing", "2")) }; var list = new List <List <Node> >(); list.Add(ns1); list.Add(ns2); Assert.AreEqual(2, list.Flatten().Count); }
public void ThrowExceptionWhenGetEnumeratorExpected3() { IEnumerable <IEnumerable <int> > source = new List <IEnumerable <int> > { new[] { 0, 1, 2 }, new[] { 3, 4, 5, 6 }, new ThrowExceptionEnumerable <int>(7, 8, 9) }; Assert.Throws <Exception>(() => { foreach (int e in source.Flatten()) { } }); }
public IEnumerable <CategoryViewModel> Get(bool includeGroupedTasks, bool includeHiddenTasks, bool showTasks) { var jobList = new List <IJob>(); List <ICategoryModel> categoryTree = categoryService.GetTree().ToList(); IEnumerable <Guid> categoryIds = categoryTree.Flatten(c => c.Children).Select(c => c.Id); if (showTasks) { List <IJob> jobs = jobService.GetByCategoryIds(categoryIds, includeGroupedTasks, includeHiddenTasks); jobList.AddRange(jobs); } IEnumerable <CategoryViewModel> result = FillCategories(categoryTree, jobList); return(result); }
static void Main(string[] args) { var jaggedList = new List <object>() { new List <object>() { "one", "two", new List <object> { "three" } }, "four" }; var flatList = jaggedList.Flatten(); Console.WriteLine(String.Join(",", flatList)); }
public ActionResult SiteMapRead([DataSourceRequest] DataSourceRequest request) { List <SiteMap> siteMaps = _siteService.All(companyId: OperatingUser.CompanyId, isAdmin: OperatingUser.IsAdmin); return(Json(siteMaps.Flatten(x => x.Children ?? new List <SiteMap>()).Select(x => new { x.Id, x.Action, x.Name, x.Controller, x.Description, x.IsActive, x.IsCoreItem, x.IsMenuItem }).ToDataSourceResult(request))); }
static void Main() { List <List <string> > strings = new List <List <string> > { new List <string> { "x", "y", "z" }, new List <string> { "0", "1", "2" } }; foreach (string x in strings.Flatten()) { Console.WriteLine(x); } }
public SharedViewModel(UrlHelper urlHelper) { var LocalizedStrings = DependencyResolver.Current.GetService <ILocalizationManager>(); WebVersion = Assembly.GetExecutingAssembly().FullName .Split(',') .Single(_ => _.Contains("Version=")) .Split('=') .Last(); TreeNode = GetMenuRights(LocalizedStrings); RemoveUnauthorizedItems(TreeNode); foreach (var menuItem in TreeNode.Flatten(_ => _.Childs).Where(_ => _.Action != null)) { menuItem.Url = menuItem.Action(this, urlHelper); } }
public void FlattenDoesNotThrowWhenChildrenIsNull() { //Arrange var data = new List <Item> { new Item("a") { Children = null } }; //Act var result = data.Flatten(item => item.Children).Select(item => item.Code); //Assert //Nothing, should not throw; }
public void Flatten_GivenCollectionWithOneItemInSubCollection_ShouldReturnFlattened() { //---------------Set up test pack------------------- var input = new List <IEnumerable <int> >(); var expected = GetRandomCollection <int>(1, 1); input.Add(expected); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = input.Flatten(); //---------------Test Result ----------------------- Assert.IsNotNull(result); CollectionAssert.IsNotEmpty(result); CollectionAssert.AreEqual(expected, result); }
public void TestFlattenIEnumerable() { object[] arr = { 1, 2, new object[] { 3, new object[] { 4 } }, 5 }; Assert.AreEqual(new object[] { 1, 2, 3, 4, 5 }, arr.Flatten()); var list = new List <object> { "a", new[] { "b", "c" }, 2 }; Assert.AreEqual(new object[] { "a", "b", "c", 2 }, list.Flatten()); int[] simple = { 1, 2, 3 }; Assert.AreEqual(new[] { 1, 2, 3 }, simple.Flatten()); int[] empty = {}; Assert.AreEqual(new int[] {}, empty.Flatten()); }
public void FlattensNestedListOfIntegers() { var list = new List <dynamic>() { 1, 2, 33, new List <dynamic>() { 4, 5, 6 } }; var result = list.Flatten(); var expected = new List <dynamic>() { 1, 2, 33, 4, 5, 6 }; Assert.Equal(expected, result); }
public List <IGrouping <string, XmlElement> > ReadFile() { XDocument document = XDocument.Load($"{AppDomain.CurrentDomain.BaseDirectory}\\labels.xml"); List <XmlElement> elements = new List <XmlElement>(); var parents = document.Root.Elements(); foreach (var currentElement in parents) { var current = new XmlElement { Name = currentElement.Name.LocalName, Value = currentElement.Attribute("id").Value, Language = currentElement.Attribute("id").Value }; GetChildElements(currentElement, current); elements.Add(current); } var data = elements.Flatten(x => x.ChildElement ?? new List <XmlElement>()).Select(z => new XmlElement { ResourceKey = z.ResourceKey, Value = z.Value, Language = z.Language }).Where(x => x.Value != null).GroupBy(x => x.ResourceKey).ToList(); return(data); }
public override IExpression Rewrite(IMethodCall methodCall) { var newSeq = new List<List<Reposition>>(); var thisMethod = methodCall.MethodToCall.ResolvedMethod; var types = thisMethod.Parameters.Select(p => p.Type.ResolvedType).ToList(); var groups = types.Select( (t, i) => new{t,i}).GroupBy(a => a.t, a=>a.i); newSeq.AddRange(from @group in groups select @group.RotateRight(1).Select((i, index) => new Reposition(i, @group.ElementAt(index))).ToList()); var newArgs = new IExpression[types.Count]; foreach (var repos in newSeq.Flatten()) { newArgs[repos.NewPos] = methodCall.Arguments.ElementAt(repos.OldPos); } return new MethodCall(methodCall) { Arguments = newArgs.ToList() }; }
private double ExpectedValue(double[] s1, double[] s2, Node cur, int player, double prob, List<double> allProbs) { if (prob < double.Epsilon) return 0; if (cur.terminal) return cur.payoff * prob; double[] s = player == 1 ? s1 : s2; //Debugging traces through the game tree for (int i = 0; i < cur.children.Length; i++) { if (!cur.children[i].terminal) continue; allProbs.Add(s[cur.children[i].index]); Console.WriteLine("{0} -> {1} Opp: {2} Prob={3} Payoff={4} [{5}]", cur.playerView(), cur.children[i].action, cardToChar(cur.OpponentCard()), allProbs.Product(), cur.children[i].payoff, allProbs.Flatten(", ")); using (TextWriter writer = new StreamWriter(LOG_FILENAME, true)) writer.WriteLine("P1: {0} P2: {1} Board: {2} {3}{4} Prob: {5:N6} Payoff: {6}", cardToChar(cur.hole1), cardToChar(cur.hole2), cardToChar(cur.board), cur.sequence, actionToChar(cur.children[i].action), allProbs.Product(), cur.children[i].payoff, allProbs.Select(d => d.ToString("N9")).Flatten(", ")); allProbs.RemoveAt(allProbs.Count - 1); } Debug.Assert(cur.children.Sum(n => s[n.index]) >= 0.9999, string.Format("Failed {0}: {1}", cur.index, cur.children.Sum(n => s[n.index]))); Debug.Assert(cur.children.Sum(n => s[n.index]) <= 1.0001, string.Format("Failed {0}: {1}", cur.index, cur.children.Sum(n => s[n.index]))); double ev = 0; int nextPlayer = player == 1 ? 2 : 1; foreach (var child in cur.children) { int lookup = child.index; if (s[lookup] > double.Epsilon) { allProbs.Add(s[lookup]); if (child.round == Rounds.Flop && cur.round == Rounds.Preflop) ev += ExpectedValue(s1, s2, child, 1, prob * s[lookup], allProbs); else ev += ExpectedValue(s1, s2, child, nextPlayer, prob * s[lookup], allProbs); allProbs.RemoveAt(allProbs.Count - 1); } } return ev; }