how to use lockf with xerces-c - c++11

I am new to programming and I am trying to use lockf to lock a XML file. I using xerces-c to parse the XML file and I need to lock the file. The function is similar the the example below:
void GetConfig::readConfigFile(string& configFile)
throw( std::runtime_error )
{
// Configure DOM parser.
m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never );
m_ConfigFileParser->setDoNamespaces( false );
m_ConfigFileParser->setDoSchema( false );
m_ConfigFileParser->setLoadExternalDTD( false );
try
{
m_ConfigFileParser->parse( configFile.c_str() );
// no need to free this pointer - owned by the parent parser object
DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();
// Get the top-level element: NAme is "root". No attributes for "root"
DOMElement* elementRoot = xmlDoc->getDocumentElement();
if( !elementRoot ) throw(std::runtime_error( "empty XML document" ));
// Parse XML file for tags of interest: "ApplicationSettings"
// Look one level nested within "root". (child of root)
DOMNodeList* children = elementRoot->getChildNodes();
const XMLSize_t nodeCount = children->getLength();
// For all nodes, children of "root" in the XML tree.
for( XMLSize_t xx = 0; xx < nodeCount; ++xx )
{
DOMNode* currentNode = children->item(xx);
if( currentNode->getNodeType() && // true is not NULL
currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element
{
// Found node which is an Element. Re-cast node as element
DOMElement* currentElement
= dynamic_cast< xercesc::DOMElement* >( currentNode );
if( XMLString::equals(currentElement->getTagName(), TAG_ApplicationSettings))
{
// Already tested node as type element and of name "ApplicationSettings".
// Read attributes of element "ApplicationSettings".
const XMLCh* xmlch_OptionA
= currentElement->getAttribute(ATTR_OptionA);
m_OptionA = XMLString::transcode(xmlch_OptionA);
const XMLCh* xmlch_OptionB
= currentElement->getAttribute(ATTR_OptionB);
m_OptionB = XMLString::transcode(xmlch_OptionB);
break; // Data found. No need to look at other elements in tree.
}
}
}
}
}
So, can anyone help me to implement lockf in this function?

Related

abort object3d.traverse in three.js

How can I abort the traverse when I traverse a three.js object?
scene.traverse(x => {
if (x.userData)
// stop traversing here
});
return and break do not work
Object3D.traverse code (r134)
You would need to modify the traverse function to bail based on output from your callback function.
Something like this (untested):
// three.js/src/core/Object3D.js
traverse( callback ) {
let bailedOut = callback( this );
if( !bailedOut ) {
const children = this.children;
for ( let i = 0, l = children.length; i < l && !bailedOut; i ++ ) {
bailedOut = children[ i ].traverse( callback );
}
}
return bailedOut;
}
And then call it like:
function doTheThing( node ) {
let bailOut = false;
if( node.userData ) {
bailOut = true;
}
else {
// do the thing
}
return bailOut;
}
scene.traverse( doTheThing );
The processing basically continues until your callback returns true, at which point it triggers a cascade back up the traverse recursion chain until it exits the original call.

libxml2: xpath relative to sub node

Given the xml file
<a>
<b>
<d>v</d>
</b>
<c>
<d>v</d>
</c>
</a>
And the xpath "//d/text()"
I want to apply the xpath only to c and not to the whole document.
This has to work with libxml2 2.7.6
Doing this does not work;
xmlNodePtr node = <node pointer to c>
xmlXPathContextPtr xpathCtx = xmlXPathNewContext( node->doc );
xpathCtx->node = node;
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression ( "//d/text()", xpathCtx);
Returned xpathObj contains refences to both /a/b/d and /a/c/d. Only /a/c/d was expected.
Use the path .//d or .//d/text() if you want to find descendants relative to another node. A path starting with //d searches all d descendant elements of the root node (also called document node).
Solved with:
xmlNodePtr node = <node pointer to c>
xmlXPathContextPtr xpathCtx = xmlXPathNewContext( node->doc );
//Update the document to set node as root
xmlNodePtr myParent = node->parent;
xmlNodePtr originalRootElement = xmlDocGetRootElement( node->doc );
xmlDocSetRootElement( node->doc, node );
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression ( "//d/text()", xpathCtx);
//xpathObj contains only /a/c/d, as expected
//restore the xml document
xmlDocSetRootElement( originalRootElement->doc, originalRootElement );
xmlAddChild( myParent, node );
Tested with valdrind.
The above example gives just the idea. In the following the complete implementation (thanks to Julo for his comment):
//Update Doc to support xpath on logical root node and restore the document structure at scope exit
class XmlDoc_UpdateDocAndRestoreAtScopeExit {
public:
XmlDoc_UpdateDocAndRestoreAtScopeExit( _xmlDoc* doc, _xmlNode* logicalRootNode) :
_doc ( doc ),
_logicalRootNode ( logicalRootNode ),
_originalRootElement( 0 ),
_refParent ( 0 ),
_refPrevSibling ( 0 ),
_refNextSibling ( 0 ),
_toRestore(false)
{
_originalRootElement = xmlDocGetRootElement( doc );
_refParent = _logicalRootNode->parent;
_refPrevSibling = _logicalRootNode->prev;
_refNextSibling = _logicalRootNode->next;
if ( _logicalRootNode != _originalRootElement ) {
xmlDocSetRootElement( _doc, _logicalRootNode );
_toRestore = true;
}
}
~XmlDoc_UpdateDocAndRestoreAtScopeExit() {
if ( _toRestore ) {
//Restore the root node
xmlDocSetRootElement( _doc, _originalRootElement );
//Restore the node at its original place
if ( 0 != _refPrevSibling ) {
xmlAddNextSibling( _refPrevSibling, _logicalRootNode );
} else if ( 0 != _refNextSibling ) {
xmlAddPrevSibling( _refNextSibling, _logicalRootNode );
} else {
xmlAddChild( _refParent, _logicalRootNode );
}
}
}
private:
XmlDoc_UpdateDocAndRestoreAtScopeExit() ; // not implemented
XmlDoc_UpdateDocAndRestoreAtScopeExit(const XmlDoc_UpdateDocAndRestoreAtScopeExit &) ; // not implemented
XmlDoc_UpdateDocAndRestoreAtScopeExit & operator= (const XmlDoc_UpdateDocAndRestoreAtScopeExit &) ; // not implemented
private:
_xmlDoc* _doc;
_xmlNode* _logicalRootNode;
_xmlNode* _originalRootElement;
_xmlNode* _refParent;
_xmlNode* _refPrevSibling;
_xmlNode* _refNextSibling;
bool _toRestore;
};
//Somewhere in the code...
xmlNodePtr node = <node pointer to c>
xmlXPathContextPtr xpathCtx = xmlXPathNewContext( node->doc );
//Here set the _rootNodePtr as the root of the document to use xpath on your "logical" root
//At scope exit the document's structure will be restored.
XmlDoc_UpdateDocAndRestoreAtScopeExit xmlDoc_UpdateDocAndRestoreAtScopeExit( node->doc, node );
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression ( "//d/text()", xpathCtx);
//xpathObj contains only /a/c/d, as expected

Kendo tree view adding child nodes dynamically is not working

Here, there are two Kendo tree views,First One here (named- #credentialsTreeView") contains nodes with check boxes with parent node, it's child nodes and inner children etc,
there is another kendo tree view (named-#CurriculumcustomCredTreeView ),what i want to do is,all the nodes i checked in the first tree view should be added into the second tree view by maintaining the exact parent child relation,for example if there is a hierarchy like parent1==>child1==>child2 (which is child of child1),if child2 is checked all it's parent nodes including child2 should be added to second tree view, but here the problem is , 1st: parent node can be added, as it can be added to the treeview in user i/f and also in datasource,so it is working fine but again on appending it's child node to this added node it is not added with the datasource,so on adding the next child node to it, it is impossible to get the details of the node from datasource to which i need to add the next node,
Kendo version--2013.3.1119.440
please see the code i have used.and please let me know the details as soon as possible.
function onAddToRequirement()
{
var treeViewCraftData = $("#credentialsTreeView").data("kendoTreeView").dataSource.data();//1st tree view which contains initially loaded list of nodes with different levels(with multiple childs and innerchilds with check boxes)
var treeViewSelectedTextList = [];
var requirementTreeView = $("#CurriculumcustomCredTreeView").data("kendoTreeView");//2nd tree view to which the selected nodes from 1st tree view to be added dynamically
$("#credentialsTreeView input[type=checkbox]:checked").closest(".k-item").each(function () {
treeViewSelectedTextList.push(
$(this).closest('.k-item').text()
);
});
var treeViewSelectedList = [];
var currentCraftNode = null;//currently three levels are there as craft==>its levels(can be multiple)==>it's Modules(can be multiple)
var currentLevelNode = null;
var currentModuleNode = null;
for (var j = 0; j < treeViewCraftData.length; j++) //treeViewCraftData contains the entire data in the datsource of 1st tree view and looping through it
{
if (treeViewCraftData[j].hasChildren)//checking craft has children
{
var treeViewLevelData = treeViewCraftData[j].children.data();//if so taking all its, levels (craft,s children)
currentCraftNode = treeViewCraftData[j];
for (var k = 0; k < treeViewLevelData.length; k++) //looping through levels
{
if (treeViewLevelData[k].hasChildren) //checking levels has children(named modules here)
{
currentLevelNode = treeViewLevelData[k];
var treeViewModuleData = treeViewLevelData[k].children.data();
for (var l = 0; l < treeViewModuleData.length; l++) //looping through modules(inner children) and checking if it is checked
{
if (treeViewModuleData[k].checked || $.inArray(treeViewModuleData[k].text, treeViewSelectedTextList) > -1)
{
currentModuleNode = treeViewModuleData[k];
if (requirementTreeView.dataSource._data.length > 0)//added condition to prevent it from adding duplicate nodes to 2nd tree view,in first case directly it goes to else part
{
var dataItemcraft1 = null;
var dataItemlevel1 = null;
$(requirementTreeView.dataSource.data()).each(function()
{
if (this.id !== currentCraftNode.id)
{
requirementTreeView.append({//appending 1st node
Name: currentCraftNode.Name,
id: currentCraftNode.id,
hasChildren:currentCraftNode.hasChildren,
//items: treeViewSelectedList.length != 0 ? treeViewSelectedList : null
}, null);
}
});
dataItemcraft1 = requirementTreeView.dataSource.get(currentCraftNode.id);
$(requirementTreeView.dataSource.data()).each(function() {
if (this.id !== currentLevelNode.id) {//appending 2nd node to first node
requirementTreeView.append({
Name: currentLevelNode.Name,
id: currentLevelNode.id,
hasChildren: currentLevelNode.hasChildren,
}, requirementTreeView.dataSource.get(dataItemcraft1.uid));
}
});
dataItemlevel1 = requirementTreeView.dataSource.get(currentCraftNode.id);//here it throws exception as above node is not added to the datsource
$(requirementTreeView.dataSource.data()).each(function() {//code to append 3rd node to above added node
//ebugger;
if (this.id !== currentModuleNode.id) {
requirementTreeView.append({
Name: currentModuleNode.Name,
id: currentModuleNode.id,
hasChildren: currentModuleNode.hasChildren,
//items: treeViewSelectedList.length != 0 ? treeViewSelectedList : null
}, requirementTreeView.dataSource.get(dataItemlevel1.uid));
}
});
dataItemcraft1 = null;
dataItemlevel1 = null;
} else
{
requirementTreeView.append//appending 1st node
({
Name: currentCraftNode.Name,
id: currentCraftNode.id,
hasChildren: currentCraftNode.hasChildren,
Value: currentCraftNode.id
});
var dataItemcraft = requirementTreeView.dataSource.get(currentCraftNode.id);//working fine
requirementTreeView.append//appending 2nd node to first node
({
Name: currentLevelNode.Name,
id: currentLevelNode.id,
hasChildren: currentLevelNode.hasChildren,
}, requirementTreeView.findByUid(dataItemcraft.uid));
requirementTreeView.expand(requirementTreeView.findByUid(dataItemcraft.uid));
var dataItemlevel = requirementTreeView.dataSource.get(currentLevelNode.id);//here it throws exception as above node is not added to the datsource
requirementTreeView.append({
Name: currentModuleNode.Name,
id: currentModuleNode.id,
hasChildren: currentModuleNode.hasChildren,
//items: treeViewSelectedList.length != 0 ? treeViewSelectedList : null
}, requirementTreeView.findByUid(dataItemlevel.uid));
requirementTreeView.expand(requirementTreeView.findByUid(dataItemlevel.uid));
dataItemcraft = null;
dataItemlevel = null;
}
}
}
} else {
}
}
}
}

Attempt at Circular Buffer - Javascript

Right! Here is my attempt at a circular buffer (For use in a graphing program, using the canvas element). Have yet to get round to testing it out.
Question is - Can anyone see any flaws in my logic? Or bottlenecks?
/**
* A circular buffer class.
* #To add value -> bufferObject.addValue(xValue, yValue);
* #To get the First-in value use -> bufferObject.getValue(0);
* #To get the Last-in value use -> bufferObject.getValue(bufferObject.length);
**/
var circularBuffer = function (bufferSize) {
this.bufferSize = bufferSize;
this.buffer = new Array(this.bufferSize); // After testing on jPerf -> 2 x 1D array seems fastest solution.
this.end = 0;
this.start = 0;
// Adds values to array in circular.
this.addValue = function(xValue, yValue) {
this.buffer[this.end] = {x : xValue, y: yValue};
if (this.end != this.bufferSize) this.end++;
else this.end = 0;
if(this.end == this.start) this.start ++;
};
// Returns a value from the buffer
this.getValue = function(index) {
var i = index+this.start;
if(i >= this.bufferSize) i -= this.bufferSize; //Check here.
return this.buffer[i]
};
// Returns the length of the buffer
this.getLength = function() {
if(this.start > this.end || this.start == this.bufferSize) {
return this.xBuffer.length;
} else {
return this.end - this.start;
}
};
// Returns true if the buffer has been initialized.
this.isInitialized = function() {
if(this.end != this.start) return true;
else return false;
};
}
Please feel free to reuse this code.
Updated twice (and tested!).
Update: Found another implementation Circular buffer in JavaScript
Made class variables private, corrected old xBuffer reference. Will do more edits tonight.
/**
* A circular buffer class.
* #To add value -> bufferObject.addValue(xValue, yValue);
* #To get the First-in value use -> bufferObject.getValue(0);
* #To get the Last-in value use -> bufferObject.getValue(bufferObject.length);
**/
var circularBuffer = function (buffer_size) {
var bufferSize = buffer_size;
var buffer = new Array(bufferSize); // After testing on jPerf -> 2 x 1D array seems fastest solution.
var end = 0;
var start = 0;
// Adds values to array in circular.
this.addValue = function(xValue, yValue) {
buffer[end] = {x : xValue, y: yValue};
if (end != bufferSize) end++;
else end = 0;
if(end == start) start++;
};
// Returns a value from the buffer
this.getValue = function(index) {
var i = index+start;
if(i >= bufferSize) i -= bufferSize; //Check here.
return buffer[i];
};
// Returns the length of the buffer
this.getLength = function() {
if(start > end || start == bufferSize) {
return buffer.length;
} else {
return end - start;
}
};
// Returns true if the buffer has been initialized.
this.isInitialized = function() {
return (end != start) ? true : false;
};
}
I implemented Vogomatix's code above, and got a few bugs. The code writes off the end of the buffer, expanding the buffer size automatically, and the addValue function is bound to a particular type. I've adjusted the code to work with any object type, added some private subroutines to simplify, and added a function to dump the contents out to a string, with an optional delimiter. Also used a namespace.
What's missing is a removeValue() but it would be just a check of count to be greater than zero, then a call to _pop().
This was done because I needed a rolling, scrolling text buffer for inbound messages, that did not grow indefinitely. I use the object with a textarea, so I get behaviour like a console window, a scrolling text box that does not chew up memory indefinitely.
This has been tested with expediency in mind, in that I am coding quickly, posted here in the hope that fellow OverFlow-ers use and anneal the code.
///////////////////////////////////////////////////////////////////////////////
// STYLE DECLARATION
// Use double quotes in JavaScript
///////////////////////////////////////////////////////////////////////////////
// Global Namespace for this application
//
var nz = nz || {};
nz.cbuffer = new Object();
///////////////////////////////////////////////////////////////////////////////
// CIRCULAR BUFFER
//
// CREDIT:
// Based on...
// Vogomatix http://stackoverflow.com/questions/20119513/attempt-at-circular-buffer-javascript
// But re-written after finding some undocumented features...
/**
* A circular buffer class, storing any type of Javascript object.
* To add value -> bufferObject.addValue(obj);
* To get the First-in value use -> bufferObject.getValue(0);
* To get the Last-in value use -> bufferObject.getValue(bufferObject.length);
* To dump to string use -> bufferObject.streamToString(sOptionalDelimiter); // Defaults to "\r\n"
**/
nz.cbuffer.circularBuffer = function (buffer_size) {
var bufferSize = buffer_size > 0 ? buffer_size : 1; // At worst, make an array of size 1
var buffer = new Array(bufferSize);
var end = 0; // Index of last element.
var start = 0; // Index of first element.
var count = 0; // Count of elements
// 'Private' function to push object onto buffer.
this._push = function (obj) {
buffer[end] = obj; // Write
end++; // Advance
if (end == bufferSize) {
end = 0; // Wrap if illegal
}
count++;
}
// 'Private' function to pop object from buffer.
this._pop = function () {
var obj = buffer[start];
start++;
if (start == bufferSize) {
start = 0; // Wrap
}
count--;
return obj;
}
// Adds values to buffer.
this.addValue = function (obj) {
if (count < bufferSize) {
// Just push
this._push(obj);
}
else {
// Pop, then push
this._pop();
this._push(obj);
}
}
// Returns a value from the buffer. Index is relative to current notional start.
this.getValue = function (index) {
if (index >= count || index < 0) return; // Catch attempt to access illegal index
var i = index + start;
if (i >= bufferSize) {
i -= bufferSize;
}
return buffer[i];
}
// Returns the length of the buffer.
this.getLength = function () {
return count;
}
// Returns all items as strings, separated by optional delimiter.
this.streamToString = function (delim) {
delim = (typeof delim === "undefined") ? "\r\n" : delim; // Default syntax; Default to CRLF
var strReturn = "";
var once = 0;
var index = 0;
var read = index + start;
for (; index < count; ++index) {
if (once == 1) strReturn += delim.toString();
strReturn += buffer[read].toString();
read++;
if (read >= bufferSize) read = 0;
once = 1;
}
return strReturn;
}
}

How to reference styles properly in InDesign Scripting?

I would like to know what is the proper way to reference a character style, a paragraph style or any other style in InDesign Scripting.
Please keep in mind that they could be under style group.
This should do it. Have a look at the function get_style.
update: use id instead of names
// written for
// http://stackoverflow.com/questions/19302941/how-to-reference-styles-properly-in-indesign-scripting
// author: #fabiantheblind
// license: wtfpl http://www.wtfpl.net
main();
function main(){
var doc = app.documents.add();// add a document
// create some styles
doc.paragraphStyles.add({name:"one"});
doc.paragraphStyles.add({name:"two"});
doc.paragraphStyles.add({name:"three"});
// add a group
var grp1 = doc.paragraphStyleGroups.add({name:"grp1"});
// add a style in the group
grp1.paragraphStyles.add({name:"four"});
// add a group in the group
var grp2 = grp1.paragraphStyleGroups.add({name:"grp2"});
// add a style in the group in the group
var parstylefive = grp2.paragraphStyles.add({name:"five"});
var fiveid = parstylefive.id;
var pg = doc.pages[0];// first page in new doc
var tf= pg.textFrames.add({geometricBounds:[0,0,100,100]});// add a textframe
tf.contents = TextFrameContents.PLACEHOLDER_TEXT;// add some cintent
var astyle = get_style(doc, fiveid);//get a style by name
if(astyle === null){
// error
alert("There is no style with that name");
}else{
// woohoo! \o/
tf.paragraphs.everyItem().appliedParagraphStyle = astyle;
}
}
/**
* This loops through all paragraph styles and returns one by his name
* could be rewritten for allCharacterStyles, allObjectStyles etc
*/
function get_style(d, id){
var thestyle = null;// result
for(var i = 0; i <d.allParagraphStyles.length;i++ ){
var onestyle = d.allParagraphStyles[i]; // isolate
if(id === onestyle.id){
thestyle = onestyle;// found it
} // end of check
} // end of loop i
// if we did not finds it we return null else Object ParagraphStyle
return thestyle;
}
I took an approach where you have to work with what I call the Fully Qualified Name (FQN) of a style, which is combination of all the groups and the style name separated by a pipe (|)
I've implemented the two following function in our code. They can be used with all type of styles with just a little bit of modification to the getStyleByFullyQualifiedName() function to support the other 4 types.
//getStyleFullyQualifiedName allow you to retrieve the style FQN,
//by providing a style object. Combine the name of the style and
//groups together separated by pipe (|).
function getStyleFullyQualifiedName(object){
var objectName = object.name;
if(object.parent.constructor.name != "Document"){
return getStyleFullyQualifiedName(object.parent) + "|" + objectName;
}
return objectName;
}
function getStyleByFullyQualifiedName(paragraphStyleFQN, document){
var tmp = paragraphStyleFQN.split("|");
var object = document;
for(var i=0; i < (tmp.length - 1); i++){
if(object.isValid){
object = object.paragraphStyleGroups.itemByName(tmp[i]);
}else{
return null;
}
}
if(!object.isValid){
return null;
}
object = object.paragraphStyles.itemByName(tmp[(tmp.length - 1)]);
if(!object.isValid){
return null;
}
return object;
}
//Assuming you have a style "Heading 1" under group "Title" and "Center.
//You can retrieve the style object like this.
var styleObject = getStyleByFullyQualifiedName("Title|Center|Heading 1", app.activeDocument);
//You can get the style FQN when you have a style object like this.
var styleFQN = getStyleFullyQualifiedName(styleObject);
alert("Valid: " + styleObject.isValid + " styleFQN: " + styleFQN);

Resources