Binding to a Binary Tree in Knockoutjs - binary-tree

I'm looking for some advice on binding knockoutjs to a binary tree with dependentObservables.
I'm working on a web project that involves a binary tree in javascript. The binary tree implementation has been completed, and I'm running into a problem using it with Knockoutjs.
The binary tree doesn't really have any properties, only a few methods (addNode, inorderTraversal, getLength, getDepth, toJSON, etc), so I have no clue how to set it up as observable. I'd really just love to have a few dependentObservables that get some information from the binary tree.
As a simple example, I'd like to at least set up a dependentObservable for the length of the tree. It just never seems to get fired...
viewModel.TreeLength = ko.dependentObservable(function(){
return this.bTree().getLength();}, viewModel);
The following adds the node to the tree, but the TreeLength never fires.
viewModel.bTree().addNode(new Node('some data'));

RP Niemeyer pointed me to the solution with valueHasMutated. The first round was just adding a call to viewModel.bTree.valueHasMutated() every time we worked with the tree.
Once this was proven to work, the code was refactored to pass a callback method to the tree, so that any time the tree changed, the callback would be invoked. We ran into some problems with closures, but finally got to the following:
function getCallBack(o)
{
var obj = o;
var func = function()
{
obj.bTree.valueHasMutated();
}
return func;
}
this.bTreeChanged = getCallBack(this);
model.bTree = new BinaryTree(model.treeData, this.bTreeChanged);

Related

How can I sort child nodes by property value in Scala.js?

The problem is to sort all child divs of a root node according to their top CSS property.
Here is my code:
val elements = global.document.getElementById("root").childNodes.asInstanceOf[dom.NodeList]
val clones = (for (i <- (0 to (elements.length - 1)) if (elements(i).isInstanceOf[dom.raw.HTMLDivElement])) yield {
val clone = elements(i).cloneNode(true)
val style = clone.attributes.getNamedItem("style").value
val parts = style.split("top: ")
val parts2 = parts(1).split("px")
val px = parts2(0).toDouble
Tuple2[dom.Node, Double](clone, px)
}).toList
val sorted = clones.sortWith((a, b) => a._2 > b._2)
global.document.getElementById("root").innerHTML = ""
for (e <- sorted) {
global.document.getElementById("root").appendChild(e._1)
}
I'm new to Scala.js and it took quite an effort to come up with this solution. It compiles and seems to work, however I'm not sure how legitimate it is.
For example I can only get the top property of the node in a very complicated way. Also I suspect that for deleting all child nodes global.document.getElementById("root").innerHTML = "" is a backdoor way. I'm not sure if this sorting can be done in place without creating clones. I welcome any suggestions for improvement and I hope that some beginner out there may find even this code useful.
Various suggestions, some pertaining to Scala and some to the underlying browser environment:
First, jQuery (actual JavaScript library) (Scala.js facade) is your friend. Trying to do anything with the raw DOM is a pain in the ass, and I don't recommend it for anything but the simplest toy applications. (This has nothing to do with Scala.js, mind -- that's just the reality of working in the browser, and is all true of JavaScript as well.)
Using jQuery, getting the elements is just:
val elements = $("root").children
Second, essentially nobody loops using indexes in Scala like that -- it's legal, but extremely rare. Instead, you get each element directly in the for. And you can stick the value assignments right into the for itself, keeping the yield clause clean.
jQuery lets you get at CSS properties directly. (Although I think you still have to parse out the "px".) Again, everything is much harder if you try to use the raw DOM functions.
And it's very rare to spell out Tuple2 -- you just use parens for a tuple. Putting it all together, it would look something like this:
for {
element <- elements
if (element.isInstanceOf[dom.raw.HTMLDivElement])
clone = element.clone()
top = clone.css("top")
px = top.dropRight(2).toDouble
}
yield (clone, px)
Mind, I haven't actually tried out the above code -- there are probably some bugs -- but that's more like what idiomatic Scala.js + jQuery code would look like, and is worth considering as a starting point.

signature and functionality of selection callback of treeview in gtkmm

I have a treeview and want to get notified if the selection changes. What is the signature for the callback?
I found a code snippet like:
Gtk::TreeView *treeview = Gtk::manage(new Gtk::TreeView);
Glib::RefPtr< Gtk::TreeSelection > sel = treeview->get_selection();
sel->set_mode( Gtk::SELECTION_MULTIPLE );
sel->set_select_function(sigc::ptr_fun(&SelFun));
But I can't find anything about the SelFun!
How is the signature
How to find out which rows and columns are selected inside this function?
How to access data from the model with that object
Yes, I have actually no idea how the TreeView/Model/Path/Selection interacts. Every link to an example is highly welcome!
You seem to want multiple selection. I had the same problem too. Once you have enabled mutliple selection, getting the selected rows is a little more difficult. The method of acquiring them varies slightly.
I'll provide the most general method. First, you need to overload the signal_changed() signal after you have enabled multiple selection. Then, assign the TreeView's TreeSelection to a RefPtr for easy access.
Glib::RefPtr<Gtk::TreeSelection> TreeView_TreeSelection;
TreeView_TreeSelection = your_TreeView.get_selection();
Next, connect the TreeSelection to the signal_changed() signal.
TreeView_TreeSelection -> signal_changed().connect(sigc::mem_fun(your_TreeView,
&your_Class::on_selection_changed));
Now, make sure to make a void function header in "your_Class" named on_selction_changed() or whatever you want. Just make sure to change the name in the connection above to whatever your class' name is.
The final step is to make the function. Here is a simple example of getting a vector of all of the TreePaths of the rows selected, then converting those TreePaths into a vector of TreeModel::Row pointers.
void your_Class::on_selection_changed()
{
if((TreeView_TreeSelection -> count_selected_rows()) == 0)
{
return;
}
vector<Gtk::TreeModel::Path> selected_rows = TreeView_TreeSelection -> get_selected_rows();
vector<Gtk::TreeModel::Row*> selected_TreeRows;
vector<Gtk::TreeModel::Path>::iterator TreePath_iterator = selected_rows.begin();
Gtk::TreeRow *row;
while(TreePath_iterator != selected_rows.end()
{
selected_row_it = p_TreeModel -> get_iter(TreePath_iterator);
row = (*selected_row_it);
selected_TreeRows.push_back(row);
TreePath_iterator++;
}
}
Do you know how to iterate through a TreeModel using the STL-like contain API called children() of a TreeModel? It's most useful for iterating over all of the rows of a TreeModel or getting the size (AKA row count) of a TreeModel. Its use depends on whether you're using a ListStore, TreeStore or a custom TreeModel.

Searching deep into Telerik Radtreview subtrees for a node with given value?

I have a RadTreeView C# component. The tree is nested, so some Nodes have their sub-trees, stored in Nodes property of upper-level Nodes.
Now I need to find a node by value. Node is hidden somewhere in subtrees. If I use call
RadTreeNode rtn= PagesTreeView.Nodes.FindNodeByValue(i.ToString());
where PagesTreeView is my tree, then it searches only across top-level nodes.
How I can Find Node by Value using not only Nodes from the current level of tree, but also dive into subtrees? Do I need to write such recursive search myself or there is a straightforward solution?
Recursively searching the RadComboBox
There isn't a built in function to recursively search, however you can roll your own pretty easiliy. This should work for you (not tested):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
FindNodeRecursive(node.Nodes, value);
}
return null;
}
}
And then call it like this:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
Yes, you would need to write your own recursive function to do the search. Another option if you are using the ASP.NET AJAX version of the control is the GetAllNodes() method. It returns all nodes in the tree hierarchy (I'm guessing it uses recursion under the hood). Once you have the entire list you would search it for the node you care about. The big drawback with that approach is if you have a lot of nodes the search could be slow and consume a lot of memory. Doing your own recursive search is the best approach.
See this article for more info.
Old question but I faced this same problem in my application, how to search through the hierarchical tree nodes.
I would like to share one correction to previous solutions proposal. When calling FindNodeRecursive() recursively the return value of your recursive call is never being evaluated or assigned to a variable. So, you will always end up with going through the foreach loop and return value is null.
Corrected and tested function code (WPF C#):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
RadTreeNode ret = null;
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
ret = FindNodeRecursive(node.Nodes, value);
}
return ret;
}
}
Function use:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
if (node != null) // found
{
;
}

Why is Document.html() so slow?

I was under the impression that the most costly method in Jsoup's API is parse().
But I just discovered that Document.html() could be even slower.
Given that the Document is the output of parse() (i.e. this is after parsing), I find this surprising.
Why is Document.html() so slow?
Answering myself. The Element.html() method is implemented as:
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return accum.toString().trim();
}
Using StringBuilder instead of String is already a good thing, and the use of StringBuilder.toString() and String.trim() may not explain the slowness of Document.html(), even for a relatively large document.
But in the middle, our method calls an overloaded version, Element.html(StringBuilder) which loops through all child nodes in the document:
private void html(StringBuilder accum) {
for (Node node : childNodes)
node.outerHtml(accum);
}
Thus if the document contains lots of child nodes, it will be slow.
It would be interesting to see whether there could be a faster implementation of this.
For example, if Jsoup stores a cached version of the raw html that was provided to it via Jsoup.parse(). As an option of course, to maintain backward compatibility and small footprint in memory.

Tree traversal without recursive / stack usage (C#)?

I'm working with WPF and I'm developing a complex usercontrol, which is composed of a tree with rich functionality etc.
For this purpose I used a View-Model design pattern, because some operations couldn't be achieved directly in WPF. So I take the IHierarchyItem (which is a node and pass it to this constructor to create a tree structure)
private IHierarchyItemViewModel(IHierarchyItem hierarchyItem, IHierarchyItemViewModel parent)
{
this.hierarchyItem = hierarchyItem;
this.parent = parent;
List<IHierarchyItemViewModel> l = new List<IHierarchyItemViewModel>();
foreach (IHierarchyItem item in hierarchyItem.Children)
{
l.Add(new IHierarchyItemViewModel(item, this));
}
children = new ReadOnlyCollection<IHierarchyItemViewModel>(l);
}
The problem is that this constructor takes about 3 seconds !! for 200 items on my dual-core.
Am I doing anythig wrong or recursive constructor call is that slow?
Thank you very much!
OK I found a non recursive version by myself, although it uses the Stack.
It traverses the whole tree:
Stack<MyItem> stack = new Stack<MyItem>();
stack.Push(root);
while (stack.Count > 0)
{
MyItem taken = stack.Pop();
foreach (MyItem child in taken.Children)
stack.Push(MyItem);
}
There should be nothing wrong with a recursive implementation of a tree, especially for such a small number of items. A recursive implementation is sometimes less space efficient, and slightly less time efficient, but the code clarity often makes up for it.
It would be useful for you to perform some simple profiling on your constructor. Using one of the suggestions from: http://en.csharp-online.net/Measure_execution_time you could indicate for yourself how long each piece is taking.
There is a possibility that one piece in particular is taking a long time. In any case, that might help you narrow down where you are really spending the time.

Resources