public void Ein_Knoten_mit_Nachkommen() { var node = new Node<int>(1); node.Add(2); node.Add(3); Assert.That(node.PreOrderValues(), Is.EqualTo(new[]{1, 2, 3})); }
private static void Main() { var codePath = Path.Combine(Directory.GetParent(Hgl.Location).Parent.FullName, @"Mgx\Lib"); var root = new Node { new LiveComponent(codePath, "Mgx.Extensions", LoadGame, false) { ExtraFolders = { Path.Combine(codePath, "Mgx.Data"), Path.Combine(codePath, "Mgx.Studio"), Path.Combine(codePath, "Mgx.Playground") }, References = { "Mgx.Core.dll", "FarseerPhysics.dll", "Psd.dll", "SharpSteer.dll", "Spine.dll", "MonoGame.Framework.dll", "MonoGame.Framework.Content.Pipeline.dll", "NAudio.dll", "Newtonsoft.Json.dll", "Mono.Cecil.dll" } } }; _extensions = root.Add(new Node { Name = "Extensions" }); HglRuntime.Start(() => root); }
/// <summary> /// Build the index /// </summary> public virtual void Build(MetricDB db, int bsize, Random rand) { this.DB = db; var n = this.DB.Count; // randomized has very good performance, even compared with more "intelligent" strategies var dseq = new DynamicSequentialOrdered (); dseq.Build (db, rand); this.NODES = new List<Node> (n / bsize + 1); var L = new List<ItemPair> (n); while (dseq.Count > 0) { if (this.NODES.Count % 100 == 0) { Console.WriteLine ("XXX {0}, bucketSize: {1}, remain {2}/{3}, db: {4}, date-time: {5}", this, bsize, dseq.Count, db.Count, Path.GetFileName(db.Name), DateTime.Now); } var refID = dseq.GetAnyItem (); dseq.Remove (refID); L.Clear (); dseq.ComputeDistances (this.DB[refID], L); var near = new Result(bsize); var far = new Result (1); dseq.AppendKExtremes (near, far, L); var node = new Node (refID); this.NODES.Add (node); dseq.Remove (near); foreach (var p in near) { node.Add(p.ObjID, p.Dist); } } }
public static Node Octaves(this Node node, int octaves, Action <OctavesConfiguration> configure = null) { var config = new OctavesConfiguration(); configure?.Invoke(config); var amplitude = 1f; var frequency = 1f; var sum = 0f; Node result = null; for (var i = 0; i < octaves; i++) { var offsetX = (float)(config.Random.NextDouble() * 10); var offsetY = (float)(config.Random.NextDouble() * 10); var octave = node .Translate(offsetX, offsetY) .Scale(1 / frequency) .Multiply(amplitude); result = result?.Add(octave) ?? octave; sum += amplitude; amplitude *= config.Persistence; frequency *= config.Lacunarity; } return(result.Divide(sum)); }
public void Ein_Knoten_deren_Nachkommen_auch_Nachkommen_haben() { var node1 = new Node<int>(1); var node2 = node1.Add(2); var node3 = node2.Add(3); var node4 = node2.Add(4); Assert.That(node1.PreOrderValues(), Is.EqualTo(new[] { 1, 2, 3, 4 })); }
/* * adds a single value to destination node */ private static void AddSingleValue(Node ip, Node dp, Node destinationNode) { object sourceObject = Expressions.GetExpressionValue<object>(ip["value"].Get<string>(), dp, ip, false); Node sourceObjectAsNode = sourceObject as Node; if (sourceObjectAsNode != null) destinationNode.Add(sourceObjectAsNode.Clone()); else { string nodeName = sourceObject.ToString(); object nodeValue = null; if (ip["value"].ContainsValue("value")) { nodeValue = Expressions.GetExpressionValue<object>(ip["value"]["value"].Get<string>(), dp, ip, false); if (ip["value"]["value"].Count > 0) nodeValue = Expressions.FormatString(dp, ip, ip["value"]["value"], nodeValue.ToString()); } destinationNode.Add(new Node(nodeName, nodeValue)); } }
private void DataBindGrid() { Node tmp = new Node(); foreach (Node idx in FilteredItems) { if (idx["Name"].Get<string>().ToLower().Contains(filter.Text.ToLower())) tmp.Add(idx); } rep.DataSource = tmp; rep.DataBind(); }
private void CreateActors(Node scene) { var timer = Create<Timeline>(); timer.Repeat(() => { var p = new Vector2(Rand.Around(area.Width / 2, area.Width / 5), Rand.Around(area.Height / 2, area.Height / 5)); scene.Add(new SteeringActor(p)); }, .1f, 100) .Then(timer.Dispose); }
private void CreateMenuNode(Node<Menu> root, List<Menu> menus, List<Menu> allMenus) { if (menus == null || menus.Count() == 0) return; foreach (var menu in menus) { var node = root.Add(menu); var subMenus = allMenus.Where(m => m.ParentId == menu.Id).ToList(); CreateMenuNode(node, subMenus, allMenus); } }
public void ShouldAddNewValue() { // arrange var target = new Node<string>(); var expected = "Test"; // act target.Add( expected ); // assert Assert.Equal( 1, target.Count ); Assert.Equal( expected, target[0].Value ); }
public void DepthPropertyShouldReturnCorrectLevel() { var target = new Node<string>(); Assert.Equal( 0, target.Depth ); target.Add( "1" ); Assert.Equal( 1, target[0].Depth ); target[0].Add( "2" ); Assert.Equal( 2, target[0][0].Depth ); target[0][0].Add( "3" ); Assert.Equal( 3, target[0][0][0].Depth ); }
public void ParentPropertyShouldReturnCorrectObject() { var target = new Node<string>(); Assert.Null( target.Parent ); target.Add( "1" ); Assert.Equal( target, target[0].Parent ); target[0].Add( "2" ); Assert.Equal( target[0], target[0][0].Parent ); target[0][0].Add( "3" ); Assert.Equal( target[0][0], target[0][0][0].Parent ); }
public string[] anagrams(string[] phrases) { Node root = new Node(); root.Children = new List<Node>(); List<string> results = new List<string>(); foreach (string phrase in phrases) { if (root.Add(Normalize(phrase))) results.Add(phrase); } return results.ToArray(); }
public Node <KeyValuePair <int, int> > GetEqualDistancePairs(Node <int> list1) { Node <KeyValuePair <int, int> > list2 = new Node <KeyValuePair <int, int> >(); if (list1.Length() % 2 == 0) { while (list1 != null) { list2.Add(new KeyValuePair <int, int>(list1.GetValue(), LastAndRemove(list1))); list1 = list1.GetNext(); } } else { while (list1.GetNext() != null) { list2.Add(new KeyValuePair <int, int>(list1.GetValue(), LastAndRemove(list1))); list1 = list1.GetNext(); } list2.Add(new KeyValuePair <int, int>(list1.GetValue(), list1.GetValue())); } return(list2.GetNext()); }
public void RemoveChildreRemoveChildrens() { Node parent = new Node("Parent"); Node child1 = new Node("Child1"); Node child2 = new Node("Child2"); Node subchild1 = new Node("Subchild1"); child1.Add(subchild1); parent.Add(child1); parent.Add(child2); parent.RemoveChildren(); Assert.IsEmpty(parent.Children); Assert.IsEmpty(child1.Children); }
/// <summary> /// Связанный список, с возможностью обращения по индексу и сортировки /// </summary> /// <param name="args"></param> static void Main(string[] args) { Node<Hendler> nodePro = new Node<Hendler>("apple"); nodePro.Add(new Node<Hendler>("wind", new Hendler(" cold"), new Node<Hendler>("12fg"))); nodePro.Add(new Node<Hendler>("snake")); nodePro.Add(new Node<Hendler>("griraffe")); nodePro.Sort(); for (int i = 0; i < nodePro.Count; i++) { Console.WriteLine("nodePro[{0}] = {1}", i, nodePro[i].data); } nodePro[2].data = "HELLO WORLD"; Console.WriteLine("------------------"); for (int i = 0; i < nodePro.Count; i++) { Console.WriteLine("nodePro[{0}] = {1}", i, nodePro[i].data); } Console.ReadLine(); }
/* * Returns a MimePart as inline content to caller. */ void ProcessMimePartInline(MimePart part, Node entityNode) { var txtPart = part as TextPart; if (txtPart != null) { // Part is text part. entityNode.Add("content", txtPart.Text); } else { // Creating a stream to decode our entity to. using (MemoryStream stream = new MemoryStream()) { // Decoding content to memory. part.ContentObject.DecodeTo(stream); // Resetting position and setting up a buffer object to hold content. stream.Position = 0; // Putting content into return node for MimeEntity. entityNode.Add("content", stream.ToArray()); } } }
public void SingleWhere() { // Creating node hierarchy. var node = new Node(); node.Add(new Node("table", "foo")); var where = new Node("where"); var and = new Node("and"); and.Add(new Node("field1", "value1")); where.Add(and); node.Add(where); var builder = new SqlDeleteBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. var result = builder.Build(); var sql = result.Get <string>(); Assert.Equal("delete from 'foo' where 'field1' = @0", sql); var arg1 = result.Children.First(); Assert.Equal("@0", arg1.Name); Assert.Equal("value1", arg1.Get <string>()); }
void Read(string file) { StringBuilder builder = new StringBuilder(); Stack <Node> stack = new Stack <Node>(); for (int i = 0; i < file.Length; i++) { if (file[i] == '{') { var node = new Node(builder.ToString().Trim()); stack.Push(node); builder.Clear(); } else if (file[i] == '}') { BuildValue(builder, stack); var n = stack.Pop(); if (stack.Count > 0) { stack.Peek().Add(n); } else { root.Add(n); } } else { builder.Append(file[i]); if (file[i] == '\n') { BuildValue(builder, stack); } } } }
public void WithOperator() { // Creating node hierarchy. var node = new Node(); var table1 = new Node("table", "table1"); var join1 = new Node("join", "table2"); join1.Add(new Node("type", "inner")); var on1 = new Node("on"); var and1 = new Node("and"); and1.Add(new Node("fk1.neq", "pk1")); on1.Add(and1); join1.Add(on1); table1.Add(join1); node.Add(table1); var builder = new SqlReadBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. var result = builder.Build(); var sql = result.Get <string>(); Assert.Equal("select * from 'table1' inner join 'table2' on 'fk1' != 'pk1' limit 25", sql); }
private static void BuildTree(Node node, IReadOnlyList <Node> folders, IReadOnlyList <Node> files, ParArchiveReaderParameters parameters) { int firstFolderIndex = node.Tags["FirstFolderIndex"]; int folderCount = node.Tags["FolderCount"]; for (int i = firstFolderIndex; i < firstFolderIndex + folderCount; i++) { node.Add(folders[i]); BuildTree(folders[i], folders, files, parameters); } int firstFileIndex = node.Tags["FirstFileIndex"]; int fileCount = node.Tags["FileCount"]; for (int i = firstFileIndex; i < firstFileIndex + fileCount; i++) { if (parameters.Recursive && files[i].Name.EndsWith(".par", StringComparison.InvariantCultureIgnoreCase)) { files[i].TransformWith <ParArchiveReader, ParArchiveReaderParameters>(parameters); } node.Add(files[i]); } }
/// <summary> /// Perform the action /// </summary> public void Execute() { // transfer Old's children to New for (int i = Old.Children.Count - 1; i >= 0; --i) { var child = Old.Children[i]; Old.Remove(child); New.Add(child, 0); } Old.Comment = true; var parent = Old.Parent; int index = parent.IndexOf(Old); parent.Add(New, index + 1); }
public void CreateSimpleMessageRaw() { var signaler = Common.GetSignaler(); var node = new Node("", "text/plain"); var content = new Node("content", "foo bar"); node.Add(content); signaler.Signal(".mime.create", node); using (var entity = node.Value as MimeEntity) { Assert.Equal(@"Content-Type: text/plain foo bar", entity.ToString()); } }
public void When_BuildVariable_Expect_Reference() { var builder = new RealBuilder(); var variable = new GetSetVariable <double>("a", Units.Volt); builder.VariableFound += (sender, args) => { if (!args.Created && args.Node.Name == "a") { args.Result = variable.Value; } }; variable.Value = 2.0; Assert.AreEqual(5.0, builder.Build(Node.Add(Node.Variable("a"), 3.0)), 1e-20); }
public void NamespacedColumns() { // Creating node hierarchy. var node = new Node(); var table1 = new Node("table", "dbo.table1"); var join1 = new Node("join", "dbo.table2"); join1.Add(new Node("type", "inner")); var on1 = new Node("on"); var and1 = new Node("and"); and1.Add(new Node("dbo.table1.fk1", "dbo.table2.pk1")); on1.Add(and1); join1.Add(on1); table1.Add(join1); node.Add(table1); var builder = new SqlReadBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. var result = builder.Build(); var sql = result.Get <string>(); Assert.Equal("select * from 'dbo'.'table1' inner join 'dbo'.'table2' on 'dbo'.'table1'.'fk1' = 'dbo'.'table2'.'pk1' limit 25", sql); }
/* * Processes the MIME headers of the given MimeEntity. */ void ProcessHeaders(MimeEntity entity, Node args) { // Looping through all headers. foreach (var idxHeader in entity.Headers) { // No need to handle Content-Type, since it's already handled as root entity name/value. if (idxHeader.Id == HeaderId.ContentType) { continue; } // Adding header as child node of main MimeEntity node. args.Add(idxHeader.Field, idxHeader.Value); } }
/// <summary> /// Builds the node. /// </summary> /// <returns></returns> public XElement BuildNode() { if (Forms.Count != 0) { XElement nodeForms = Node.Element(Ns.Office + "forms"); if (nodeForms == null) { nodeForms = new XElement(Ns.Office + "forms"); } foreach (ODFForm f in Forms) { nodeForms.Add(f.Node); } Node.Add(nodeForms); } foreach (Column column in ColumnCollection) { Node.Add(column.Node); } if (RowHeader != null) { Node.Add(RowHeader.Node); } foreach (Row row in Rows) { //check for nested tables foreach (Cell cell in row.Cells) { foreach (IContent iContent in cell.Content) { if (iContent is Table) { Table table = iContent as Table; table.BuildNode(); } } } //now, append the row node Node.Add(row.Node); } return(Node); }
private static Node GenerateTreeViewDataForType(JavaFileInfo fileInfo, Type type) { Type.TypeData data = type.GetData(); Type.DataEnum dataEnum = data as Type.DataEnum; Node node = new Node(type.ToString()); if (fileInfo != null) { Node packageNode = new Node("[Package]"); packageNode.Add(fileInfo.Package); node.Add(packageNode); Node importNode = new Node("[Imports]"); importNode.AddRangeAsStrings(fileInfo.Imports); node.Add(importNode); } if (data.Fields.Count > 0) { Node fieldNode = new Node("[Fields]"); fieldNode.AddRangeAsStrings(data.Fields); node.Add(fieldNode); } if (data.Methods.Count > 0) { Node methodNode = new Node("[Methods]"); methodNode.AddRangeAsStrings(data.Methods); node.Add(methodNode); } if (type.NestedTypes.Count > 0) { Node nestedNode = new Node("[Nested Types]"); nestedNode.AddRange(type.NestedTypes.Select(nestedType => GenerateTreeViewDataForType(null, nestedType))); node.Add(nestedNode); } if (dataEnum != null) { Node enumNode = new Node("[Enum Values]"); enumNode.AddRange(dataEnum.EnumValues); node.Add(enumNode); } return(node); }
/* * puts in an email address into the given node */ private static void GetAddress(InternetAddress adr, string field, Node node) { if (adr == null || !(adr is MailboxAddress)) { return; } MailboxAddress mailboxAdr = adr as MailboxAddress; Node nNode = new Node(field, mailboxAdr.Address); if (!string.IsNullOrEmpty(mailboxAdr.Name)) { nNode.Add("display-name", mailboxAdr.Name); } node.Add(nNode); }
/* * extracts values if an [extract] node is given */ private static void ExtractValue(Node ip, Node result) { Node toAdd = new Node("value"); foreach (Node idxExtract in ip["extract"]) { string name = idxExtract.Name; object value = Expressions.GetExpressionValue <object>(idxExtract.Get <string>(), result["value"], result["value"], false); if (value == null && idxExtract.ContainsValue("default")) { value = idxExtract["default"].Value; } toAdd.Add(name, value); } ip.Add(toAdd); }
public void WrongBooleanGroup_Throws() { // Creating node hierarchy. var node = new Node(); node.Add(new Node("table", "foo")); var where = new Node("where"); var and = new Node("xor"); and.Add(new Node("field1", "value1")); where.Add(and); node.Add(where); var builder = new SqlDeleteBuilder(node, "'"); Assert.Throws <ArgumentException>(() => builder.Build()); }
public void WithContentEncoding() { var signaler = Common.GetSignaler(); var node = new Node("", "text/plain"); var content = new Node("content", "foo bar"); node.Add(content); content.Add(new Node("Content-Encoding", "default")); signaler.Signal(".mime.create", node); using (var entity = node.Value as MimeEntity) { Assert.Equal(@"Content-Type: text/plain foo bar", entity.ToString()); } }
/// <summary> /// Init the standard style source template styles. /// </summary> public void InitStandardTableOfContentStyle() { for (int i = 1; i <= 10; i++) { TableOfContentsIndexTemplate tableOfContentsIndexTemplate = new TableOfContentsIndexTemplate( TableOfContents, i, "Contents_20_" + i); tableOfContentsIndexTemplate.InitStandardTemplate(); Node.Add(tableOfContentsIndexTemplate.Node); TableOfContentsIndexTemplateCollection.Add( tableOfContentsIndexTemplate); } }
/* * Helper for above. */ static void HandleObject(Node node, JObject obj) { // Special treatment for "__value" property. var val = obj.Children().FirstOrDefault(ix => ix is JProperty && (ix as JProperty).Name == "__value") as JProperty; if (val != null) { // Handling "__value" by setting the root node for object to "__value" property's value. node.Value = (val.Value as JValue).Value; obj.Remove("__value"); } foreach (var idx in obj) { HandleToken(node.Add(idx.Key).LastChild, idx.Value); } }
public void MultipleValuesThrows_01() { // Creating node hierarchy. var node = new Node(); node.Add(new Node("table", "foo")); var values = new Node("values"); values.Add(new Node("field1", "howdy")); node.Add(values); node.Add(new Node("values")); var builder = new SqlCreateBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. Assert.Throws <ArgumentException>(() => builder.Build()); }
public void CreateFromFilename() { var signaler = Common.GetSignaler(); var node = new Node("", "text/plain"); var content = new Node("filename", "/test.txt"); content.Add(new Node("Content-Encoding", "default")); node.Add(content); signaler.Signal(".mime.create", node); using (var entity = node.Value as MimeEntity) { Assert.Contains("Content-Disposition: attachment; filename=test.txt", entity.ToString()); Assert.Contains("Content-Type: text/plain", entity.ToString()); Assert.Contains("Some example test file used as attachment", entity.ToString()); } }
private Node ReadTranslation(AssetInfo assetInfo, string translationPath) { Node translation = NodeFactory.CreateContainer(string.Concat(assetInfo.Id, "_Translation")); foreach (string outputFile in assetInfo.OutputNames) { string path = Path.Combine(translationPath, outputFile); Node file = NodeFactory.FromFile(path, Yarhl.IO.FileOpenMode.Read); translation.Add(file); } translation.Transform(assetInfo.TranslationMergers, Parameters); return(translation); }
public void Transfer(Node newRoot) { foreach (var item in Items) { newRoot.Add(item); } foreach (var child in Children) { child.Transfer(newRoot); } Items.Clear(); Children.Clear(); nodePool.Return(this); }
public void NestedWhereLevels_02() { // Creating node hierarchy. var node = new Node(); node.Add(new Node("table", "foo")); var where = new Node("where"); var or1 = new Node("or"); or1.Add(new Node("foo1", 5)); or1.Add(new Node("foo2", "howdy")); var and2 = new Node("and"); and2.Add(new Node("foo3", "jalla")); and2.Add(new Node("foo4", "balla")); or1.Add(and2); where.Add(or1); node.Add(where); var builder = new SqlReadBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. var result = builder.Build(); var sql = result.Get <string>(); Assert.Equal("select * from 'foo' where 'foo1' = @0 or 'foo2' = @1 or ('foo3' = @2 and 'foo4' = @3) limit 25", sql); var arg1 = result.Children.First(); Assert.Equal("@0", arg1.Name); Assert.Equal(5, arg1.Value); var arg2 = result.Children.Skip(1).First(); Assert.Equal("@1", arg2.Name); Assert.Equal("howdy", arg2.Value); var arg3 = result.Children.Skip(2).First(); Assert.Equal("@2", arg3.Name); Assert.Equal("jalla", arg3.Value); var arg4 = result.Children.Skip(3).First(); Assert.Equal("@3", arg4.Name); Assert.Equal("balla", arg4.Value); }
public void CreateMultipartMessage() { var signaler = Common.GetSignaler(); // Creating a Multipart var node = new Node(""); var rootEntity = new Node("entity", "multipart/mixed"); node.Add(rootEntity); var message1 = new Node("entity", "text/plain"); rootEntity.Add(message1); var content1 = new Node("content", "some text"); message1.Add(content1); var message2 = new Node("entity", "text/plain"); rootEntity.Add(message2); var content2 = new Node("content", "some other text"); message2.Add(content2); signaler.Signal(".mime.create", node); var entity = node.Value as MimeEntity; try { // Running through a couple of simple asserts. Assert.Equal(typeof(Multipart), entity.GetType()); var multipart = entity as Multipart; Assert.Equal(2, multipart.Count); Assert.Equal(typeof(MimePart), multipart.First().GetType()); Assert.Equal(typeof(MimePart), multipart.Skip(1).First().GetType()); var text1 = multipart.First() as MimePart; Assert.Equal(@"Content-Type: text/plain some text", text1.ToString()); var text2 = multipart.Skip(1).First() as MimePart; Assert.Equal(@"Content-Type: text/plain some other text", text2.ToString()); } finally { Common.DisposeEntity(entity); } }
static void Main(String[] args) { int n = int.Parse(Console.ReadLine()); Node root = new Node(""); for (int i = 0; i < n; ++i) { string s = Console.ReadLine(); if (!root.Add(s)) { Console.WriteLine("BAD SET"); Console.WriteLine(s); return; } } Console.WriteLine("GOOD SET"); }
private T GetOrCreateNode <T>(Node parent, Func <T> func, Node newParent) where T : Node { T newNode; var retrievedChild = parent.GetChildren <T>(); if (retrievedChild == null || !retrievedChild.Any()) { newNode = func.Invoke(); //Do not add to parent but to "this" newParent.Add(newNode); } else { newNode = retrievedChild.First(); } return(newNode); }
public void NoValueNode_Throws() { // Creating node hierarchy. var node = new Node(); node.Add(new Node("table", "foo")); var where = new Node("where"); var and = new Node("and"); and.Add(new Node("field2", "value2")); where.Add(and); node.Add(where); var builder = new SqlUpdateBuilder(node, "'"); // Extracting SQL + params, and asserting correctness. Assert.Throws <ArgumentException>(() => builder.Build()); }
public static object From(UIControl control, SpriteFont font, UIViewStyle style) { var button = control as Button; if (button != null) { return new TextButtonView(button, font) { Style = style }; } var cb = control as ToggleButton; if (cb != null) { return new CheckBoxView(cb) { Style = style }; } var slider = control as Slider; if (slider != null) { return new GaugeView(slider); } var label = control as Label; if (label != null) { return new LabelView(label) { Style = style }; } var container = control as UIContainer; if (container != null) { var node = new Node { new BackgroundView(container) { Style = style } }; foreach (var child in container) { node.Add(From(child, font, style)); } return node; } return null; }
public Tree() { _ui = Add(new StackPanel(0) { Orientation = Orientation.Vertical, Anchor = new Vector2(0, .2f), Padding = new Margin(5, 5), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, }); _view = Add(new Node()); _view.Add(new BackgroundView(_ui)); var components = Hgl.Components; foreach (var component in components) { LoadNode(component); } }
internal static void Initialize() { lock (_locker) { lock (_transactionalLocker) { if (_dbPath != null) return; // multiple initializations might occur _dbPath = ConfigurationManager.AppSettings["magix.core.database-path"]; _database = new Node(); foreach (string idxDirectory in GetDirectories(_dbPath)) { foreach (string idxFile in GetFiles(idxDirectory)) { _database.Add(LoadFile(idxFile)); } } } } }
public void Für_einen_hinzugefügten_Wert_wird_ein_Knoten_angelegt() { var node = new Node<int>(1); var child = node.Add(2); Assert.That(node.Children, Is.EquivalentTo(new[] {child})); }
public void Der_hinzugefügte_Wert_wird_in_die_ChildValues_aufgenommen() { var node = new Node<char>('x'); node.Add('y'); Assert.That(node.ChildValues, Is.EquivalentTo(new[]{'y'})); }
/* * puts in an email address into the given node */ private static void GetAddress(InternetAddress adr, string field, Node node) { if (adr == null || !(adr is MailboxAddress)) return; MailboxAddress mailboxAdr = adr as MailboxAddress; Node nNode = new Node(field, mailboxAdr.Address); if (!string.IsNullOrEmpty(mailboxAdr.Name)) nNode.Add("display-name", mailboxAdr.Name); node.Add(nNode); }
Node Combination() { var node = new Node( Operation.Combination, false ); node.Add( Sequence() ); while (cs.AcceptSpace()) { node.Add( Sequence() ); } return node; }
// Add a node public void Add(String text, int number) { Node node = new Node(); node.TextData = text; node.NumberData = number; node.Add(nodeHead); }
public static void Main() { Task1Tree<int> nodes = new Task1Tree<int>(); StringReader reader = new StringReader(GlobalConstants.Input); int nodePairsCount = 0; string firstLine = reader.ReadLine(); if (!int.TryParse(firstLine, out nodePairsCount)) { throw new ArgumentException("Input is not valid"); } for (int i = 0; i < nodePairsCount - 1; i++) { string[] line = reader.ReadLine().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); int parentValue = int.Parse(line[0]); int childValue = int.Parse(line[1]); if (!nodes.Contains(parentValue) && !nodes.Contains(childValue)) { var theNewNode = new Node<int>(parentValue); theNewNode.Add(new Node<int>(childValue)); nodes.Add(theNewNode); } else if (!nodes.Contains(parentValue) && nodes.Contains(childValue)) { var theNode = new Node<int>(parentValue); var theNodeToAdd = nodes.Find(childValue); nodes.RemoveTreeNode(theNodeToAdd); theNode.Add(theNodeToAdd); nodes.Add(theNode); } else if (nodes.Contains(parentValue) && !nodes.Contains(childValue)) { var theNode = nodes.Find(parentValue); theNode.Add(new Node<int>(childValue)); } else { var theParentNode = nodes.Find(parentValue); var theChildNode = nodes.Find(childValue); nodes.RemoveTreeNode(theChildNode); theParentNode.Add(theChildNode); } } Console.WriteLine(nodes.ToString()); Console.WriteLine("Root: " + nodes.Childs[0].Value); var leafs = nodes.GetAllLeafs().Select(x => x.Value).ToList(); Console.WriteLine("Leafs: {0}", string.Join(", ", leafs)); Console.WriteLine("Max level: {0}*", nodes.TheLongestPathInTheTree()); //// What means 'all middle nodes' in the current context? - Node that has parent and at least one child. var middleNodes = nodes.GetAllMiddleLeafs().Select(x => x.Value).ToList(); Console.WriteLine("Middle nodes: {0}", string.Join(", ", middleNodes)); Console.ForegroundColor = ConsoleColor.DarkRed; Console.BackgroundColor = ConsoleColor.Gray; Console.WriteLine("* Consider that start level begins from 0."); Console.ResetColor(); }
private Node FilterApplications() { OldMaximized = ""; Node retVal = new Node(); if (filter.Text.ToLowerInvariant() == Language.Instance["Newest", null, "Newest"].ToLowerInvariant()) { List<Node> nodes = new List<Node>(Modules); nodes.Sort( delegate(Node left, Node right) { return left["Date"].Get<DateTime>().CompareTo(right["Date"].Get<DateTime>()); }); int idxNo = 0; foreach (Node idxNode in Modules) { if (++idxNo >= 10) break; retVal.Add(idxNode); } } else if (filter.Text.ToLowerInvariant() == Language.Instance["Updates", null, "Updates"].ToLowerInvariant()) { List<Node> nodes = new List<Node>(Modules); nodes.RemoveAll( delegate(Node idx) { return !(idx["Installed"].Get<bool>() && idx["HasUpdate"].Get<bool>()); }); retVal.AddRange(nodes); } else if (filter.Text.ToLowerInvariant() == Language.Instance["Popular", null, "Popular"].ToLowerInvariant()) { int idxNo = 0; foreach (Node idxNode in Modules) { if (++idxNo >= 10) break; retVal.Add(idxNode); } } else { foreach (Node idxNode in Modules) { bool hasValue = false; if (string.IsNullOrEmpty(filter.Text)) hasValue = true; else { if ( idxNode["CandyName"].Get<string>().ToLowerInvariant().Contains( filter.Text.ToLowerInvariant())) hasValue = true; if ( idxNode["Description"].Get<string>().ToLowerInvariant().Contains( filter.Text.ToLowerInvariant())) hasValue = true; } if (hasValue) retVal.Add(idxNode); } } return retVal; }
/// <summary> /// Converts a string value to a string, int or boolean type. /// </summary> /// <param name="value">The string that is to be parsed.</param> /// <returns>An object that is the parsed value of the string.</returns> protected Node ParseValue(string key, string value) { if(value.ToUpper() == "TRUE") { return new Node(key, true); } else if(value.ToUpper() == "FALSE") { return new Node(key, false); } else if(value == "") { return new Node(key, null); } else if(Regex.Match(value, @"\A([""'])(.*)\1\Z").Success) { return new Node(key, value.Substring(1, value.Length - 2)); } else if(Regex.Match(value, @"\A\[?(.+)(,(.+))+\]?\Z").Success) { // Value is an array of items if(value.StartsWith("[") && value.EndsWith("]")) { value = value.Substring(1, value.Length - 2); } string[] vals = value.SplitCSV(); Node coll = new Node(key, null); foreach(string val in vals) { coll.Add(new Node(null, val)); } return coll; } else if(Regex.Match(value, @"\{(.+:.+)(?:,(.+:.+))*\}").Success) { // Value is an dictionary of items value = value.Substring(1, value.Length - 2); string[] vals = value.SplitCSV(); Node coll = new Node(key, null); foreach(string val in vals) { string subkey = val.Substring(0, val.IndexOf(':')); coll.Add(ParseValue(subkey, val.Substring(val.IndexOf(':') + 1))); } return coll; } else { return new Node(key, value); } }
/// <summary> /// Processes the current line into an existing Dictionary. /// </summary> /// <param name="context">Node containing the Dictionary to which the /// element should be added.</param> /// <param name="line">The line containing the key: value pair.</param> protected Node ProcessDictionaryElement(Node context, string line) { string key = line.Substring(0, line.IndexOf(":")).Trim(); line = line.Substring(line.IndexOf(":") + 1).Trim(); var node = ParseValue(key, line); return context.Add(node); }
private Node GridDistribution(Rectangle area, Color[] colors, BodyRenderer renderer) { var hexagons = new Node(); var r = 8; var x = r * (float)Math.Sqrt(3); var y = r * 2f; var n = area.Width / x - 1; var m = area.Height / y - 1; var o = new Vector2(r + 3, r); var d = r; for (var i = 0; i < n; i++) { o += new Vector2(0, d); d = -d; for (var j = 0; j < m; j++) { if (Rand.Float() < .6f) continue; var pos = o + new Vector2(i * x, j * y); var color = colors.RandomItem(); hexagons.Add(BuildHexagon(renderer, color, pos, r, r)); } } return hexagons; }
private Node TreeDistribution(Rectangle area, Color[] colors, BodyRenderer renderer) { var hexagons = new Node(); var radius = 2; var spacing = 4; var mapWidth = area.Width / spacing - 3; var mapHeight = area.Height / spacing - 1; var map = new HexagonMap<bool>(mapWidth, mapHeight); var first = new Hexagon(Rand.Floor(mapWidth), Rand.Floor(mapHeight)); map[first] = true; hexagons.Add(BuildHexagon(renderer, colors, first, radius, spacing)); var current = first; var n = 5 + Rand.Floor(10); for (int i = 0; i < n; i++) { var freeNeighbors = current.GetNeighborsWhere(hexagon => map.IsInBound(hexagon) && !map[hexagon]).ToArray(); if (!freeNeighbors.Any()) break; current = freeNeighbors.RandomItem(); map[current] = true; hexagons.Add(BuildHexagon(renderer, colors, current, radius, spacing)); } return hexagons; }
/// <summary> /// Processes the current line into an existing list. /// </summary> /// <param name="context">Node containing the list to which the /// element should be added.</param> /// <param name="line">The line containing the list element (complete /// with leading '-').</param> protected Node ProcessListElement(Node context, string line) { var value = ParseValue(null, line.Substring(1).Trim()); return context.Add(value); }
Node Sequence() { var node = new Node( Operation.Sequence, cs.Accept("+") ); node.Add( Exclusion() ); while (cs.Accept("..")) { node.Add( Exclusion() ); } return node; }
Node Exclusion () { var node = new Node( Operation.Exclusion, false ); node.Add( Factor() ); while (cs.Accept("|")) { node.Add( Factor() ); } return node; }