How can I reuse code between Javascript macros and minimize work done within the macros? - tiddlywiki

I currently have two macros that are part of a (very limited-audience) plugin I'm developing, that both look basically like:
(function(){
exports.name = "name";
exports.params = [
{name: "value"}
];
function get(tiddler) {
// return some contents of some tiddler fields according to some rule
}
function parse(data) {
// convert string to some kind of useful object
}
function logic(x, y) {
// determine whether the two objects correspond in some way
};
function format(data, title) {
// produce WikiText for a link with some additional decoration
};
exports.run = function(value) {
value = parse(value);
var result = [];
this.wiki.each(function(tiddler, title) {
var data = get(tiddler);
if (data !== undefined && logic(value, parse(data))) {
result.push(format(data, title));
}
});
return result.join(" | ");
};
})();
So they're already fairly neatly factored when considered individually; the problem is that only the core logic is really different between the two macros. How can I share the functions get, logic and format between the macros? I tried just putting them in a separate tiddler, but that doesn't work; when the macros run, TW raises an error claiming that the functions are "not defined". Wrapping each function as its own javascript macro in a separate tiddler, e.g.
(function(){
exports.name = "get";
exports.params = [
{name: "tiddler"}
];
exports.run = function(tiddler) {
// return some contents of some tiddler fields according to some rule
}
})();
also didn't help.
I'd also like to set this up to be more modular/flexible, by turning the main get/parse/logic/format process into a custom filter, then letting a normal filter expression take care of the iteration and using e.g. the widget or <> macro to display the items. How exactly do I set this up? The documentation tells me
If the provided filter operators are not enough, a developer can add
new filters by adding a module with the filteroperator type
but I can't find any documentation of the API for this, nor any examples.

How can I share the functions get, logic and format between the macros?
You can use the Common/JS standard require('<tiddler title>') syntax to access the exports of another tiddler. The target tiddler should be set up as a JS module (ie, the type field set to application/javascript and the module-type field set to library). You can see an example here:
https://github.com/Jermolene/TiddlyWiki5/blob/master/core/modules/widgets/count.js#L15
I'd also like to set this up to be more modular/flexible, by turning the main get/parse/logic/format process into a custom filter, then letting a normal filter expression take care of the iteration and using e.g. the widget or <> macro to display the items. How exactly do I set this up?
The API for writing filter operators isn't currently documented, but there are many examples to look at:
https://github.com/Jermolene/TiddlyWiki5/tree/master/core/modules/filters

Related

Returning other values from d3.call

Per the docs, "The call operator always returns the current selection, regardless of the return value of the specified function." I'd like to know if there is a variant of call or reasonable workaround for getting call-behavior that returns values other than the selection.
Motivation:
I've got a chart and a datebrush, each encapsulated in a function
function trends_datebrush() {
// Setup
function chart(_selection) {
_selection.each(function(_data) {
// Do things
...});
}
return chart;
};
(The chart follows a similar format but isn't called datebrush).
These are instantiated with:
d3.select("someDiv")
.datum("data")
.call(trends_datebrush());
// And then we call the chart
I'd like to return a subselection from brush to be used as the data variable in the chart call. As is I need to make them both aware of some higher order global state, which gets messy especially since I want other control functions to drill down on the data. If I could override call, then I could do something like
d3.select("someDiv")
.datum("data")
.call(trends_datebrush())
.call(trends_chart());
And then if I were to implement some new filter I could throw it into the chain with another call statement.
tl;DR: Looking for ways to get chain chart calls s.t. they can pass transformed data to each other. I want monadic D3 charts! Except I don't really know monads so I might be misusing the word.

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.

Convert: "preg_replace" -> "preg_replace_callback"

I'm trying to update my code but I'm stuck at this codeline.
How do I proceed to convert this to preg_replace_callback?
$buffer = preg_replace("#§([a-z0-9-_]+)\.?([a-z0-9-_]+)?#ie","\$templ->\\1(\\2)",$buffer);
Here is the process of converting preg_replace (with the e modifier) to preg_replace_callback. You create a function that will act on all of the matches that it finds. Normally this is pretty simple, however with your case it is a little more complex as the function returns the value of an object. To accommodate this, you can use an anonymous function (a function without a name) and attach the USE keyword with your object to it. This can be done inline, however for the sake of clarity, I have made it its own variable.
Take a look at this portion of the complete code below:
$callback_function = function($m) use ($templ) {
I created a variable named callback_function that will be used in the preg_replace_callback function. This function will be fed each match as the variable $m automatically. So within the function you can use $m[1] and $m[2] to access the parts of the expression that it matched. Also note that I've attached the $templ variable with the USE keyword so that $templ will be available within the function.
Hopefully that makes sense. Anyway, here is the complete code:
<?php
// SET THE TEXT OF THE BUFFER STRING
$buffer = 'There are a bunch of §guns.roses growing along the side of the §guns.road.';
// THIS IS JUST A SAMPLE CLASS SINCE I DO NOT KNOW WHAT YOUR CLASS REALLY LOOKS LIKE
class Test {
// FUNCTION NAMED 'guns' WITH A SPACE FOR A PARAMETER
public function guns($info) {
return '<b>BLUE '.strtoupper($info).'</b>';
}
}
// INSTANTIATE A NEW 'Test' CLASS
$templ = new Test();
// THIS IS THE FUNCTION THAT YOUR CALLBACK WILL USE
// NOTICE THAT IT IS AN ANONYMOUS FUNCTION (THERE IS NO FUNCTION NAME)
$callback_function = function($m) use ($templ) {
return $templ->$m[1]($m[2]);
};
// THIS USES PREG_REPLACE_CALLBACK TO SUBSTITUTE OUT THE MATCHED TEXT WITH THE CALLBACK FUNCTION
$buffer = preg_replace_callback('/§([a-z0-9-_]+)\.?([a-z0-9-_]+)?/i', $callback_function, $buffer);
// PRINT OUT THE FINAL VERSION OF THE STRING
print $buffer;
This outputs the following:
There are a bunch of <b>BLUE ROSES</b> growing along the side of the <b>BLUE ROAD</b>.

Why did Playframework 2 use a custom Scala Template Engine instead of scalas build in xml mode?

Play 2.0 uses a custom scala based template engine that allows to use a subset of scala inside html code.
Why was this design decision made instead of using scalas build-in xml mode?
The play template engine has some disadvantages like
only a subset of scala is supported, for example it seems not to be possible to define functions inside of functions
no editor support in eclipse
On the other hand, I understand that the play scala template engine supports non-well-formed html which wouldn't be possible with scalas xml mode, but I guess it should always be possible to write the templates in a well formed way. I'm just a beginner in play and scala and would simply like to understand the context.
I think it has several answers :
It is a template. Templates are not supposed to hold complex logic. All logic manipulation has to be done in the controller/model.
Templates can have about any format you want : email, CSV, SQL and so on. Restricting a template to valid XML is really limiting the possibilities of the framework.
Everything is compilable. Even routes, assets, template inheritance, etc. In order for those mecanisms to work with the rest of the framework, some choice probably had to be made. But no one will be able to answer you better than the creators of the framework.
One reason may be the clumsy handling of attributes in xml in scala. There are two problems:
Attributes like "selected" which must either be present or not
Adding a list of attributes dynamically like the htmlArgs of the input helper templates
An example in plain scala shows the difficulties:
def addAttributes(element: Elem, attributes: Map[Symbol, _ <: Any]): Elem = {
var el = element
for ((key, value) <- attributes) el = el % Attribute(None, key.name, Text(value.toString), Null)
el
}
def multiselect[T](field: play.api.data.Field,
options: Seq[T],
optionValue: T => String,
optionText: T => String,
args: (Symbol, Any)*)(implicit handler: FieldConstructor, lang: play.api.i18n.Lang) = {
val values = { field.indexes.map { v => field("[" + v + "]").value } }
input(field, args: _*) {
(id, name, value, htmlArgs) =>
Html(
addAttributes(
<select id={ id } name={ name } multiple="multiple">
{
options.map { v =>
val z: Option[String] = if (values contains v) Some("selected") else None
<option value={ optionValue(v) } selected={ z map Text }>{ optionText(v) }</option>
}
}
</select>,
htmlArgs).toString)
}
}

What is action ID in Photoshop script?

I read a tutorial of photoshop scripting,
and I can't understand this line.
//get action ID
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
I think these codes are call Photoshop actions,
but I don't have any references, so
I can't really understand how to use these.
Why are they need and How to use these?
Well, the code you posted creates convenient aliases for the charIDToTypeID and stringIDToTypeID functions. Those functions simply convert strings to an enumeration value of type PSConstants. For instance,
CharIDToTypeID("BD1") //returns 1111765280 which corresponds to PSConstants.phEnumBitDepth1
See http://www.pcpix.com/Photoshop/

Resources