void Step::evaluate(Node* context, NodeSet& nodes) const { nodesInAxis(context, nodes); EvaluationContext& evaluationContext = Expression::evaluationContext(); for (unsigned i = 0; i < m_predicates.size(); i++) { Predicate* predicate = m_predicates[i]; NodeSet newNodes; if (!nodes.isSorted()) newNodes.markSorted(false); evaluationContext.size = nodes.size(); evaluationContext.position = 1; for (unsigned j = 0; j < nodes.size(); j++) { Node* node = nodes[j]; Expression::evaluationContext().node = node; EvaluationContext backupCtx = evaluationContext; if (predicate->evaluate()) newNodes.append(node); evaluationContext = backupCtx; ++evaluationContext.position; } nodes.swap(newNodes); } }
void Step::evaluate(EvaluationContext& evaluationContext, Node* context, NodeSet& nodes) const { evaluationContext.position = 0; nodesInAxis(evaluationContext, context, nodes); // Check predicates that couldn't be merged into node test. for (unsigned i = 0; i < m_predicates.size(); i++) { Predicate* predicate = m_predicates[i].get(); OwnPtrWillBeRawPtr<NodeSet> newNodes(NodeSet::create()); if (!nodes.isSorted()) newNodes->markSorted(false); for (unsigned j = 0; j < nodes.size(); j++) { Node* node = nodes[j]; evaluationContext.node = node; evaluationContext.size = nodes.size(); evaluationContext.position = j + 1; if (predicate->evaluate(evaluationContext)) newNodes->append(node); } nodes.swap(*newNodes); } }
void ActionChoiceWindow::createButtons( ActionNode* actions, const CEGUI::Point& center, float radius, float angle, float angleWidth) { PushButton* button = NULL; if (actions->isLeaf()) { button = createButton(actions->getAction()->getName(), center); } else { if (actions->getGroup() != NULL) { button = createButton(actions->getGroup()->getName(), center); } const NodeSet children = actions->getChildren(); float angleStep = angleWidth / (float)children.size(); float ang = children.size()>1 ? angle - angleWidth : angle - 180; for (NodeSet::const_iterator iter = children.begin(); iter != children.end(); iter++) { CEGUI::Point centerChild = getPositionOnCircle(center, radius, ang); createButtons(*iter, centerChild, radius, ang, 60); ang += angleStep; } } actions->setButton(button); if (button != NULL) mWindow->addChildWindow(button); }
void Step::evaluate(Node* context, NodeSet& nodes) const { EvaluationContext& evaluationContext = Expression::evaluationContext(); evaluationContext.position = 0; nodesInAxis(context, nodes); // Check predicates that couldn't be merged into node test. for (unsigned i = 0; i < m_predicates.size(); i++) { Predicate* predicate = m_predicates[i].get(); NodeSet newNodes; if (!nodes.isSorted()) newNodes.markSorted(false); for (unsigned j = 0; j < nodes.size(); j++) { Node* node = nodes[j]; evaluationContext.node = node; evaluationContext.size = nodes.size(); evaluationContext.position = j + 1; if (predicate->evaluate()) newNodes.append(node); } nodes.swap(newNodes); } }
void RegionGraph::constructCVM( const FactorGraph &fg, const std::vector<NodeSet> &cl) { using std::pair; DLOG(INFO) << "constructCVM called (" << fg.nrNodes() << " vars, " << fg.nrFactors() << " facs, " << cl.size() << " clusters)"; // Retain only maximal clusters DLOG(INFO) << " Constructing ClusterGraph"; ClusterGraph cg( cl ); DLOG(INFO) << " Erasing non-maximal clusters"; cg.eraseNonMaximal(); // Create inner regions - first pass DLOG(INFO) << " Creating inner regions (first pass)"; std::set<NodeSet> betas; for( size_t alpha = 0; alpha < cg.nrClusters(); alpha++ ) for( size_t alpha2 = alpha; (++alpha2) != cg.nrClusters(); ) { NodeSet intersection = cg.cluster(alpha) & cg.cluster(alpha2); if( intersection.size() > 0 ) betas.insert( intersection ); } // Create inner regions - subsequent passes DLOG(INFO) << " Creating inner regions (next passes)"; std::set<NodeSet> new_betas; do { new_betas.clear(); for (std::set<NodeSet>::const_iterator gamma = betas.begin(); gamma != betas.end(); gamma++ ) for (std::set<NodeSet>::const_iterator gamma2 = gamma; (++gamma2) != betas.end(); ) { NodeSet intersection = (*gamma) & (*gamma2); if( (intersection.size() > 0) && (betas.count(intersection) == 0) ) new_betas.insert( intersection ); } betas.insert(new_betas.begin(), new_betas.end()); } while( new_betas.size() ); // Create inner regions - final phase DLOG(INFO) << " Creating inner regions (final phase)"; std::vector<Region> irs; irs.reserve( betas.size() ); for (std::set<NodeSet>::const_iterator beta = betas.begin(); beta != betas.end(); beta++ ) irs.push_back( Region(*beta,0.0) ); // Create edges DLOG(INFO) << " Creating edges"; std::vector<std::pair<size_t,size_t> > edges; for( size_t beta = 0; beta < irs.size(); beta++ ) for( size_t alpha = 0; alpha < cg.nrClusters(); alpha++ ) if( cg.cluster(alpha) >> irs[beta] ) edges.push_back( pair<size_t,size_t>(alpha,beta) ); // Construct region graph DLOG(INFO) << " Constructing region graph"; construct( fg, cg.clusters(), irs, edges ); // Calculate counting numbers DLOG(INFO) << " Calculating counting numbers"; calcCVMCountingNumbers(); DLOG(INFO) << "Done."; }
Arabica::XPath::NodeSet<std::string> InterpreterDraft6::selectTransitions(const std::string& event) { Arabica::XPath::NodeSet<std::string> enabledTransitions; NodeSet<std::string> states; for (unsigned int i = 0; i < _configuration.size(); i++) { if (isAtomic(_configuration[i])) states.push_back(_configuration[i]); } states.to_document_order(); #if 0 std::cout << "Atomic states: " << std::endl; for (int i = 0; i < states.size(); i++) { std::cout << states[i] << std::endl << "----" << std::endl; } std::cout << std::endl; #endif unsigned int index = 0; while(states.size() > index) { bool foundTransition = false; NodeSet<std::string> transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", states[index]); for (unsigned int k = 0; k < transitions.size(); k++) { if (isEnabledTransition(transitions[k], event)) { enabledTransitions.push_back(transitions[k]); foundTransition = true; goto LOOP; } } if (!foundTransition) { Node<std::string> parent = states[index].getParentNode(); if (parent) { states.push_back(parent); } } LOOP: index++; } enabledTransitions = filterPreempted(enabledTransitions); #if 0 std::cout << "Enabled transitions: " << std::endl; for (int i = 0; i < enabledTransitions.size(); i++) { std::cout << DOMUtils::xPathForNode(enabledTransitions[i]) << std::endl; } std::cout << std::endl; #endif return enabledTransitions; }
Arabica::XPath::NodeSet<std::string> InterpreterDraft6::selectEventlessTransitions() { Arabica::XPath::NodeSet<std::string> enabledTransitions; NodeSet<std::string> states; for (unsigned int i = 0; i < _configuration.size(); i++) { if (isAtomic(_configuration[i])) states.push_back(_configuration[i]); } states.to_document_order(); #if 0 std::cout << "Atomic States: "; for (int i = 0; i < atomicStates.size(); i++) { std::cout << ATTR(atomicStates[i], "id") << ", "; } std::cout << std::endl; #endif unsigned int index = 0; while(states.size() > index) { bool foundTransition = false; NodeSet<std::string> transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", states[index]); for (unsigned int k = 0; k < transitions.size(); k++) { if (!HAS_ATTR(transitions[k], "event") && hasConditionMatch(transitions[k])) { enabledTransitions.push_back(transitions[k]); foundTransition = true; goto LOOP; } } if (!foundTransition) { Node<std::string> parent = states[index].getParentNode(); if (parent) { states.push_back(parent); } } LOOP: index++; } #if 0 std::cout << "Enabled eventless transitions: " << std::endl; for (int i = 0; i < enabledTransitions.size(); i++) { std::cout << enabledTransitions[i] << std::endl << "----" << std::endl; } std::cout << std::endl; #endif enabledTransitions = filterPreempted(enabledTransitions); return enabledTransitions; }
void step(DhtRunner& dht, std::atomic_uint& done, std::shared_ptr<NodeSet> all_nodes, dht::InfoHash cur_h, unsigned cur_depth) { std::cout << "step at " << cur_h << ", depth " << cur_depth << std::endl; done++; dht.get(cur_h, [all_nodes](const std::vector<std::shared_ptr<Value>>& /*values*/) { return true; }, [&,all_nodes,cur_h,cur_depth](bool, const std::vector<std::shared_ptr<Node>>& nodes) { all_nodes->insert(nodes.begin(), nodes.end()); NodeSet sbuck {nodes.begin(), nodes.end()}; if (not sbuck.empty()) { unsigned bdepth = sbuck.size()==1 ? 0u : InfoHash::commonBits((*sbuck.begin())->id, (*std::prev(sbuck.end()))->id); unsigned target_depth = std::min(159u, bdepth+3u); std::cout << cur_h << " : " << nodes.size() << " nodes; target is " << target_depth << " bits deep (cur " << cur_depth << ")" << std::endl; for (unsigned b = cur_depth ; b < target_depth; b++) { auto new_h = cur_h; new_h.setBit(b, 1); step(dht, done, all_nodes, new_h, b+1); } } done--; std::cout << done.load() << " operations left, " << all_nodes->size() << " nodes found." << std::endl; cv.notify_one(); }); }
/** * Gets the spelling alternatives to the specified query terms. * Returns a map with term as key and an Alternative object as value for each query term */ std::map<std::string, Alternative> getAlternatives() { if (!_alternatives.empty()) return _alternatives; _alternatives.clear(); NodeSet alternatives = doc->FindFast("cps:reply/cps:content/alternatives_list/alternatives", true); for (unsigned int i = 0; i < alternatives.size(); i++) { Node *el = alternatives[i]->getFirstChild(); Alternative alt; while (el != NULL) { std::string name = el->getName(); if (name == "to") alt.to = el->getContent(); else if (name == "count") alt.count = atoi(el->getContentPtr()); else if (name == "word") { Alternative::Word w; w.count = atoi(el->getAttribute("count")->getContentPtr()); w.h = atof(el->getAttribute("h")->getContentPtr()); w.idif = atof(el->getAttribute("idif")->getContentPtr()); w.cr = atof(el->getAttribute("cr")->getContentPtr()); w.content = el->getContent(); alt.words.push_back(w); } el = el->getNextSibling(); } _alternatives[alt.to] = alt; } return _alternatives; }
// ---------------------------------------------------------------------- bool LocalizationNeighborhood:: is_sound( void ) const throw() { NodeSet temp = ref_nodes(); temp.insert( sounds_.begin(), sounds_.end() ); // if there is no info about ref-nodes of the anchors, ignore this // check return true anyway if ( anchor_cnt() > 0 && temp.size() == 0 ) return true; //TODO: Dimension anpassen !!!! return (int)temp.size() >= 3; }
void InterpreterDraft6::microstep(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) { #if VERBOSE std::cout << "Transitions: "; for (int i = 0; i < enabledTransitions.size(); i++) { std::cout << ((Element<std::string>)getSourceState(enabledTransitions[i])).getAttribute("id") << " -> " << std::endl; NodeSet<std::string> targetSet = getTargetStates(enabledTransitions[i]); for (int j = 0; j < targetSet.size(); j++) { std::cout << " " << ((Element<std::string>)targetSet[j]).getAttribute("id") << std::endl; } } std::cout << std::endl; #endif // --- MONITOR: beforeMicroStep ------------------------------ for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { try { (*monIter)->beforeMicroStep(shared_from_this()); } USCXML_MONITOR_CATCH_BLOCK(beforeMicroStep) } exitStates(enabledTransitions); monIter_t monIter; for (int i = 0; i < enabledTransitions.size(); i++) { Element<std::string> transition(enabledTransitions[i]); // --- MONITOR: beforeTakingTransitions ------------------------------ for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { try { (*monIter)->beforeTakingTransition(shared_from_this(), transition, (i + 1 < enabledTransitions.size())); } USCXML_MONITOR_CATCH_BLOCK(beforeTakingTransitions) } executeContent(transition); // --- MONITOR: afterTakingTransitions ------------------------------ for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { try { (*monIter)->afterTakingTransition(shared_from_this(), transition, (i + 1 < enabledTransitions.size())); } USCXML_MONITOR_CATCH_BLOCK(afterTakingTransitions) } } enterStates(enabledTransitions); // --- MONITOR: afterMicroStep ------------------------------ for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { try { (*monIter)->afterMicroStep(shared_from_this()); } USCXML_MONITOR_CATCH_BLOCK(afterMicroStep) } }
// setup / fetch the documents initial transitions NodeSet<std::string> InterpreterDraft6::getDocumentInitialTransitions() { NodeSet<std::string> initialTransitions; if (_userDefinedStartConfiguration.size() > 0) { // we emulate entering a given configuration by creating a pseudo deep history Element<std::string> initHistory = _document.createElementNS(_nsInfo.nsURL, "history"); _nsInfo.setPrefix(initHistory); initHistory.setAttribute("id", UUID::getUUID()); initHistory.setAttribute("type", "deep"); _scxml.insertBefore(initHistory, _scxml.getFirstChild()); std::string histId = ATTR(initHistory, "id"); NodeSet<std::string> histStates; for (int i = 0; i < _userDefinedStartConfiguration.size(); i++) { histStates.push_back(getState(_userDefinedStartConfiguration[i])); } _historyValue[histId] = histStates; Element<std::string> initialElem = _document.createElementNS(_nsInfo.nsURL, "initial"); _nsInfo.setPrefix(initialElem); initialElem.setAttribute("generated", "true"); Element<std::string> transitionElem = _document.createElementNS(_nsInfo.nsURL, "transition"); _nsInfo.setPrefix(transitionElem); transitionElem.setAttribute("target", histId); initialElem.appendChild(transitionElem); _scxml.appendChild(initialElem); initialTransitions.push_back(transitionElem); } else { // try to get initial transition from initial element initialTransitions = _xpath.evaluate("/" + _nsInfo.xpathPrefix + "initial/" + _nsInfo.xpathPrefix + "transition", _scxml).asNodeSet(); if (initialTransitions.size() == 0) { Arabica::XPath::NodeSet<std::string> initialStates; // fetch per draft initialStates = getInitialStates(); assert(initialStates.size() > 0); for (int i = 0; i < initialStates.size(); i++) { Element<std::string> initialElem = _document.createElementNS(_nsInfo.nsURL, "initial"); _nsInfo.setPrefix(initialElem); initialElem.setAttribute("generated", "true"); Element<std::string> transitionElem = _document.createElementNS(_nsInfo.nsURL, "transition"); _nsInfo.setPrefix(transitionElem); transitionElem.setAttribute("target", ATTR(initialStates[i], "id")); initialElem.appendChild(transitionElem); _scxml.appendChild(initialElem); initialTransitions.push_back(transitionElem); } } } return initialTransitions; }
NodeSet IndSetExtBySeparators::mergeComponentAndNeighbors( const NodeSet& component, const NodeSet& compNeighbors) { // neighbors and comp nodes are different sets vector<Node> mergedComp(compNeighbors.size() + component.size()); for (unsigned int i = 0; i < component.size(); i++) { mergedComp[i] = component[i]; } for (unsigned int i = 0; i < compNeighbors.size(); i++) { mergedComp[i + component.size()] = compNeighbors[i]; } return mergedComp; }
void XPathDataModel::assign(const NodeSet<std::string>& key, const NodeSet<std::string>& value, const Element<std::string>& assignElem) { if (key.size() == 0) return; if (value.size() == 0 || !value[0]) return; for (size_t i = 0; i < key.size(); i++) { switch (key[i].getNodeType()) case Node_base::ELEMENT_NODE: { assign(Element<std::string>(key[i]), value, assignElem); break; default: // std::cout << key[i].getNodeType() << std::endl; ERROR_EXECUTION_THROW("Unsupported node type for assign"); break; } } }
void XPathDataModel::assign(const NodeSet<std::string>& key, const std::string& value, const Element<std::string>& assignElem) { if (key.size() == 0) return; for (size_t i = 0; i < key.size(); i++) { Node<std::string> node = key[i]; switch (node.getNodeType()) { case Node_base::ATTRIBUTE_NODE: { Attr<std::string> attr(node); attr.setValue(value); break; } case Node_base::TEXT_NODE: { Text<std::string> text(node); text.setNodeValue(value); break; } case Node_base::ELEMENT_NODE: { Element<std::string> element(node); if (HAS_ATTR(assignElem, "type") && iequals(ATTR(assignElem, "type"), "addattribute")) { // addattribute: Add an attribute with the name specified by 'attr' // and value specified by 'expr' to the node specified by 'location'. if (!HAS_ATTR(assignElem, "attr")) ERROR_EXECUTION_THROW("Assign element is missing 'attr'"); element.setAttribute(ATTR(assignElem, "attr"), value); } else { /// test 547 while(element.hasChildNodes()) element.removeChild(element.getChildNodes().item(0)); Text<std::string> text = _doc.createTextNode(value); element.appendChild(text); } break; } default: ERROR_EXECUTION_THROW("Unsupported node type with assign"); break; } } }
void Server::_route_xml(int fd,vector<shared_ptr<Document> > docs) { Node::PrefixNsMap pnm; pnm["psxml"]="http://www.psxml.org/PSXML-0.1"; for(unsigned int i = 0; i < docs.size(); i++) { shared_ptr<Document> doc = docs[i]; Element * root = doc->get_root_node(); // deal with subscribes if(root->get_name() == "Subscribe") { NodeSet subs = doc->get_root_node()->find( "/psxml:Subscribe/psxml:XPath",pnm); list<XPathExpression> exps; for(unsigned int i =0; i < subs.size(); i++) { Element * sub = dynamic_cast<Element*>(subs[i]); assert(sub != NULL); ustring exp(sub->get_attribute("exp")->get_value()); NodeSet nss = sub->find("./psxml:Namespace",pnm); Node::PrefixNsMap prefix_map; XPathExpression xpath; xpath.expression = exp; for(unsigned int j = 0; j < nss.size(); j++) { Element * ns = dynamic_cast<Element*>(nss[j]); assert(ns != NULL); ustring pf(ns->get_attribute("prefix")->get_value()); prefix_map[pf] = ns->get_child_text()->get_content(); } xpath.ns = prefix_map; exps.push_back(xpath); } bool foreign = (_foreign_connections.count(fd) > 0); _engine.subscribe(fd,exps,foreign); // if our aggregate subscriptions have changed (non-foreign) // we tell the other psxmld servers! if(!foreign) _update_foreign_subscriptions(); } // find any data publishes _engine.publish( root->find("/psxml:Publish/*",pnm), _protocols); } }
/** * Returns the map of facets where key is path for facet and value as vector of terms for this facet */ std::map<std::string, std::vector<std::string> > getFacets() { if (!_facets.empty()) return _facets; NodeSet ns = doc->FindFast("facet", true); for (unsigned int i = 0; i < ns.size(); i++) { std::list<Node *> terms = ns[i]->getChildren("term"); std::string path = ns[i]->getAttribute("path")->getValue(); for (std::list<Node *>::iterator it = terms.begin(); it != terms.end(); it++) { _facets[path].push_back((*it)->getContent()); } } return _facets; }
void LocationPath::evaluate(NodeSet& nodes) const { bool resultIsSorted = nodes.isSorted(); for (unsigned i = 0; i < m_steps.size(); i++) { Step* step = m_steps[i]; NodeSet newNodes; HashSet<Node*> newNodesSet; bool needToCheckForDuplicateNodes = !nodes.subtreesAreDisjoint() || (step->axis() != Step::ChildAxis && step->axis() != Step::SelfAxis && step->axis() != Step::DescendantAxis && step->axis() != Step::DescendantOrSelfAxis && step->axis() != Step::AttributeAxis); if (needToCheckForDuplicateNodes) resultIsSorted = false; // This is a simplified check that can be improved to handle more cases. if (nodes.subtreesAreDisjoint() && (step->axis() == Step::ChildAxis || step->axis() == Step::SelfAxis)) newNodes.markSubtreesDisjoint(true); for (unsigned j = 0; j < nodes.size(); j++) { NodeSet matches; step->evaluate(nodes[j], matches); if (!matches.isSorted()) resultIsSorted = false; for (size_t nodeIndex = 0; nodeIndex < matches.size(); ++nodeIndex) { Node* node = matches[nodeIndex]; if (!needToCheckForDuplicateNodes || newNodesSet.add(node).isNewEntry) newNodes.append(node); } } nodes.swap(newNodes); } nodes.markSorted(resultIsSorted); }
/** Get parsed fields. * Get fields stored below the given node. * @param node root node where to start searching * @return vector of field representations. */ std::vector<InterfaceField> InterfaceParser::getFields(xmlpp::Node *node) { vector<InterfaceField> result; NodeSet set = node->find("field"); for (NodeSet::iterator i = set.begin(); i != set.end(); ++i) { InterfaceField f(&enum_constants); const Element * el = dynamic_cast<const Element *>(*i); if ( el ) { // valid element const Element::AttributeList& attrs = el->get_attributes(); for(Element::AttributeList::const_iterator iter = attrs.begin(); iter != attrs.end(); ++iter) { const Attribute* attr = *iter; //std::cout << " Attribute " << attr->get_name() << " = " << attr->get_value() << std::endl; f.setAttribute(attr->get_name(), attr->get_value()); } } else { throw InterfaceGeneratorInvalidContentException("constant is not an element"); } // Get field comment NodeSet nameset = (*i)->find("text()"); if ( nameset.size() == 0 ) { throw InterfaceGeneratorInvalidContentException("no comment for field %s", f.getName().c_str()); } const TextNode *comment_node = dynamic_cast<const TextNode *>(nameset[0]); if ( ! comment_node ) { throw InterfaceGeneratorInvalidContentException("comment node not text node for constant"); } f.setComment(comment_node->get_content()); //std::cout << "Field name: " << field_name << std::endl; try { f.valid(); result.push_back(f); } catch ( fawkes::Exception &e ) { e.print_trace(); } } for (vector<InterfaceField>::iterator i = result.begin(); i != result.end(); ++i) { for (vector<InterfaceField>::iterator j = i + 1; j != result.end(); ++j) { if ( (*i).getName() == (*j).getName() ) { throw InterfaceGeneratorAmbiguousNameException((*i).getName().c_str(), "field"); } } } return result; }
void XPathDataModel::assign(const XPathValue<std::string>& key, const NodeSet<std::string>& value, const Element<std::string>& assignElem) { if (value.size() == 0 || !value[0]) return; switch (key.type()) { case NODE_SET: { assign(key.asNodeSet(), value, assignElem); break; } case STRING: case Arabica::XPath::BOOL: case NUMBER: case ANY: ERROR_EXECUTION_THROW("Type ANY as key for assign not supported") } }
bool isInNodeSet(Node node, const NodeSet& sortedNodes) { int n = sortedNodes.size(); int i = 0; while (n > 0) { int j = i + n / 2; if (sortedNodes[j] == node) { return true; } else if (node < sortedNodes[j]) { n = n / 2; } else { i = j + 1; n = n - n / 2 - 1; } } return false; }
//a recursive function, helper function for insertFragment void LoadGraph::insertFragmentHelp(NodeSet & vs, unsigned int iterIndx, vector<NodeOrtholog>& vfset) { if(iterIndx<vs.size()) { for(unsigned int i=0; i<(*pOrthinfolist)[vs[iterIndx]].size(); i++) { NodeOrtholog vf; vf.orthID=(*pOrthinfolist)[vs[iterIndx]][i]; vf.nodeID=vs[iterIndx]; vfset.push_back(vf); insertFragmentHelp( vs,iterIndx+1, vfset); vfset.pop_back(); } }else insertFragmentTuple( vfset); }
void NodeSetVariableResolver::setVariable(const std::string& name, const NodeSet<std::string>& value) { #if VERBOSE std::cout << std::endl << "Setting " << name << ":" << std::endl; for (size_t i = 0; i < value.size(); i++) { std::cout << value[i].getNodeType() << " | " << value[i] << std::endl; } std::cout << std::endl; #endif _variables[name] = value; #if 0 std::map<std::string, Arabica::XPath::NodeSet<std::string> >::iterator varIter = _variables.begin(); while (varIter != _variables.end()) { std::cout << varIter->first << ":" << std::endl; for (size_t i = 0; i < varIter->second.size(); i++) { std::cout << varIter->second[i].getNodeType() << " | " << varIter->second[i] << std::endl; } varIter++; } #endif }
void XemProcessor::xemFunctionVariable ( __XProcFunctionArgs__ ) { if ( args.size() != 1 ) { throwXemProcessorException("Invalid number of arguments for xem:variable() !"); } NodeSet* ns = args[0]; if ( ns->size() != 1 ) { throwXemProcessorException("Invalid number of nodes for first argument of xem:variable() !"); } if ( ! ns->front().isAttribute() ) { throwXemProcessorException("Argument of xem:variable() is not an attribute !"); } AttributeRef attrRef = ns->front().toAttribute(); KeyId keyId = attrRef.getElement().getAttrAsKeyId(getXProcessor(),attrRef.getKeyId()); Log_XemCommon ( "Selected attr=%x\n", keyId ); NodeSet* variable = getXProcessor().getVariable(keyId); variable->copyTo(result); }
std::string XPathDataModel::evalAsString(const std::string& expr) { XPathValue<std::string> result; try { result = _xpath.evaluate_expr(expr, _doc); } catch(SyntaxException e) { ERROR_EXECUTION_THROW(e.what()); } catch(std::runtime_error e) { ERROR_EXECUTION_THROW(e.what()); } switch (result.type()) { case STRING: return result.asString(); break; case Arabica::XPath::BOOL: // MSVC croaks with ambiguous symbol without qualified name return (result.asBool() ? "true" : "false"); break; case NUMBER: return toStr(result.asNumber()); break; case NODE_SET: { NodeSet<std::string> nodeSet = result.asNodeSet(); std::stringstream ss; for (size_t i = 0; i < nodeSet.size(); i++) { ss << nodeSet[i]; if (nodeSet[i].getNodeType() != Node_base::TEXT_NODE) { ss << std::endl; } } return ss.str(); break; } case ANY: ERROR_EXECUTION_THROW("Type ANY not supported to evaluate as string"); break; } return "undefined"; }
Data XPathDataModel::getStringAsData(const std::string& content) { Data data; XPathValue<std::string> result = _xpath.evaluate_expr(content, _doc); std::stringstream ss; switch (result.type()) { case ANY: break; case Arabica::XPath::BOOL: ss << result.asBool(); break; case NUMBER: ss << result.asNumber(); break; case STRING: ss << result.asString(); break; case NODE_SET: NodeSet<std::string> ns = result.asNodeSet(); for (size_t i = 0; i < ns.size(); i++) { ss.str(""); ss << i; std::string idx = ss.str(); ss.str(""); ss << ns[i]; data.compound[idx] = Data(ss.str(), Data::INTERPRETED); } data.type = Data::INTERPRETED; return data; break; } data.atom = ss.str(); data.type = Data::VERBATIM; return data; }
void InterpreterDraft6::exitInterpreter() { #if VERBOSE std::cout << "Exiting interpreter " << _name << std::endl; #endif NodeSet<std::string> statesToExit = _configuration; statesToExit.forward(false); statesToExit.sort(); for (int i = 0; i < statesToExit.size(); i++) { Arabica::XPath::NodeSet<std::string> onExitElems = filterChildElements(_nsInfo.xmlNSPrefix + "onexit", statesToExit[i]); for (int j = 0; j < onExitElems.size(); j++) { executeContent(onExitElems[j]); } Arabica::XPath::NodeSet<std::string> invokeElems = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", statesToExit[i]); // TODO: we ought to cancel all remaining invokers just to be sure with the persist extension for (int j = 0; j < invokeElems.size(); j++) { cancelInvoke(invokeElems[j]); } if (isFinal(statesToExit[i]) && parentIsScxmlState(statesToExit[i])) { returnDoneEvent(statesToExit[i]); } } _configuration = NodeSet<std::string>(); }
void buildOrthogonalChannelInfo(Router *router, const size_t dim, ShiftSegmentList& segmentList) { if (segmentList.empty()) { // There are no segments, so we can just return now. return; } // Do a sweep to determine space for shifting segments. size_t altDim = (dim + 1) % 2; const size_t n = router->m_obstacles.size(); const size_t cpn = segmentList.size(); // Set up the events for the sweep. size_t totalEvents = 2 * (n + cpn); Event **events = new Event*[totalEvents]; unsigned ctr = 0; ObstacleList::iterator obstacleIt = router->m_obstacles.begin(); for (unsigned i = 0; i < n; i++) { Obstacle *obstacle = *obstacleIt; JunctionRef *junction = dynamic_cast<JunctionRef *> (obstacle); if (junction && ! junction->positionFixed()) { // Junctions that are free to move are not treated as obstacles. ++obstacleIt; totalEvents -= 2; continue; } Box bBox = obstacle->routingBox(); Point min = bBox.min; Point max = bBox.max; double mid = min[dim] + ((max[dim] - min[dim]) / 2); Node *v = new Node(obstacle, mid); events[ctr++] = new Event(Open, v, min[altDim]); events[ctr++] = new Event(Close, v, max[altDim]); ++obstacleIt; } for (ShiftSegmentList::iterator curr = segmentList.begin(); curr != segmentList.end(); ++curr) { const Point& lowPt = (*curr)->lowPoint(); const Point& highPt = (*curr)->highPoint(); COLA_ASSERT(lowPt[dim] == highPt[dim]); COLA_ASSERT(lowPt[altDim] < highPt[altDim]); Node *v = new Node(*curr, lowPt[dim]); events[ctr++] = new Event(SegOpen, v, lowPt[altDim]); events[ctr++] = new Event(SegClose, v, highPt[altDim]); } qsort((Event*)events, (size_t) totalEvents, sizeof(Event*), compare_events); // Process the sweep. // We do multiple passes over sections of the list so we can add relevant // entries to the scanline that might follow, before process them. NodeSet scanline; double thisPos = (totalEvents > 0) ? events[0]->pos : 0; unsigned int posStartIndex = 0; unsigned int posFinishIndex = 0; for (unsigned i = 0; i <= totalEvents; ++i) { // If we have finished the current scanline or all events, then we // process the events on the current scanline in a couple of passes. if ((i == totalEvents) || (events[i]->pos != thisPos)) { posFinishIndex = i; for (int pass = 2; pass <= 4; ++pass) { for (unsigned j = posStartIndex; j < posFinishIndex; ++j) { processShiftEvent(scanline, events[j], dim, pass); } } if (i == totalEvents) { // We have cleaned up, so we can now break out of loop. break; } thisPos = events[i]->pos; posStartIndex = i; } // Do the first sweep event handling -- building the correct // structure of the scanline. const int pass = 1; processShiftEvent(scanline, events[i], dim, pass); } COLA_ASSERT(scanline.size() == 0); for (unsigned i = 0; i < totalEvents; ++i) { delete events[i]; } delete [] events; }
int main(int argc, char** argv) { try { using namespace uscxml; using namespace Arabica::DOM; using namespace Arabica::XPath; const char* xml = "<scxml>" " <state id=\"atomic\" />" " <state id=\"compound\">" " <state id=\"compoundChild1\" />" " <state id=\"compoundChild2\" />" " </state>" " <parallel id=\"parallel\">" " </parallel>" "</scxml>"; Interpreter interpreter = Interpreter::fromXML(xml); assert(interpreter); interpreter.getImpl()->init(); Element<std::string> atomicState = interpreter.getImpl()->getState("atomic"); assert(InterpreterImpl::isAtomic(atomicState)); assert(!InterpreterImpl::isParallel(atomicState)); assert(!InterpreterImpl::isCompound(atomicState)); Element<std::string> compoundState = interpreter.getImpl()->getState("compound"); assert(!InterpreterImpl::isAtomic(compoundState)); assert(!InterpreterImpl::isParallel(compoundState)); assert(InterpreterImpl::isCompound(compoundState)); Element<std::string> parallelState = interpreter.getImpl()->getState("parallel"); assert(!InterpreterImpl::isAtomic(parallelState)); assert(InterpreterImpl::isParallel(parallelState)); assert(!InterpreterImpl::isCompound(parallelState)); // parallel states are not compound! NodeSet<std::string> initialState = interpreter.getImpl()->getInitialStates(); assert(initialState[0] == atomicState); NodeSet<std::string> childs = interpreter.getImpl()->getChildStates(compoundState); Node<std::string> compoundChild1 = interpreter.getImpl()->getState("compoundChild1"); Node<std::string> compoundChild2 = interpreter.getImpl()->getState("compoundChild2"); assert(childs.size() > 0); assert(InterpreterImpl::isMember(compoundChild1, childs)); assert(InterpreterImpl::isMember(compoundChild2, childs)); assert(!InterpreterImpl::isMember(compoundState, childs)); assert(InterpreterImpl::isDescendant(compoundChild1, compoundState)); { std::string idrefs("id1"); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 1); assert(tokenizedIdrefs.front().compare("id1") == 0); } { std::string idrefs(" id1"); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 1); assert(tokenizedIdrefs.front().compare("id1") == 0); } { std::string idrefs(" id1 "); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 1); assert(tokenizedIdrefs.front().compare("id1") == 0); } { std::string idrefs(" \tid1\n "); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 1); assert(tokenizedIdrefs.front().compare("id1") == 0); } { std::string idrefs("id1 id2 id3"); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 3); assert(tokenizedIdrefs.front().compare("id1") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id2") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id3") == 0); } { std::string idrefs("\t id1 \nid2\n\n id3\t"); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 3); assert(tokenizedIdrefs.front().compare("id1") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id2") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id3") == 0); } { std::string idrefs("id1 \nid2 \tid3"); std::list<std::string> tokenizedIdrefs = InterpreterImpl::tokenizeIdRefs(idrefs); assert(tokenizedIdrefs.size() == 3); assert(tokenizedIdrefs.front().compare("id1") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id2") == 0); tokenizedIdrefs.pop_front(); assert(tokenizedIdrefs.front().compare("id3") == 0); } std::string transEvents; transEvents = "error"; assert(InterpreterImpl::nameMatch(transEvents, "error")); assert(!InterpreterImpl::nameMatch(transEvents, "foo")); transEvents = "error foo"; assert(InterpreterImpl::nameMatch(transEvents, "error")); assert(InterpreterImpl::nameMatch(transEvents, "error.send")); assert(InterpreterImpl::nameMatch(transEvents, "error.send.failed")); assert(InterpreterImpl::nameMatch(transEvents, "foo")); assert(InterpreterImpl::nameMatch(transEvents, "foo.bar")); assert(!InterpreterImpl::nameMatch(transEvents, "errors.my.custom")); assert(!InterpreterImpl::nameMatch(transEvents, "errorhandler.mistake")); // is the event name case sensitive? // assert(!InterpreterImpl::nameMatch(transEvents, "errOr.send")); assert(!InterpreterImpl::nameMatch(transEvents, "foobar")); } catch(std::exception e) { std::cout << e.what(); return false; } catch(uscxml::Event e) { std::cout << e; return false; } }
bool moveRelated(){ return moves.size()>0; }